Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp
Line
Count
Source (jump to first uncovered line)
1
//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements semantic analysis for C++ declarations.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/ASTConsumer.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/ASTLambda.h"
16
#include "clang/AST/ASTMutationListener.h"
17
#include "clang/AST/CXXInheritance.h"
18
#include "clang/AST/CharUnits.h"
19
#include "clang/AST/ComparisonCategories.h"
20
#include "clang/AST/DeclCXX.h"
21
#include "clang/AST/DeclTemplate.h"
22
#include "clang/AST/EvaluatedExprVisitor.h"
23
#include "clang/AST/Expr.h"
24
#include "clang/AST/ExprCXX.h"
25
#include "clang/AST/RecordLayout.h"
26
#include "clang/AST/RecursiveASTVisitor.h"
27
#include "clang/AST/StmtVisitor.h"
28
#include "clang/AST/TypeLoc.h"
29
#include "clang/AST/TypeOrdering.h"
30
#include "clang/Basic/AttributeCommonInfo.h"
31
#include "clang/Basic/PartialDiagnostic.h"
32
#include "clang/Basic/Specifiers.h"
33
#include "clang/Basic/TargetInfo.h"
34
#include "clang/Lex/LiteralSupport.h"
35
#include "clang/Lex/Preprocessor.h"
36
#include "clang/Sema/CXXFieldCollector.h"
37
#include "clang/Sema/DeclSpec.h"
38
#include "clang/Sema/EnterExpressionEvaluationContext.h"
39
#include "clang/Sema/Initialization.h"
40
#include "clang/Sema/Lookup.h"
41
#include "clang/Sema/Ownership.h"
42
#include "clang/Sema/ParsedTemplate.h"
43
#include "clang/Sema/Scope.h"
44
#include "clang/Sema/ScopeInfo.h"
45
#include "clang/Sema/SemaInternal.h"
46
#include "clang/Sema/Template.h"
47
#include "llvm/ADT/ArrayRef.h"
48
#include "llvm/ADT/STLExtras.h"
49
#include "llvm/ADT/ScopeExit.h"
50
#include "llvm/ADT/SmallString.h"
51
#include "llvm/ADT/StringExtras.h"
52
#include "llvm/Support/ConvertUTF.h"
53
#include "llvm/Support/SaveAndRestore.h"
54
#include <map>
55
#include <optional>
56
#include <set>
57
58
using namespace clang;
59
60
//===----------------------------------------------------------------------===//
61
// CheckDefaultArgumentVisitor
62
//===----------------------------------------------------------------------===//
63
64
namespace {
65
/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
66
/// the default argument of a parameter to determine whether it
67
/// contains any ill-formed subexpressions. For example, this will
68
/// diagnose the use of local variables or parameters within the
69
/// default argument expression.
70
class CheckDefaultArgumentVisitor
71
    : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
72
  Sema &S;
73
  const Expr *DefaultArg;
74
75
public:
76
  CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
77
0
      : S(S), DefaultArg(DefaultArg) {}
78
79
  bool VisitExpr(const Expr *Node);
80
  bool VisitDeclRefExpr(const DeclRefExpr *DRE);
81
  bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
82
  bool VisitLambdaExpr(const LambdaExpr *Lambda);
83
  bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
84
};
85
86
/// VisitExpr - Visit all of the children of this expression.
87
0
bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
88
0
  bool IsInvalid = false;
89
0
  for (const Stmt *SubStmt : Node->children())
90
0
    if (SubStmt)
91
0
      IsInvalid |= Visit(SubStmt);
92
0
  return IsInvalid;
93
0
}
94
95
/// VisitDeclRefExpr - Visit a reference to a declaration, to
96
/// determine whether this declaration can be used in the default
97
/// argument expression.
98
0
bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
99
0
  const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
100
101
0
  if (!isa<VarDecl, BindingDecl>(Decl))
102
0
    return false;
103
104
0
  if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
105
    // C++ [dcl.fct.default]p9:
106
    //   [...] parameters of a function shall not be used in default
107
    //   argument expressions, even if they are not evaluated. [...]
108
    //
109
    // C++17 [dcl.fct.default]p9 (by CWG 2082):
110
    //   [...] A parameter shall not appear as a potentially-evaluated
111
    //   expression in a default argument. [...]
112
    //
113
0
    if (DRE->isNonOdrUse() != NOUR_Unevaluated)
114
0
      return S.Diag(DRE->getBeginLoc(),
115
0
                    diag::err_param_default_argument_references_param)
116
0
             << Param->getDeclName() << DefaultArg->getSourceRange();
117
0
  } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
118
    // C++ [dcl.fct.default]p7:
119
    //   Local variables shall not be used in default argument
120
    //   expressions.
121
    //
122
    // C++17 [dcl.fct.default]p7 (by CWG 2082):
123
    //   A local variable shall not appear as a potentially-evaluated
124
    //   expression in a default argument.
125
    //
126
    // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
127
    //   Note: A local variable cannot be odr-used (6.3) in a default
128
    //   argument.
129
    //
130
0
    if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
131
0
      return S.Diag(DRE->getBeginLoc(),
132
0
                    diag::err_param_default_argument_references_local)
133
0
             << Decl << DefaultArg->getSourceRange();
134
0
  }
135
0
  return false;
136
0
}
137
138
/// VisitCXXThisExpr - Visit a C++ "this" expression.
139
0
bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
140
  // C++ [dcl.fct.default]p8:
141
  //   The keyword this shall not be used in a default argument of a
142
  //   member function.
143
0
  return S.Diag(ThisE->getBeginLoc(),
144
0
                diag::err_param_default_argument_references_this)
145
0
         << ThisE->getSourceRange();
146
0
}
147
148
bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
149
0
    const PseudoObjectExpr *POE) {
150
0
  bool Invalid = false;
151
0
  for (const Expr *E : POE->semantics()) {
152
    // Look through bindings.
153
0
    if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
154
0
      E = OVE->getSourceExpr();
155
0
      assert(E && "pseudo-object binding without source expression?");
156
0
    }
157
158
0
    Invalid |= Visit(E);
159
0
  }
160
0
  return Invalid;
161
0
}
162
163
0
bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
164
  // [expr.prim.lambda.capture]p9
165
  // a lambda-expression appearing in a default argument cannot implicitly or
166
  // explicitly capture any local entity. Such a lambda-expression can still
167
  // have an init-capture if any full-expression in its initializer satisfies
168
  // the constraints of an expression appearing in a default argument.
169
0
  bool Invalid = false;
170
0
  for (const LambdaCapture &LC : Lambda->captures()) {
171
0
    if (!Lambda->isInitCapture(&LC))
172
0
      return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
173
    // Init captures are always VarDecl.
174
0
    auto *D = cast<VarDecl>(LC.getCapturedVar());
175
0
    Invalid |= Visit(D->getInit());
176
0
  }
177
0
  return Invalid;
178
0
}
179
} // namespace
180
181
void
182
Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
183
0
                                                 const CXXMethodDecl *Method) {
184
  // If we have an MSAny spec already, don't bother.
185
0
  if (!Method || ComputedEST == EST_MSAny)
186
0
    return;
187
188
0
  const FunctionProtoType *Proto
189
0
    = Method->getType()->getAs<FunctionProtoType>();
190
0
  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
191
0
  if (!Proto)
192
0
    return;
193
194
0
  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
195
196
  // If we have a throw-all spec at this point, ignore the function.
197
0
  if (ComputedEST == EST_None)
198
0
    return;
199
200
0
  if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
201
0
    EST = EST_BasicNoexcept;
202
203
0
  switch (EST) {
204
0
  case EST_Unparsed:
205
0
  case EST_Uninstantiated:
206
0
  case EST_Unevaluated:
207
0
    llvm_unreachable("should not see unresolved exception specs here");
208
209
  // If this function can throw any exceptions, make a note of that.
210
0
  case EST_MSAny:
211
0
  case EST_None:
212
    // FIXME: Whichever we see last of MSAny and None determines our result.
213
    // We should make a consistent, order-independent choice here.
214
0
    ClearExceptions();
215
0
    ComputedEST = EST;
216
0
    return;
217
0
  case EST_NoexceptFalse:
218
0
    ClearExceptions();
219
0
    ComputedEST = EST_None;
220
0
    return;
221
  // FIXME: If the call to this decl is using any of its default arguments, we
222
  // need to search them for potentially-throwing calls.
223
  // If this function has a basic noexcept, it doesn't affect the outcome.
224
0
  case EST_BasicNoexcept:
225
0
  case EST_NoexceptTrue:
226
0
  case EST_NoThrow:
227
0
    return;
228
  // If we're still at noexcept(true) and there's a throw() callee,
229
  // change to that specification.
230
0
  case EST_DynamicNone:
231
0
    if (ComputedEST == EST_BasicNoexcept)
232
0
      ComputedEST = EST_DynamicNone;
233
0
    return;
234
0
  case EST_DependentNoexcept:
235
0
    llvm_unreachable(
236
0
        "should not generate implicit declarations for dependent cases");
237
0
  case EST_Dynamic:
238
0
    break;
239
0
  }
240
0
  assert(EST == EST_Dynamic && "EST case not considered earlier.");
241
0
  assert(ComputedEST != EST_None &&
242
0
         "Shouldn't collect exceptions when throw-all is guaranteed.");
243
0
  ComputedEST = EST_Dynamic;
244
  // Record the exceptions in this function's exception specification.
245
0
  for (const auto &E : Proto->exceptions())
246
0
    if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
247
0
      Exceptions.push_back(E);
248
0
}
249
250
0
void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
251
0
  if (!S || ComputedEST == EST_MSAny)
252
0
    return;
253
254
  // FIXME:
255
  //
256
  // C++0x [except.spec]p14:
257
  //   [An] implicit exception-specification specifies the type-id T if and
258
  // only if T is allowed by the exception-specification of a function directly
259
  // invoked by f's implicit definition; f shall allow all exceptions if any
260
  // function it directly invokes allows all exceptions, and f shall allow no
261
  // exceptions if every function it directly invokes allows no exceptions.
262
  //
263
  // Note in particular that if an implicit exception-specification is generated
264
  // for a function containing a throw-expression, that specification can still
265
  // be noexcept(true).
266
  //
267
  // Note also that 'directly invoked' is not defined in the standard, and there
268
  // is no indication that we should only consider potentially-evaluated calls.
269
  //
270
  // Ultimately we should implement the intent of the standard: the exception
271
  // specification should be the set of exceptions which can be thrown by the
272
  // implicit definition. For now, we assume that any non-nothrow expression can
273
  // throw any exception.
274
275
0
  if (Self->canThrow(S))
276
0
    ComputedEST = EST_None;
277
0
}
278
279
ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
280
0
                                             SourceLocation EqualLoc) {
281
0
  if (RequireCompleteType(Param->getLocation(), Param->getType(),
282
0
                          diag::err_typecheck_decl_incomplete_type))
283
0
    return true;
284
285
  // C++ [dcl.fct.default]p5
286
  //   A default argument expression is implicitly converted (clause
287
  //   4) to the parameter type. The default argument expression has
288
  //   the same semantic constraints as the initializer expression in
289
  //   a declaration of a variable of the parameter type, using the
290
  //   copy-initialization semantics (8.5).
291
0
  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
292
0
                                                                    Param);
293
0
  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
294
0
                                                           EqualLoc);
295
0
  InitializationSequence InitSeq(*this, Entity, Kind, Arg);
296
0
  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
297
0
  if (Result.isInvalid())
298
0
    return true;
299
0
  Arg = Result.getAs<Expr>();
300
301
0
  CheckCompletedExpr(Arg, EqualLoc);
302
0
  Arg = MaybeCreateExprWithCleanups(Arg);
303
304
0
  return Arg;
305
0
}
306
307
void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
308
0
                                   SourceLocation EqualLoc) {
309
  // Add the default argument to the parameter
310
0
  Param->setDefaultArg(Arg);
311
312
  // We have already instantiated this parameter; provide each of the
313
  // instantiations with the uninstantiated default argument.
314
0
  UnparsedDefaultArgInstantiationsMap::iterator InstPos
315
0
    = UnparsedDefaultArgInstantiations.find(Param);
316
0
  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
317
0
    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
318
0
      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
319
320
    // We're done tracking this parameter's instantiations.
321
0
    UnparsedDefaultArgInstantiations.erase(InstPos);
322
0
  }
323
0
}
324
325
/// ActOnParamDefaultArgument - Check whether the default argument
326
/// provided for a function parameter is well-formed. If so, attach it
327
/// to the parameter declaration.
328
void
329
Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
330
0
                                Expr *DefaultArg) {
331
0
  if (!param || !DefaultArg)
332
0
    return;
333
334
0
  ParmVarDecl *Param = cast<ParmVarDecl>(param);
335
0
  UnparsedDefaultArgLocs.erase(Param);
336
337
  // Default arguments are only permitted in C++
338
0
  if (!getLangOpts().CPlusPlus) {
339
0
    Diag(EqualLoc, diag::err_param_default_argument)
340
0
      << DefaultArg->getSourceRange();
341
0
    return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
342
0
  }
343
344
  // Check for unexpanded parameter packs.
345
0
  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument))
346
0
    return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
347
348
  // C++11 [dcl.fct.default]p3
349
  //   A default argument expression [...] shall not be specified for a
350
  //   parameter pack.
351
0
  if (Param->isParameterPack()) {
352
0
    Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
353
0
        << DefaultArg->getSourceRange();
354
    // Recover by discarding the default argument.
355
0
    Param->setDefaultArg(nullptr);
356
0
    return;
357
0
  }
358
359
0
  ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
360
0
  if (Result.isInvalid())
361
0
    return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
362
363
0
  DefaultArg = Result.getAs<Expr>();
364
365
  // Check that the default argument is well-formed
366
0
  CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
367
0
  if (DefaultArgChecker.Visit(DefaultArg))
368
0
    return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
369
370
0
  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
371
0
}
372
373
/// ActOnParamUnparsedDefaultArgument - We've seen a default
374
/// argument for a function parameter, but we can't parse it yet
375
/// because we're inside a class definition. Note that this default
376
/// argument will be parsed later.
377
void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
378
                                             SourceLocation EqualLoc,
379
0
                                             SourceLocation ArgLoc) {
380
0
  if (!param)
381
0
    return;
382
383
0
  ParmVarDecl *Param = cast<ParmVarDecl>(param);
384
0
  Param->setUnparsedDefaultArg();
385
0
  UnparsedDefaultArgLocs[Param] = ArgLoc;
386
0
}
387
388
/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
389
/// the default argument for the parameter param failed.
390
void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
391
1
                                          Expr *DefaultArg) {
392
1
  if (!param)
393
0
    return;
394
395
1
  ParmVarDecl *Param = cast<ParmVarDecl>(param);
396
1
  Param->setInvalidDecl();
397
1
  UnparsedDefaultArgLocs.erase(Param);
398
1
  ExprResult RE;
399
1
  if (DefaultArg) {
400
0
    RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
401
0
                            Param->getType().getNonReferenceType());
402
1
  } else {
403
1
    RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
404
1
                            Param->getType().getNonReferenceType());
405
1
  }
406
1
  Param->setDefaultArg(RE.get());
407
1
}
408
409
/// CheckExtraCXXDefaultArguments - Check for any extra default
410
/// arguments in the declarator, which is not a function declaration
411
/// or definition and therefore is not permitted to have default
412
/// arguments. This routine should be invoked for every declarator
413
/// that is not a function declaration or definition.
414
2.58k
void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
415
  // C++ [dcl.fct.default]p3
416
  //   A default argument expression shall be specified only in the
417
  //   parameter-declaration-clause of a function declaration or in a
418
  //   template-parameter (14.1). It shall not be specified for a
419
  //   parameter pack. If it is specified in a
420
  //   parameter-declaration-clause, it shall not occur within a
421
  //   declarator or abstract-declarator of a parameter-declaration.
422
2.58k
  bool MightBeFunction = D.isFunctionDeclarationContext();
423
2.87k
  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
424
284
    DeclaratorChunk &chunk = D.getTypeObject(i);
425
284
    if (chunk.Kind == DeclaratorChunk::Function) {
426
1
      if (MightBeFunction) {
427
        // This is a function declaration. It can have default arguments, but
428
        // keep looking in case its return type is a function type with default
429
        // arguments.
430
1
        MightBeFunction = false;
431
1
        continue;
432
1
      }
433
0
      for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
434
0
           ++argIdx) {
435
0
        ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
436
0
        if (Param->hasUnparsedDefaultArg()) {
437
0
          std::unique_ptr<CachedTokens> Toks =
438
0
              std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
439
0
          SourceRange SR;
440
0
          if (Toks->size() > 1)
441
0
            SR = SourceRange((*Toks)[1].getLocation(),
442
0
                             Toks->back().getLocation());
443
0
          else
444
0
            SR = UnparsedDefaultArgLocs[Param];
445
0
          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
446
0
            << SR;
447
0
        } else if (Param->getDefaultArg()) {
448
0
          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
449
0
            << Param->getDefaultArg()->getSourceRange();
450
0
          Param->setDefaultArg(nullptr);
451
0
        }
452
0
      }
453
283
    } else if (chunk.Kind != DeclaratorChunk::Paren) {
454
235
      MightBeFunction = false;
455
235
    }
456
284
  }
457
2.58k
}
458
459
0
static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
460
0
  return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
461
0
    return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
462
0
  });
463
0
}
464
465
/// MergeCXXFunctionDecl - Merge two declarations of the same C++
466
/// function, once we already know that they have the same
467
/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
468
/// error, false otherwise.
469
bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
470
0
                                Scope *S) {
471
0
  bool Invalid = false;
472
473
  // The declaration context corresponding to the scope is the semantic
474
  // parent, unless this is a local function declaration, in which case
475
  // it is that surrounding function.
476
0
  DeclContext *ScopeDC = New->isLocalExternDecl()
477
0
                             ? New->getLexicalDeclContext()
478
0
                             : New->getDeclContext();
479
480
  // Find the previous declaration for the purpose of default arguments.
481
0
  FunctionDecl *PrevForDefaultArgs = Old;
482
0
  for (/**/; PrevForDefaultArgs;
483
       // Don't bother looking back past the latest decl if this is a local
484
       // extern declaration; nothing else could work.
485
0
       PrevForDefaultArgs = New->isLocalExternDecl()
486
0
                                ? nullptr
487
0
                                : PrevForDefaultArgs->getPreviousDecl()) {
488
    // Ignore hidden declarations.
489
0
    if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
490
0
      continue;
491
492
0
    if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
493
0
        !New->isCXXClassMember()) {
494
      // Ignore default arguments of old decl if they are not in
495
      // the same scope and this is not an out-of-line definition of
496
      // a member function.
497
0
      continue;
498
0
    }
499
500
0
    if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
501
      // If only one of these is a local function declaration, then they are
502
      // declared in different scopes, even though isDeclInScope may think
503
      // they're in the same scope. (If both are local, the scope check is
504
      // sufficient, and if neither is local, then they are in the same scope.)
505
0
      continue;
506
0
    }
507
508
    // We found the right previous declaration.
509
0
    break;
510
0
  }
511
512
  // C++ [dcl.fct.default]p4:
513
  //   For non-template functions, default arguments can be added in
514
  //   later declarations of a function in the same
515
  //   scope. Declarations in different scopes have completely
516
  //   distinct sets of default arguments. That is, declarations in
517
  //   inner scopes do not acquire default arguments from
518
  //   declarations in outer scopes, and vice versa. In a given
519
  //   function declaration, all parameters subsequent to a
520
  //   parameter with a default argument shall have default
521
  //   arguments supplied in this or previous declarations. A
522
  //   default argument shall not be redefined by a later
523
  //   declaration (not even to the same value).
524
  //
525
  // C++ [dcl.fct.default]p6:
526
  //   Except for member functions of class templates, the default arguments
527
  //   in a member function definition that appears outside of the class
528
  //   definition are added to the set of default arguments provided by the
529
  //   member function declaration in the class definition.
530
0
  for (unsigned p = 0, NumParams = PrevForDefaultArgs
531
0
                                       ? PrevForDefaultArgs->getNumParams()
532
0
                                       : 0;
533
0
       p < NumParams; ++p) {
534
0
    ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
535
0
    ParmVarDecl *NewParam = New->getParamDecl(p);
536
537
0
    bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
538
0
    bool NewParamHasDfl = NewParam->hasDefaultArg();
539
540
0
    if (OldParamHasDfl && NewParamHasDfl) {
541
0
      unsigned DiagDefaultParamID =
542
0
        diag::err_param_default_argument_redefinition;
543
544
      // MSVC accepts that default parameters be redefined for member functions
545
      // of template class. The new default parameter's value is ignored.
546
0
      Invalid = true;
547
0
      if (getLangOpts().MicrosoftExt) {
548
0
        CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
549
0
        if (MD && MD->getParent()->getDescribedClassTemplate()) {
550
          // Merge the old default argument into the new parameter.
551
0
          NewParam->setHasInheritedDefaultArg();
552
0
          if (OldParam->hasUninstantiatedDefaultArg())
553
0
            NewParam->setUninstantiatedDefaultArg(
554
0
                                      OldParam->getUninstantiatedDefaultArg());
555
0
          else
556
0
            NewParam->setDefaultArg(OldParam->getInit());
557
0
          DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
558
0
          Invalid = false;
559
0
        }
560
0
      }
561
562
      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
563
      // hint here. Alternatively, we could walk the type-source information
564
      // for NewParam to find the last source location in the type... but it
565
      // isn't worth the effort right now. This is the kind of test case that
566
      // is hard to get right:
567
      //   int f(int);
568
      //   void g(int (*fp)(int) = f);
569
      //   void g(int (*fp)(int) = &f);
570
0
      Diag(NewParam->getLocation(), DiagDefaultParamID)
571
0
        << NewParam->getDefaultArgRange();
572
573
      // Look for the function declaration where the default argument was
574
      // actually written, which may be a declaration prior to Old.
575
0
      for (auto Older = PrevForDefaultArgs;
576
0
           OldParam->hasInheritedDefaultArg(); /**/) {
577
0
        Older = Older->getPreviousDecl();
578
0
        OldParam = Older->getParamDecl(p);
579
0
      }
580
581
0
      Diag(OldParam->getLocation(), diag::note_previous_definition)
582
0
        << OldParam->getDefaultArgRange();
583
0
    } else if (OldParamHasDfl) {
584
      // Merge the old default argument into the new parameter unless the new
585
      // function is a friend declaration in a template class. In the latter
586
      // case the default arguments will be inherited when the friend
587
      // declaration will be instantiated.
588
0
      if (New->getFriendObjectKind() == Decl::FOK_None ||
589
0
          !New->getLexicalDeclContext()->isDependentContext()) {
590
        // It's important to use getInit() here;  getDefaultArg()
591
        // strips off any top-level ExprWithCleanups.
592
0
        NewParam->setHasInheritedDefaultArg();
593
0
        if (OldParam->hasUnparsedDefaultArg())
594
0
          NewParam->setUnparsedDefaultArg();
595
0
        else if (OldParam->hasUninstantiatedDefaultArg())
596
0
          NewParam->setUninstantiatedDefaultArg(
597
0
                                       OldParam->getUninstantiatedDefaultArg());
598
0
        else
599
0
          NewParam->setDefaultArg(OldParam->getInit());
600
0
      }
601
0
    } else if (NewParamHasDfl) {
602
0
      if (New->getDescribedFunctionTemplate()) {
603
        // Paragraph 4, quoted above, only applies to non-template functions.
604
0
        Diag(NewParam->getLocation(),
605
0
             diag::err_param_default_argument_template_redecl)
606
0
          << NewParam->getDefaultArgRange();
607
0
        Diag(PrevForDefaultArgs->getLocation(),
608
0
             diag::note_template_prev_declaration)
609
0
            << false;
610
0
      } else if (New->getTemplateSpecializationKind()
611
0
                   != TSK_ImplicitInstantiation &&
612
0
                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
613
        // C++ [temp.expr.spec]p21:
614
        //   Default function arguments shall not be specified in a declaration
615
        //   or a definition for one of the following explicit specializations:
616
        //     - the explicit specialization of a function template;
617
        //     - the explicit specialization of a member function template;
618
        //     - the explicit specialization of a member function of a class
619
        //       template where the class template specialization to which the
620
        //       member function specialization belongs is implicitly
621
        //       instantiated.
622
0
        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
623
0
          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
624
0
          << New->getDeclName()
625
0
          << NewParam->getDefaultArgRange();
626
0
      } else if (New->getDeclContext()->isDependentContext()) {
627
        // C++ [dcl.fct.default]p6 (DR217):
628
        //   Default arguments for a member function of a class template shall
629
        //   be specified on the initial declaration of the member function
630
        //   within the class template.
631
        //
632
        // Reading the tea leaves a bit in DR217 and its reference to DR205
633
        // leads me to the conclusion that one cannot add default function
634
        // arguments for an out-of-line definition of a member function of a
635
        // dependent type.
636
0
        int WhichKind = 2;
637
0
        if (CXXRecordDecl *Record
638
0
              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
639
0
          if (Record->getDescribedClassTemplate())
640
0
            WhichKind = 0;
641
0
          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
642
0
            WhichKind = 1;
643
0
          else
644
0
            WhichKind = 2;
645
0
        }
646
647
0
        Diag(NewParam->getLocation(),
648
0
             diag::err_param_default_argument_member_template_redecl)
649
0
          << WhichKind
650
0
          << NewParam->getDefaultArgRange();
651
0
      }
652
0
    }
653
0
  }
654
655
  // DR1344: If a default argument is added outside a class definition and that
656
  // default argument makes the function a special member function, the program
657
  // is ill-formed. This can only happen for constructors.
658
0
  if (isa<CXXConstructorDecl>(New) &&
659
0
      New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
660
0
    CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
661
0
                     OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
662
0
    if (NewSM != OldSM) {
663
0
      ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
664
0
      assert(NewParam->hasDefaultArg());
665
0
      Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
666
0
        << NewParam->getDefaultArgRange() << NewSM;
667
0
      Diag(Old->getLocation(), diag::note_previous_declaration);
668
0
    }
669
0
  }
670
671
0
  const FunctionDecl *Def;
672
  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
673
  // template has a constexpr specifier then all its declarations shall
674
  // contain the constexpr specifier.
675
0
  if (New->getConstexprKind() != Old->getConstexprKind()) {
676
0
    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
677
0
        << New << static_cast<int>(New->getConstexprKind())
678
0
        << static_cast<int>(Old->getConstexprKind());
679
0
    Diag(Old->getLocation(), diag::note_previous_declaration);
680
0
    Invalid = true;
681
0
  } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
682
0
             Old->isDefined(Def) &&
683
             // If a friend function is inlined but does not have 'inline'
684
             // specifier, it is a definition. Do not report attribute conflict
685
             // in this case, redefinition will be diagnosed later.
686
0
             (New->isInlineSpecified() ||
687
0
              New->getFriendObjectKind() == Decl::FOK_None)) {
688
    // C++11 [dcl.fcn.spec]p4:
689
    //   If the definition of a function appears in a translation unit before its
690
    //   first declaration as inline, the program is ill-formed.
691
0
    Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
692
0
    Diag(Def->getLocation(), diag::note_previous_definition);
693
0
    Invalid = true;
694
0
  }
695
696
  // C++17 [temp.deduct.guide]p3:
697
  //   Two deduction guide declarations in the same translation unit
698
  //   for the same class template shall not have equivalent
699
  //   parameter-declaration-clauses.
700
0
  if (isa<CXXDeductionGuideDecl>(New) &&
701
0
      !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
702
0
    Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
703
0
    Diag(Old->getLocation(), diag::note_previous_declaration);
704
0
  }
705
706
  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
707
  // argument expression, that declaration shall be a definition and shall be
708
  // the only declaration of the function or function template in the
709
  // translation unit.
710
0
  if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
711
0
      functionDeclHasDefaultArgument(Old)) {
712
0
    Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
713
0
    Diag(Old->getLocation(), diag::note_previous_declaration);
714
0
    Invalid = true;
715
0
  }
716
717
  // C++11 [temp.friend]p4 (DR329):
718
  //   When a function is defined in a friend function declaration in a class
719
  //   template, the function is instantiated when the function is odr-used.
720
  //   The same restrictions on multiple declarations and definitions that
721
  //   apply to non-template function declarations and definitions also apply
722
  //   to these implicit definitions.
723
0
  const FunctionDecl *OldDefinition = nullptr;
724
0
  if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
725
0
      Old->isDefined(OldDefinition, true))
726
0
    CheckForFunctionRedefinition(New, OldDefinition);
727
728
0
  return Invalid;
729
0
}
730
731
0
void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {
732
0
  Diag(Loc, getLangOpts().CPlusPlus26
733
0
                ? diag::warn_cxx23_placeholder_var_definition
734
0
                : diag::ext_placeholder_var_definition);
735
0
}
736
737
NamedDecl *
738
Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
739
0
                                   MultiTemplateParamsArg TemplateParamLists) {
740
0
  assert(D.isDecompositionDeclarator());
741
0
  const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
742
743
  // The syntax only allows a decomposition declarator as a simple-declaration,
744
  // a for-range-declaration, or a condition in Clang, but we parse it in more
745
  // cases than that.
746
0
  if (!D.mayHaveDecompositionDeclarator()) {
747
0
    Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
748
0
      << Decomp.getSourceRange();
749
0
    return nullptr;
750
0
  }
751
752
0
  if (!TemplateParamLists.empty()) {
753
    // FIXME: There's no rule against this, but there are also no rules that
754
    // would actually make it usable, so we reject it for now.
755
0
    Diag(TemplateParamLists.front()->getTemplateLoc(),
756
0
         diag::err_decomp_decl_template);
757
0
    return nullptr;
758
0
  }
759
760
0
  Diag(Decomp.getLSquareLoc(),
761
0
       !getLangOpts().CPlusPlus17
762
0
           ? diag::ext_decomp_decl
763
0
           : D.getContext() == DeclaratorContext::Condition
764
0
                 ? diag::ext_decomp_decl_cond
765
0
                 : diag::warn_cxx14_compat_decomp_decl)
766
0
      << Decomp.getSourceRange();
767
768
  // The semantic context is always just the current context.
769
0
  DeclContext *const DC = CurContext;
770
771
  // C++17 [dcl.dcl]/8:
772
  //   The decl-specifier-seq shall contain only the type-specifier auto
773
  //   and cv-qualifiers.
774
  // C++20 [dcl.dcl]/8:
775
  //   If decl-specifier-seq contains any decl-specifier other than static,
776
  //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
777
  // C++23 [dcl.pre]/6:
778
  //   Each decl-specifier in the decl-specifier-seq shall be static,
779
  //   thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
780
0
  auto &DS = D.getDeclSpec();
781
0
  {
782
    // Note: While constrained-auto needs to be checked, we do so separately so
783
    // we can emit a better diagnostic.
784
0
    SmallVector<StringRef, 8> BadSpecifiers;
785
0
    SmallVector<SourceLocation, 8> BadSpecifierLocs;
786
0
    SmallVector<StringRef, 8> CPlusPlus20Specifiers;
787
0
    SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
788
0
    if (auto SCS = DS.getStorageClassSpec()) {
789
0
      if (SCS == DeclSpec::SCS_static) {
790
0
        CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
791
0
        CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
792
0
      } else {
793
0
        BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
794
0
        BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
795
0
      }
796
0
    }
797
0
    if (auto TSCS = DS.getThreadStorageClassSpec()) {
798
0
      CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
799
0
      CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
800
0
    }
801
0
    if (DS.hasConstexprSpecifier()) {
802
0
      BadSpecifiers.push_back(
803
0
          DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
804
0
      BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
805
0
    }
806
0
    if (DS.isInlineSpecified()) {
807
0
      BadSpecifiers.push_back("inline");
808
0
      BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
809
0
    }
810
811
0
    if (!BadSpecifiers.empty()) {
812
0
      auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
813
0
      Err << (int)BadSpecifiers.size()
814
0
          << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
815
      // Don't add FixItHints to remove the specifiers; we do still respect
816
      // them when building the underlying variable.
817
0
      for (auto Loc : BadSpecifierLocs)
818
0
        Err << SourceRange(Loc, Loc);
819
0
    } else if (!CPlusPlus20Specifiers.empty()) {
820
0
      auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
821
0
                         getLangOpts().CPlusPlus20
822
0
                             ? diag::warn_cxx17_compat_decomp_decl_spec
823
0
                             : diag::ext_decomp_decl_spec);
824
0
      Warn << (int)CPlusPlus20Specifiers.size()
825
0
           << llvm::join(CPlusPlus20Specifiers.begin(),
826
0
                         CPlusPlus20Specifiers.end(), " ");
827
0
      for (auto Loc : CPlusPlus20SpecifierLocs)
828
0
        Warn << SourceRange(Loc, Loc);
829
0
    }
830
    // We can't recover from it being declared as a typedef.
831
0
    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
832
0
      return nullptr;
833
0
  }
834
835
  // C++2a [dcl.struct.bind]p1:
836
  //   A cv that includes volatile is deprecated
837
0
  if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
838
0
      getLangOpts().CPlusPlus20)
839
0
    Diag(DS.getVolatileSpecLoc(),
840
0
         diag::warn_deprecated_volatile_structured_binding);
841
842
0
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
843
0
  QualType R = TInfo->getType();
844
845
0
  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
846
0
                                      UPPC_DeclarationType))
847
0
    D.setInvalidType();
848
849
  // The syntax only allows a single ref-qualifier prior to the decomposition
850
  // declarator. No other declarator chunks are permitted. Also check the type
851
  // specifier here.
852
0
  if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
853
0
      D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
854
0
      (D.getNumTypeObjects() == 1 &&
855
0
       D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
856
0
    Diag(Decomp.getLSquareLoc(),
857
0
         (D.hasGroupingParens() ||
858
0
          (D.getNumTypeObjects() &&
859
0
           D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
860
0
             ? diag::err_decomp_decl_parens
861
0
             : diag::err_decomp_decl_type)
862
0
        << R;
863
864
    // In most cases, there's no actual problem with an explicitly-specified
865
    // type, but a function type won't work here, and ActOnVariableDeclarator
866
    // shouldn't be called for such a type.
867
0
    if (R->isFunctionType())
868
0
      D.setInvalidType();
869
0
  }
870
871
  // Constrained auto is prohibited by [decl.pre]p6, so check that here.
872
0
  if (DS.isConstrainedAuto()) {
873
0
    TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
874
0
    assert(TemplRep->Kind == TNK_Concept_template &&
875
0
           "No other template kind should be possible for a constrained auto");
876
877
0
    SourceRange TemplRange{TemplRep->TemplateNameLoc,
878
0
                           TemplRep->RAngleLoc.isValid()
879
0
                               ? TemplRep->RAngleLoc
880
0
                               : TemplRep->TemplateNameLoc};
881
0
    Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
882
0
        << TemplRange << FixItHint::CreateRemoval(TemplRange);
883
0
  }
884
885
  // Build the BindingDecls.
886
0
  SmallVector<BindingDecl*, 8> Bindings;
887
888
  // Build the BindingDecls.
889
0
  for (auto &B : D.getDecompositionDeclarator().bindings()) {
890
    // Check for name conflicts.
891
0
    DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
892
0
    IdentifierInfo *VarName = B.Name;
893
0
    assert(VarName && "Cannot have an unnamed binding declaration");
894
895
0
    LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
896
0
                          ForVisibleRedeclaration);
897
0
    LookupName(Previous, S,
898
0
               /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
899
900
    // It's not permitted to shadow a template parameter name.
901
0
    if (Previous.isSingleResult() &&
902
0
        Previous.getFoundDecl()->isTemplateParameter()) {
903
0
      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
904
0
                                      Previous.getFoundDecl());
905
0
      Previous.clear();
906
0
    }
907
908
0
    auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, VarName);
909
910
    // Find the shadowed declaration before filtering for scope.
911
0
    NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
912
0
                                  ? getShadowedDeclaration(BD, Previous)
913
0
                                  : nullptr;
914
915
0
    bool ConsiderLinkage = DC->isFunctionOrMethod() &&
916
0
                           DS.getStorageClassSpec() == DeclSpec::SCS_extern;
917
0
    FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
918
0
                         /*AllowInlineNamespace*/false);
919
920
0
    bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
921
0
                         DC->isFunctionOrMethod() && VarName->isPlaceholder();
922
0
    if (!Previous.empty()) {
923
0
      if (IsPlaceholder) {
924
0
        bool sameDC = (Previous.end() - 1)
925
0
                          ->getDeclContext()
926
0
                          ->getRedeclContext()
927
0
                          ->Equals(DC->getRedeclContext());
928
0
        if (sameDC &&
929
0
            isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
930
0
          Previous.clear();
931
0
          DiagPlaceholderVariableDefinition(B.NameLoc);
932
0
        }
933
0
      } else {
934
0
        auto *Old = Previous.getRepresentativeDecl();
935
0
        Diag(B.NameLoc, diag::err_redefinition) << B.Name;
936
0
        Diag(Old->getLocation(), diag::note_previous_definition);
937
0
      }
938
0
    } else if (ShadowedDecl && !D.isRedeclaration()) {
939
0
      CheckShadow(BD, ShadowedDecl, Previous);
940
0
    }
941
0
    PushOnScopeChains(BD, S, true);
942
0
    Bindings.push_back(BD);
943
0
    ParsingInitForAutoVars.insert(BD);
944
0
  }
945
946
  // There are no prior lookup results for the variable itself, because it
947
  // is unnamed.
948
0
  DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
949
0
                               Decomp.getLSquareLoc());
950
0
  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
951
0
                        ForVisibleRedeclaration);
952
953
  // Build the variable that holds the non-decomposed object.
954
0
  bool AddToScope = true;
955
0
  NamedDecl *New =
956
0
      ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
957
0
                              MultiTemplateParamsArg(), AddToScope, Bindings);
958
0
  if (AddToScope) {
959
0
    S->AddDecl(New);
960
0
    CurContext->addHiddenDecl(New);
961
0
  }
962
963
0
  if (isInOpenMPDeclareTargetContext())
964
0
    checkDeclIsAllowedInOpenMPTarget(nullptr, New);
965
966
0
  return New;
967
0
}
968
969
static bool checkSimpleDecomposition(
970
    Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
971
    QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
972
0
    llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
973
0
  if ((int64_t)Bindings.size() != NumElems) {
974
0
    S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
975
0
        << DecompType << (unsigned)Bindings.size()
976
0
        << (unsigned)NumElems.getLimitedValue(UINT_MAX)
977
0
        << toString(NumElems, 10) << (NumElems < Bindings.size());
978
0
    return true;
979
0
  }
980
981
0
  unsigned I = 0;
982
0
  for (auto *B : Bindings) {
983
0
    SourceLocation Loc = B->getLocation();
984
0
    ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
985
0
    if (E.isInvalid())
986
0
      return true;
987
0
    E = GetInit(Loc, E.get(), I++);
988
0
    if (E.isInvalid())
989
0
      return true;
990
0
    B->setBinding(ElemType, E.get());
991
0
  }
992
993
0
  return false;
994
0
}
995
996
static bool checkArrayLikeDecomposition(Sema &S,
997
                                        ArrayRef<BindingDecl *> Bindings,
998
                                        ValueDecl *Src, QualType DecompType,
999
                                        const llvm::APSInt &NumElems,
1000
0
                                        QualType ElemType) {
1001
0
  return checkSimpleDecomposition(
1002
0
      S, Bindings, Src, DecompType, NumElems, ElemType,
1003
0
      [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1004
0
        ExprResult E = S.ActOnIntegerConstant(Loc, I);
1005
0
        if (E.isInvalid())
1006
0
          return ExprError();
1007
0
        return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1008
0
      });
1009
0
}
1010
1011
static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1012
                                    ValueDecl *Src, QualType DecompType,
1013
0
                                    const ConstantArrayType *CAT) {
1014
0
  return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1015
0
                                     llvm::APSInt(CAT->getSize()),
1016
0
                                     CAT->getElementType());
1017
0
}
1018
1019
static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1020
                                     ValueDecl *Src, QualType DecompType,
1021
0
                                     const VectorType *VT) {
1022
0
  return checkArrayLikeDecomposition(
1023
0
      S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1024
0
      S.Context.getQualifiedType(VT->getElementType(),
1025
0
                                 DecompType.getQualifiers()));
1026
0
}
1027
1028
static bool checkComplexDecomposition(Sema &S,
1029
                                      ArrayRef<BindingDecl *> Bindings,
1030
                                      ValueDecl *Src, QualType DecompType,
1031
0
                                      const ComplexType *CT) {
1032
0
  return checkSimpleDecomposition(
1033
0
      S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1034
0
      S.Context.getQualifiedType(CT->getElementType(),
1035
0
                                 DecompType.getQualifiers()),
1036
0
      [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1037
0
        return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1038
0
      });
1039
0
}
1040
1041
static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1042
                                     TemplateArgumentListInfo &Args,
1043
0
                                     const TemplateParameterList *Params) {
1044
0
  SmallString<128> SS;
1045
0
  llvm::raw_svector_ostream OS(SS);
1046
0
  bool First = true;
1047
0
  unsigned I = 0;
1048
0
  for (auto &Arg : Args.arguments()) {
1049
0
    if (!First)
1050
0
      OS << ", ";
1051
0
    Arg.getArgument().print(PrintingPolicy, OS,
1052
0
                            TemplateParameterList::shouldIncludeTypeForArgument(
1053
0
                                PrintingPolicy, Params, I));
1054
0
    First = false;
1055
0
    I++;
1056
0
  }
1057
0
  return std::string(OS.str());
1058
0
}
1059
1060
static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1061
                                     SourceLocation Loc, StringRef Trait,
1062
                                     TemplateArgumentListInfo &Args,
1063
0
                                     unsigned DiagID) {
1064
0
  auto DiagnoseMissing = [&] {
1065
0
    if (DiagID)
1066
0
      S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1067
0
                                               Args, /*Params*/ nullptr);
1068
0
    return true;
1069
0
  };
1070
1071
  // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1072
0
  NamespaceDecl *Std = S.getStdNamespace();
1073
0
  if (!Std)
1074
0
    return DiagnoseMissing();
1075
1076
  // Look up the trait itself, within namespace std. We can diagnose various
1077
  // problems with this lookup even if we've been asked to not diagnose a
1078
  // missing specialization, because this can only fail if the user has been
1079
  // declaring their own names in namespace std or we don't support the
1080
  // standard library implementation in use.
1081
0
  LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1082
0
                      Loc, Sema::LookupOrdinaryName);
1083
0
  if (!S.LookupQualifiedName(Result, Std))
1084
0
    return DiagnoseMissing();
1085
0
  if (Result.isAmbiguous())
1086
0
    return true;
1087
1088
0
  ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1089
0
  if (!TraitTD) {
1090
0
    Result.suppressDiagnostics();
1091
0
    NamedDecl *Found = *Result.begin();
1092
0
    S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1093
0
    S.Diag(Found->getLocation(), diag::note_declared_at);
1094
0
    return true;
1095
0
  }
1096
1097
  // Build the template-id.
1098
0
  QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1099
0
  if (TraitTy.isNull())
1100
0
    return true;
1101
0
  if (!S.isCompleteType(Loc, TraitTy)) {
1102
0
    if (DiagID)
1103
0
      S.RequireCompleteType(
1104
0
          Loc, TraitTy, DiagID,
1105
0
          printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1106
0
                            TraitTD->getTemplateParameters()));
1107
0
    return true;
1108
0
  }
1109
1110
0
  CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1111
0
  assert(RD && "specialization of class template is not a class?");
1112
1113
  // Look up the member of the trait type.
1114
0
  S.LookupQualifiedName(TraitMemberLookup, RD);
1115
0
  return TraitMemberLookup.isAmbiguous();
1116
0
}
1117
1118
static TemplateArgumentLoc
1119
getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1120
0
                                   uint64_t I) {
1121
0
  TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1122
0
  return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1123
0
}
1124
1125
static TemplateArgumentLoc
1126
0
getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1127
0
  return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1128
0
}
1129
1130
namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1131
1132
static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1133
0
                               llvm::APSInt &Size) {
1134
0
  EnterExpressionEvaluationContext ContextRAII(
1135
0
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1136
1137
0
  DeclarationName Value = S.PP.getIdentifierInfo("value");
1138
0
  LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1139
1140
  // Form template argument list for tuple_size<T>.
1141
0
  TemplateArgumentListInfo Args(Loc, Loc);
1142
0
  Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1143
1144
  // If there's no tuple_size specialization or the lookup of 'value' is empty,
1145
  // it's not tuple-like.
1146
0
  if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1147
0
      R.empty())
1148
0
    return IsTupleLike::NotTupleLike;
1149
1150
  // If we get this far, we've committed to the tuple interpretation, but
1151
  // we can still fail if there actually isn't a usable ::value.
1152
1153
0
  struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1154
0
    LookupResult &R;
1155
0
    TemplateArgumentListInfo &Args;
1156
0
    ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1157
0
        : R(R), Args(Args) {}
1158
0
    Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1159
0
                                               SourceLocation Loc) override {
1160
0
      return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1161
0
             << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1162
0
                                  /*Params*/ nullptr);
1163
0
    }
1164
0
  } Diagnoser(R, Args);
1165
1166
0
  ExprResult E =
1167
0
      S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1168
0
  if (E.isInvalid())
1169
0
    return IsTupleLike::Error;
1170
1171
0
  E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1172
0
  if (E.isInvalid())
1173
0
    return IsTupleLike::Error;
1174
1175
0
  return IsTupleLike::TupleLike;
1176
0
}
1177
1178
/// \return std::tuple_element<I, T>::type.
1179
static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1180
0
                                        unsigned I, QualType T) {
1181
  // Form template argument list for tuple_element<I, T>.
1182
0
  TemplateArgumentListInfo Args(Loc, Loc);
1183
0
  Args.addArgument(
1184
0
      getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1185
0
  Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1186
1187
0
  DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1188
0
  LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1189
0
  if (lookupStdTypeTraitMember(
1190
0
          S, R, Loc, "tuple_element", Args,
1191
0
          diag::err_decomp_decl_std_tuple_element_not_specialized))
1192
0
    return QualType();
1193
1194
0
  auto *TD = R.getAsSingle<TypeDecl>();
1195
0
  if (!TD) {
1196
0
    R.suppressDiagnostics();
1197
0
    S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1198
0
        << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1199
0
                             /*Params*/ nullptr);
1200
0
    if (!R.empty())
1201
0
      S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1202
0
    return QualType();
1203
0
  }
1204
1205
0
  return S.Context.getTypeDeclType(TD);
1206
0
}
1207
1208
namespace {
1209
struct InitializingBinding {
1210
  Sema &S;
1211
0
  InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1212
0
    Sema::CodeSynthesisContext Ctx;
1213
0
    Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1214
0
    Ctx.PointOfInstantiation = BD->getLocation();
1215
0
    Ctx.Entity = BD;
1216
0
    S.pushCodeSynthesisContext(Ctx);
1217
0
  }
1218
0
  ~InitializingBinding() {
1219
0
    S.popCodeSynthesisContext();
1220
0
  }
1221
};
1222
}
1223
1224
static bool checkTupleLikeDecomposition(Sema &S,
1225
                                        ArrayRef<BindingDecl *> Bindings,
1226
                                        VarDecl *Src, QualType DecompType,
1227
0
                                        const llvm::APSInt &TupleSize) {
1228
0
  if ((int64_t)Bindings.size() != TupleSize) {
1229
0
    S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1230
0
        << DecompType << (unsigned)Bindings.size()
1231
0
        << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1232
0
        << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1233
0
    return true;
1234
0
  }
1235
1236
0
  if (Bindings.empty())
1237
0
    return false;
1238
1239
0
  DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1240
1241
  // [dcl.decomp]p3:
1242
  //   The unqualified-id get is looked up in the scope of E by class member
1243
  //   access lookup ...
1244
0
  LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1245
0
  bool UseMemberGet = false;
1246
0
  if (S.isCompleteType(Src->getLocation(), DecompType)) {
1247
0
    if (auto *RD = DecompType->getAsCXXRecordDecl())
1248
0
      S.LookupQualifiedName(MemberGet, RD);
1249
0
    if (MemberGet.isAmbiguous())
1250
0
      return true;
1251
    //   ... and if that finds at least one declaration that is a function
1252
    //   template whose first template parameter is a non-type parameter ...
1253
0
    for (NamedDecl *D : MemberGet) {
1254
0
      if (FunctionTemplateDecl *FTD =
1255
0
              dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1256
0
        TemplateParameterList *TPL = FTD->getTemplateParameters();
1257
0
        if (TPL->size() != 0 &&
1258
0
            isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1259
          //   ... the initializer is e.get<i>().
1260
0
          UseMemberGet = true;
1261
0
          break;
1262
0
        }
1263
0
      }
1264
0
    }
1265
0
  }
1266
1267
0
  unsigned I = 0;
1268
0
  for (auto *B : Bindings) {
1269
0
    InitializingBinding InitContext(S, B);
1270
0
    SourceLocation Loc = B->getLocation();
1271
1272
0
    ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1273
0
    if (E.isInvalid())
1274
0
      return true;
1275
1276
    //   e is an lvalue if the type of the entity is an lvalue reference and
1277
    //   an xvalue otherwise
1278
0
    if (!Src->getType()->isLValueReferenceType())
1279
0
      E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1280
0
                                   E.get(), nullptr, VK_XValue,
1281
0
                                   FPOptionsOverride());
1282
1283
0
    TemplateArgumentListInfo Args(Loc, Loc);
1284
0
    Args.addArgument(
1285
0
        getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1286
1287
0
    if (UseMemberGet) {
1288
      //   if [lookup of member get] finds at least one declaration, the
1289
      //   initializer is e.get<i-1>().
1290
0
      E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1291
0
                                     CXXScopeSpec(), SourceLocation(), nullptr,
1292
0
                                     MemberGet, &Args, nullptr);
1293
0
      if (E.isInvalid())
1294
0
        return true;
1295
1296
0
      E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);
1297
0
    } else {
1298
      //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1299
      //   in the associated namespaces.
1300
0
      Expr *Get = UnresolvedLookupExpr::Create(
1301
0
          S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1302
0
          DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/ true, &Args,
1303
0
          UnresolvedSetIterator(), UnresolvedSetIterator(),
1304
0
          /*KnownDependent=*/false);
1305
1306
0
      Expr *Arg = E.get();
1307
0
      E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1308
0
    }
1309
0
    if (E.isInvalid())
1310
0
      return true;
1311
0
    Expr *Init = E.get();
1312
1313
    //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1314
0
    QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1315
0
    if (T.isNull())
1316
0
      return true;
1317
1318
    //   each vi is a variable of type "reference to T" initialized with the
1319
    //   initializer, where the reference is an lvalue reference if the
1320
    //   initializer is an lvalue and an rvalue reference otherwise
1321
0
    QualType RefType =
1322
0
        S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1323
0
    if (RefType.isNull())
1324
0
      return true;
1325
0
    auto *RefVD = VarDecl::Create(
1326
0
        S.Context, Src->getDeclContext(), Loc, Loc,
1327
0
        B->getDeclName().getAsIdentifierInfo(), RefType,
1328
0
        S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1329
0
    RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1330
0
    RefVD->setTSCSpec(Src->getTSCSpec());
1331
0
    RefVD->setImplicit();
1332
0
    if (Src->isInlineSpecified())
1333
0
      RefVD->setInlineSpecified();
1334
0
    RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1335
1336
0
    InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1337
0
    InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1338
0
    InitializationSequence Seq(S, Entity, Kind, Init);
1339
0
    E = Seq.Perform(S, Entity, Kind, Init);
1340
0
    if (E.isInvalid())
1341
0
      return true;
1342
0
    E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1343
0
    if (E.isInvalid())
1344
0
      return true;
1345
0
    RefVD->setInit(E.get());
1346
0
    S.CheckCompleteVariableDeclaration(RefVD);
1347
1348
0
    E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1349
0
                                   DeclarationNameInfo(B->getDeclName(), Loc),
1350
0
                                   RefVD);
1351
0
    if (E.isInvalid())
1352
0
      return true;
1353
1354
0
    B->setBinding(T, E.get());
1355
0
    I++;
1356
0
  }
1357
1358
0
  return false;
1359
0
}
1360
1361
/// Find the base class to decompose in a built-in decomposition of a class type.
1362
/// This base class search is, unfortunately, not quite like any other that we
1363
/// perform anywhere else in C++.
1364
static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1365
                                                const CXXRecordDecl *RD,
1366
0
                                                CXXCastPath &BasePath) {
1367
0
  auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1368
0
                          CXXBasePath &Path) {
1369
0
    return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1370
0
  };
1371
1372
0
  const CXXRecordDecl *ClassWithFields = nullptr;
1373
0
  AccessSpecifier AS = AS_public;
1374
0
  if (RD->hasDirectFields())
1375
    // [dcl.decomp]p4:
1376
    //   Otherwise, all of E's non-static data members shall be public direct
1377
    //   members of E ...
1378
0
    ClassWithFields = RD;
1379
0
  else {
1380
    //   ... or of ...
1381
0
    CXXBasePaths Paths;
1382
0
    Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1383
0
    if (!RD->lookupInBases(BaseHasFields, Paths)) {
1384
      // If no classes have fields, just decompose RD itself. (This will work
1385
      // if and only if zero bindings were provided.)
1386
0
      return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1387
0
    }
1388
1389
0
    CXXBasePath *BestPath = nullptr;
1390
0
    for (auto &P : Paths) {
1391
0
      if (!BestPath)
1392
0
        BestPath = &P;
1393
0
      else if (!S.Context.hasSameType(P.back().Base->getType(),
1394
0
                                      BestPath->back().Base->getType())) {
1395
        //   ... the same ...
1396
0
        S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1397
0
          << false << RD << BestPath->back().Base->getType()
1398
0
          << P.back().Base->getType();
1399
0
        return DeclAccessPair();
1400
0
      } else if (P.Access < BestPath->Access) {
1401
0
        BestPath = &P;
1402
0
      }
1403
0
    }
1404
1405
    //   ... unambiguous ...
1406
0
    QualType BaseType = BestPath->back().Base->getType();
1407
0
    if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1408
0
      S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1409
0
        << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1410
0
      return DeclAccessPair();
1411
0
    }
1412
1413
    //   ... [accessible, implied by other rules] base class of E.
1414
0
    S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1415
0
                           *BestPath, diag::err_decomp_decl_inaccessible_base);
1416
0
    AS = BestPath->Access;
1417
1418
0
    ClassWithFields = BaseType->getAsCXXRecordDecl();
1419
0
    S.BuildBasePathArray(Paths, BasePath);
1420
0
  }
1421
1422
  // The above search did not check whether the selected class itself has base
1423
  // classes with fields, so check that now.
1424
0
  CXXBasePaths Paths;
1425
0
  if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1426
0
    S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1427
0
      << (ClassWithFields == RD) << RD << ClassWithFields
1428
0
      << Paths.front().back().Base->getType();
1429
0
    return DeclAccessPair();
1430
0
  }
1431
1432
0
  return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1433
0
}
1434
1435
static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1436
                                     ValueDecl *Src, QualType DecompType,
1437
0
                                     const CXXRecordDecl *OrigRD) {
1438
0
  if (S.RequireCompleteType(Src->getLocation(), DecompType,
1439
0
                            diag::err_incomplete_type))
1440
0
    return true;
1441
1442
0
  CXXCastPath BasePath;
1443
0
  DeclAccessPair BasePair =
1444
0
      findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1445
0
  const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1446
0
  if (!RD)
1447
0
    return true;
1448
0
  QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1449
0
                                                 DecompType.getQualifiers());
1450
1451
0
  auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1452
0
    unsigned NumFields = llvm::count_if(
1453
0
        RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1454
0
    assert(Bindings.size() != NumFields);
1455
0
    S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1456
0
        << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1457
0
        << (NumFields < Bindings.size());
1458
0
    return true;
1459
0
  };
1460
1461
  //   all of E's non-static data members shall be [...] well-formed
1462
  //   when named as e.name in the context of the structured binding,
1463
  //   E shall not have an anonymous union member, ...
1464
0
  unsigned I = 0;
1465
0
  for (auto *FD : RD->fields()) {
1466
0
    if (FD->isUnnamedBitfield())
1467
0
      continue;
1468
1469
    // All the non-static data members are required to be nameable, so they
1470
    // must all have names.
1471
0
    if (!FD->getDeclName()) {
1472
0
      if (RD->isLambda()) {
1473
0
        S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1474
0
        S.Diag(RD->getLocation(), diag::note_lambda_decl);
1475
0
        return true;
1476
0
      }
1477
1478
0
      if (FD->isAnonymousStructOrUnion()) {
1479
0
        S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1480
0
          << DecompType << FD->getType()->isUnionType();
1481
0
        S.Diag(FD->getLocation(), diag::note_declared_at);
1482
0
        return true;
1483
0
      }
1484
1485
      // FIXME: Are there any other ways we could have an anonymous member?
1486
0
    }
1487
1488
    // We have a real field to bind.
1489
0
    if (I >= Bindings.size())
1490
0
      return DiagnoseBadNumberOfBindings();
1491
0
    auto *B = Bindings[I++];
1492
0
    SourceLocation Loc = B->getLocation();
1493
1494
    // The field must be accessible in the context of the structured binding.
1495
    // We already checked that the base class is accessible.
1496
    // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1497
    // const_cast here.
1498
0
    S.CheckStructuredBindingMemberAccess(
1499
0
        Loc, const_cast<CXXRecordDecl *>(OrigRD),
1500
0
        DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1501
0
                                     BasePair.getAccess(), FD->getAccess())));
1502
1503
    // Initialize the binding to Src.FD.
1504
0
    ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1505
0
    if (E.isInvalid())
1506
0
      return true;
1507
0
    E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1508
0
                            VK_LValue, &BasePath);
1509
0
    if (E.isInvalid())
1510
0
      return true;
1511
0
    E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1512
0
                                  CXXScopeSpec(), FD,
1513
0
                                  DeclAccessPair::make(FD, FD->getAccess()),
1514
0
                                  DeclarationNameInfo(FD->getDeclName(), Loc));
1515
0
    if (E.isInvalid())
1516
0
      return true;
1517
1518
    // If the type of the member is T, the referenced type is cv T, where cv is
1519
    // the cv-qualification of the decomposition expression.
1520
    //
1521
    // FIXME: We resolve a defect here: if the field is mutable, we do not add
1522
    // 'const' to the type of the field.
1523
0
    Qualifiers Q = DecompType.getQualifiers();
1524
0
    if (FD->isMutable())
1525
0
      Q.removeConst();
1526
0
    B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1527
0
  }
1528
1529
0
  if (I != Bindings.size())
1530
0
    return DiagnoseBadNumberOfBindings();
1531
1532
0
  return false;
1533
0
}
1534
1535
0
void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1536
0
  QualType DecompType = DD->getType();
1537
1538
  // If the type of the decomposition is dependent, then so is the type of
1539
  // each binding.
1540
0
  if (DecompType->isDependentType()) {
1541
0
    for (auto *B : DD->bindings())
1542
0
      B->setType(Context.DependentTy);
1543
0
    return;
1544
0
  }
1545
1546
0
  DecompType = DecompType.getNonReferenceType();
1547
0
  ArrayRef<BindingDecl*> Bindings = DD->bindings();
1548
1549
  // C++1z [dcl.decomp]/2:
1550
  //   If E is an array type [...]
1551
  // As an extension, we also support decomposition of built-in complex and
1552
  // vector types.
1553
0
  if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1554
0
    if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1555
0
      DD->setInvalidDecl();
1556
0
    return;
1557
0
  }
1558
0
  if (auto *VT = DecompType->getAs<VectorType>()) {
1559
0
    if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1560
0
      DD->setInvalidDecl();
1561
0
    return;
1562
0
  }
1563
0
  if (auto *CT = DecompType->getAs<ComplexType>()) {
1564
0
    if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1565
0
      DD->setInvalidDecl();
1566
0
    return;
1567
0
  }
1568
1569
  // C++1z [dcl.decomp]/3:
1570
  //   if the expression std::tuple_size<E>::value is a well-formed integral
1571
  //   constant expression, [...]
1572
0
  llvm::APSInt TupleSize(32);
1573
0
  switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1574
0
  case IsTupleLike::Error:
1575
0
    DD->setInvalidDecl();
1576
0
    return;
1577
1578
0
  case IsTupleLike::TupleLike:
1579
0
    if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1580
0
      DD->setInvalidDecl();
1581
0
    return;
1582
1583
0
  case IsTupleLike::NotTupleLike:
1584
0
    break;
1585
0
  }
1586
1587
  // C++1z [dcl.dcl]/8:
1588
  //   [E shall be of array or non-union class type]
1589
0
  CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1590
0
  if (!RD || RD->isUnion()) {
1591
0
    Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1592
0
        << DD << !RD << DecompType;
1593
0
    DD->setInvalidDecl();
1594
0
    return;
1595
0
  }
1596
1597
  // C++1z [dcl.decomp]/4:
1598
  //   all of E's non-static data members shall be [...] direct members of
1599
  //   E or of the same unambiguous public base class of E, ...
1600
0
  if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1601
0
    DD->setInvalidDecl();
1602
0
}
1603
1604
/// Merge the exception specifications of two variable declarations.
1605
///
1606
/// This is called when there's a redeclaration of a VarDecl. The function
1607
/// checks if the redeclaration might have an exception specification and
1608
/// validates compatibility and merges the specs if necessary.
1609
0
void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1610
  // Shortcut if exceptions are disabled.
1611
0
  if (!getLangOpts().CXXExceptions)
1612
0
    return;
1613
1614
0
  assert(Context.hasSameType(New->getType(), Old->getType()) &&
1615
0
         "Should only be called if types are otherwise the same.");
1616
1617
0
  QualType NewType = New->getType();
1618
0
  QualType OldType = Old->getType();
1619
1620
  // We're only interested in pointers and references to functions, as well
1621
  // as pointers to member functions.
1622
0
  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1623
0
    NewType = R->getPointeeType();
1624
0
    OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1625
0
  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1626
0
    NewType = P->getPointeeType();
1627
0
    OldType = OldType->castAs<PointerType>()->getPointeeType();
1628
0
  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1629
0
    NewType = M->getPointeeType();
1630
0
    OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1631
0
  }
1632
1633
0
  if (!NewType->isFunctionProtoType())
1634
0
    return;
1635
1636
  // There's lots of special cases for functions. For function pointers, system
1637
  // libraries are hopefully not as broken so that we don't need these
1638
  // workarounds.
1639
0
  if (CheckEquivalentExceptionSpec(
1640
0
        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1641
0
        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1642
0
    New->setInvalidDecl();
1643
0
  }
1644
0
}
1645
1646
/// CheckCXXDefaultArguments - Verify that the default arguments for a
1647
/// function declaration are well-formed according to C++
1648
/// [dcl.fct.default].
1649
0
void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1650
0
  unsigned NumParams = FD->getNumParams();
1651
0
  unsigned ParamIdx = 0;
1652
1653
  // This checking doesn't make sense for explicit specializations; their
1654
  // default arguments are determined by the declaration we're specializing,
1655
  // not by FD.
1656
0
  if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1657
0
    return;
1658
0
  if (auto *FTD = FD->getDescribedFunctionTemplate())
1659
0
    if (FTD->isMemberSpecialization())
1660
0
      return;
1661
1662
  // Find first parameter with a default argument
1663
0
  for (; ParamIdx < NumParams; ++ParamIdx) {
1664
0
    ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1665
0
    if (Param->hasDefaultArg())
1666
0
      break;
1667
0
  }
1668
1669
  // C++20 [dcl.fct.default]p4:
1670
  //   In a given function declaration, each parameter subsequent to a parameter
1671
  //   with a default argument shall have a default argument supplied in this or
1672
  //   a previous declaration, unless the parameter was expanded from a
1673
  //   parameter pack, or shall be a function parameter pack.
1674
0
  for (; ParamIdx < NumParams; ++ParamIdx) {
1675
0
    ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1676
0
    if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1677
0
        !(CurrentInstantiationScope &&
1678
0
          CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1679
0
      if (Param->isInvalidDecl())
1680
0
        /* We already complained about this parameter. */;
1681
0
      else if (Param->getIdentifier())
1682
0
        Diag(Param->getLocation(),
1683
0
             diag::err_param_default_argument_missing_name)
1684
0
          << Param->getIdentifier();
1685
0
      else
1686
0
        Diag(Param->getLocation(),
1687
0
             diag::err_param_default_argument_missing);
1688
0
    }
1689
0
  }
1690
0
}
1691
1692
/// Check that the given type is a literal type. Issue a diagnostic if not,
1693
/// if Kind is Diagnose.
1694
/// \return \c true if a problem has been found (and optionally diagnosed).
1695
template <typename... Ts>
1696
static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1697
                             SourceLocation Loc, QualType T, unsigned DiagID,
1698
0
                             Ts &&...DiagArgs) {
1699
0
  if (T->isDependentType())
1700
0
    return false;
1701
1702
0
  switch (Kind) {
1703
0
  case Sema::CheckConstexprKind::Diagnose:
1704
0
    return SemaRef.RequireLiteralType(Loc, T, DiagID,
1705
0
                                      std::forward<Ts>(DiagArgs)...);
1706
1707
0
  case Sema::CheckConstexprKind::CheckValid:
1708
0
    return !T->isLiteralType(SemaRef.Context);
1709
0
  }
1710
1711
0
  llvm_unreachable("unknown CheckConstexprKind");
1712
0
}
Unexecuted instantiation: SemaDeclCXX.cpp:bool CheckLiteralType<bool>(clang::Sema&, clang::Sema::CheckConstexprKind, clang::SourceLocation, clang::QualType, unsigned int, bool&&)
Unexecuted instantiation: SemaDeclCXX.cpp:bool CheckLiteralType<unsigned int, clang::SourceRange, bool, bool>(clang::Sema&, clang::Sema::CheckConstexprKind, clang::SourceLocation, clang::QualType, unsigned int, unsigned int&&, clang::SourceRange&&, bool&&, bool&&)
Unexecuted instantiation: SemaDeclCXX.cpp:bool CheckLiteralType<bool, int>(clang::Sema&, clang::Sema::CheckConstexprKind, clang::SourceLocation, clang::QualType, unsigned int, bool&&, int&&)
1713
1714
/// Determine whether a destructor cannot be constexpr due to
1715
static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1716
                                               const CXXDestructorDecl *DD,
1717
0
                                               Sema::CheckConstexprKind Kind) {
1718
0
  auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1719
0
    const CXXRecordDecl *RD =
1720
0
        T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1721
0
    if (!RD || RD->hasConstexprDestructor())
1722
0
      return true;
1723
1724
0
    if (Kind == Sema::CheckConstexprKind::Diagnose) {
1725
0
      SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1726
0
          << static_cast<int>(DD->getConstexprKind()) << !FD
1727
0
          << (FD ? FD->getDeclName() : DeclarationName()) << T;
1728
0
      SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1729
0
          << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1730
0
    }
1731
0
    return false;
1732
0
  };
1733
1734
0
  const CXXRecordDecl *RD = DD->getParent();
1735
0
  for (const CXXBaseSpecifier &B : RD->bases())
1736
0
    if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1737
0
      return false;
1738
0
  for (const FieldDecl *FD : RD->fields())
1739
0
    if (!Check(FD->getLocation(), FD->getType(), FD))
1740
0
      return false;
1741
0
  return true;
1742
0
}
1743
1744
/// Check whether a function's parameter types are all literal types. If so,
1745
/// return true. If not, produce a suitable diagnostic and return false.
1746
static bool CheckConstexprParameterTypes(Sema &SemaRef,
1747
                                         const FunctionDecl *FD,
1748
0
                                         Sema::CheckConstexprKind Kind) {
1749
0
  unsigned ArgIndex = 0;
1750
0
  const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1751
0
  for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1752
0
                                              e = FT->param_type_end();
1753
0
       i != e; ++i, ++ArgIndex) {
1754
0
    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1755
0
    assert(PD && "null in a parameter list");
1756
0
    SourceLocation ParamLoc = PD->getLocation();
1757
0
    if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1758
0
                         diag::err_constexpr_non_literal_param, ArgIndex + 1,
1759
0
                         PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1760
0
                         FD->isConsteval()))
1761
0
      return false;
1762
0
  }
1763
0
  return true;
1764
0
}
1765
1766
/// Check whether a function's return type is a literal type. If so, return
1767
/// true. If not, produce a suitable diagnostic and return false.
1768
static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1769
0
                                     Sema::CheckConstexprKind Kind) {
1770
0
  if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1771
0
                       diag::err_constexpr_non_literal_return,
1772
0
                       FD->isConsteval()))
1773
0
    return false;
1774
0
  return true;
1775
0
}
1776
1777
/// Get diagnostic %select index for tag kind for
1778
/// record diagnostic message.
1779
/// WARNING: Indexes apply to particular diagnostics only!
1780
///
1781
/// \returns diagnostic %select index.
1782
0
static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1783
0
  switch (Tag) {
1784
0
  case TagTypeKind::Struct:
1785
0
    return 0;
1786
0
  case TagTypeKind::Interface:
1787
0
    return 1;
1788
0
  case TagTypeKind::Class:
1789
0
    return 2;
1790
0
  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1791
0
  }
1792
0
}
1793
1794
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1795
                                       Stmt *Body,
1796
                                       Sema::CheckConstexprKind Kind);
1797
1798
// Check whether a function declaration satisfies the requirements of a
1799
// constexpr function definition or a constexpr constructor definition. If so,
1800
// return true. If not, produce appropriate diagnostics (unless asked not to by
1801
// Kind) and return false.
1802
//
1803
// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1804
bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1805
0
                                            CheckConstexprKind Kind) {
1806
0
  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1807
0
  if (MD && MD->isInstance()) {
1808
    // C++11 [dcl.constexpr]p4:
1809
    //  The definition of a constexpr constructor shall satisfy the following
1810
    //  constraints:
1811
    //  - the class shall not have any virtual base classes;
1812
    //
1813
    // FIXME: This only applies to constructors and destructors, not arbitrary
1814
    // member functions.
1815
0
    const CXXRecordDecl *RD = MD->getParent();
1816
0
    if (RD->getNumVBases()) {
1817
0
      if (Kind == CheckConstexprKind::CheckValid)
1818
0
        return false;
1819
1820
0
      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1821
0
        << isa<CXXConstructorDecl>(NewFD)
1822
0
        << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1823
0
      for (const auto &I : RD->vbases())
1824
0
        Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1825
0
            << I.getSourceRange();
1826
0
      return false;
1827
0
    }
1828
0
  }
1829
1830
0
  if (!isa<CXXConstructorDecl>(NewFD)) {
1831
    // C++11 [dcl.constexpr]p3:
1832
    //  The definition of a constexpr function shall satisfy the following
1833
    //  constraints:
1834
    // - it shall not be virtual; (removed in C++20)
1835
0
    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1836
0
    if (Method && Method->isVirtual()) {
1837
0
      if (getLangOpts().CPlusPlus20) {
1838
0
        if (Kind == CheckConstexprKind::Diagnose)
1839
0
          Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1840
0
      } else {
1841
0
        if (Kind == CheckConstexprKind::CheckValid)
1842
0
          return false;
1843
1844
0
        Method = Method->getCanonicalDecl();
1845
0
        Diag(Method->getLocation(), diag::err_constexpr_virtual);
1846
1847
        // If it's not obvious why this function is virtual, find an overridden
1848
        // function which uses the 'virtual' keyword.
1849
0
        const CXXMethodDecl *WrittenVirtual = Method;
1850
0
        while (!WrittenVirtual->isVirtualAsWritten())
1851
0
          WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1852
0
        if (WrittenVirtual != Method)
1853
0
          Diag(WrittenVirtual->getLocation(),
1854
0
               diag::note_overridden_virtual_function);
1855
0
        return false;
1856
0
      }
1857
0
    }
1858
1859
    // - its return type shall be a literal type;
1860
0
    if (!CheckConstexprReturnType(*this, NewFD, Kind))
1861
0
      return false;
1862
0
  }
1863
1864
0
  if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1865
    // A destructor can be constexpr only if the defaulted destructor could be;
1866
    // we don't need to check the members and bases if we already know they all
1867
    // have constexpr destructors.
1868
0
    if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1869
0
      if (Kind == CheckConstexprKind::CheckValid)
1870
0
        return false;
1871
0
      if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1872
0
        return false;
1873
0
    }
1874
0
  }
1875
1876
  // - each of its parameter types shall be a literal type;
1877
0
  if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1878
0
    return false;
1879
1880
0
  Stmt *Body = NewFD->getBody();
1881
0
  assert(Body &&
1882
0
         "CheckConstexprFunctionDefinition called on function with no body");
1883
0
  return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1884
0
}
1885
1886
/// Check the given declaration statement is legal within a constexpr function
1887
/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1888
///
1889
/// \return true if the body is OK (maybe only as an extension), false if we
1890
///         have diagnosed a problem.
1891
static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1892
                                   DeclStmt *DS, SourceLocation &Cxx1yLoc,
1893
0
                                   Sema::CheckConstexprKind Kind) {
1894
  // C++11 [dcl.constexpr]p3 and p4:
1895
  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1896
  //  contain only
1897
0
  for (const auto *DclIt : DS->decls()) {
1898
0
    switch (DclIt->getKind()) {
1899
0
    case Decl::StaticAssert:
1900
0
    case Decl::Using:
1901
0
    case Decl::UsingShadow:
1902
0
    case Decl::UsingDirective:
1903
0
    case Decl::UnresolvedUsingTypename:
1904
0
    case Decl::UnresolvedUsingValue:
1905
0
    case Decl::UsingEnum:
1906
      //   - static_assert-declarations
1907
      //   - using-declarations,
1908
      //   - using-directives,
1909
      //   - using-enum-declaration
1910
0
      continue;
1911
1912
0
    case Decl::Typedef:
1913
0
    case Decl::TypeAlias: {
1914
      //   - typedef declarations and alias-declarations that do not define
1915
      //     classes or enumerations,
1916
0
      const auto *TN = cast<TypedefNameDecl>(DclIt);
1917
0
      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1918
        // Don't allow variably-modified types in constexpr functions.
1919
0
        if (Kind == Sema::CheckConstexprKind::Diagnose) {
1920
0
          TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1921
0
          SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1922
0
            << TL.getSourceRange() << TL.getType()
1923
0
            << isa<CXXConstructorDecl>(Dcl);
1924
0
        }
1925
0
        return false;
1926
0
      }
1927
0
      continue;
1928
0
    }
1929
1930
0
    case Decl::Enum:
1931
0
    case Decl::CXXRecord:
1932
      // C++1y allows types to be defined, not just declared.
1933
0
      if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1934
0
        if (Kind == Sema::CheckConstexprKind::Diagnose) {
1935
0
          SemaRef.Diag(DS->getBeginLoc(),
1936
0
                       SemaRef.getLangOpts().CPlusPlus14
1937
0
                           ? diag::warn_cxx11_compat_constexpr_type_definition
1938
0
                           : diag::ext_constexpr_type_definition)
1939
0
              << isa<CXXConstructorDecl>(Dcl);
1940
0
        } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1941
0
          return false;
1942
0
        }
1943
0
      }
1944
0
      continue;
1945
1946
0
    case Decl::EnumConstant:
1947
0
    case Decl::IndirectField:
1948
0
    case Decl::ParmVar:
1949
      // These can only appear with other declarations which are banned in
1950
      // C++11 and permitted in C++1y, so ignore them.
1951
0
      continue;
1952
1953
0
    case Decl::Var:
1954
0
    case Decl::Decomposition: {
1955
      // C++1y [dcl.constexpr]p3 allows anything except:
1956
      //   a definition of a variable of non-literal type or of static or
1957
      //   thread storage duration or [before C++2a] for which no
1958
      //   initialization is performed.
1959
0
      const auto *VD = cast<VarDecl>(DclIt);
1960
0
      if (VD->isThisDeclarationADefinition()) {
1961
0
        if (VD->isStaticLocal()) {
1962
0
          if (Kind == Sema::CheckConstexprKind::Diagnose) {
1963
0
            SemaRef.Diag(VD->getLocation(),
1964
0
                         SemaRef.getLangOpts().CPlusPlus23
1965
0
                             ? diag::warn_cxx20_compat_constexpr_var
1966
0
                             : diag::ext_constexpr_static_var)
1967
0
                << isa<CXXConstructorDecl>(Dcl)
1968
0
                << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1969
0
          } else if (!SemaRef.getLangOpts().CPlusPlus23) {
1970
0
            return false;
1971
0
          }
1972
0
        }
1973
0
        if (SemaRef.LangOpts.CPlusPlus23) {
1974
0
          CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1975
0
                           diag::warn_cxx20_compat_constexpr_var,
1976
0
                           isa<CXXConstructorDecl>(Dcl),
1977
0
                           /*variable of non-literal type*/ 2);
1978
0
        } else if (CheckLiteralType(
1979
0
                       SemaRef, Kind, VD->getLocation(), VD->getType(),
1980
0
                       diag::err_constexpr_local_var_non_literal_type,
1981
0
                       isa<CXXConstructorDecl>(Dcl))) {
1982
0
          return false;
1983
0
        }
1984
0
        if (!VD->getType()->isDependentType() &&
1985
0
            !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1986
0
          if (Kind == Sema::CheckConstexprKind::Diagnose) {
1987
0
            SemaRef.Diag(
1988
0
                VD->getLocation(),
1989
0
                SemaRef.getLangOpts().CPlusPlus20
1990
0
                    ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1991
0
                    : diag::ext_constexpr_local_var_no_init)
1992
0
                << isa<CXXConstructorDecl>(Dcl);
1993
0
          } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1994
0
            return false;
1995
0
          }
1996
0
          continue;
1997
0
        }
1998
0
      }
1999
0
      if (Kind == Sema::CheckConstexprKind::Diagnose) {
2000
0
        SemaRef.Diag(VD->getLocation(),
2001
0
                     SemaRef.getLangOpts().CPlusPlus14
2002
0
                      ? diag::warn_cxx11_compat_constexpr_local_var
2003
0
                      : diag::ext_constexpr_local_var)
2004
0
          << isa<CXXConstructorDecl>(Dcl);
2005
0
      } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2006
0
        return false;
2007
0
      }
2008
0
      continue;
2009
0
    }
2010
2011
0
    case Decl::NamespaceAlias:
2012
0
    case Decl::Function:
2013
      // These are disallowed in C++11 and permitted in C++1y. Allow them
2014
      // everywhere as an extension.
2015
0
      if (!Cxx1yLoc.isValid())
2016
0
        Cxx1yLoc = DS->getBeginLoc();
2017
0
      continue;
2018
2019
0
    default:
2020
0
      if (Kind == Sema::CheckConstexprKind::Diagnose) {
2021
0
        SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2022
0
            << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2023
0
      }
2024
0
      return false;
2025
0
    }
2026
0
  }
2027
2028
0
  return true;
2029
0
}
2030
2031
/// Check that the given field is initialized within a constexpr constructor.
2032
///
2033
/// \param Dcl The constexpr constructor being checked.
2034
/// \param Field The field being checked. This may be a member of an anonymous
2035
///        struct or union nested within the class being checked.
2036
/// \param Inits All declarations, including anonymous struct/union members and
2037
///        indirect members, for which any initialization was provided.
2038
/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2039
///        multiple notes for different members to the same error.
2040
/// \param Kind Whether we're diagnosing a constructor as written or determining
2041
///        whether the formal requirements are satisfied.
2042
/// \return \c false if we're checking for validity and the constructor does
2043
///         not satisfy the requirements on a constexpr constructor.
2044
static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2045
                                          const FunctionDecl *Dcl,
2046
                                          FieldDecl *Field,
2047
                                          llvm::SmallSet<Decl*, 16> &Inits,
2048
                                          bool &Diagnosed,
2049
0
                                          Sema::CheckConstexprKind Kind) {
2050
  // In C++20 onwards, there's nothing to check for validity.
2051
0
  if (Kind == Sema::CheckConstexprKind::CheckValid &&
2052
0
      SemaRef.getLangOpts().CPlusPlus20)
2053
0
    return true;
2054
2055
0
  if (Field->isInvalidDecl())
2056
0
    return true;
2057
2058
0
  if (Field->isUnnamedBitfield())
2059
0
    return true;
2060
2061
  // Anonymous unions with no variant members and empty anonymous structs do not
2062
  // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2063
  // indirect fields don't need initializing.
2064
0
  if (Field->isAnonymousStructOrUnion() &&
2065
0
      (Field->getType()->isUnionType()
2066
0
           ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2067
0
           : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2068
0
    return true;
2069
2070
0
  if (!Inits.count(Field)) {
2071
0
    if (Kind == Sema::CheckConstexprKind::Diagnose) {
2072
0
      if (!Diagnosed) {
2073
0
        SemaRef.Diag(Dcl->getLocation(),
2074
0
                     SemaRef.getLangOpts().CPlusPlus20
2075
0
                         ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2076
0
                         : diag::ext_constexpr_ctor_missing_init);
2077
0
        Diagnosed = true;
2078
0
      }
2079
0
      SemaRef.Diag(Field->getLocation(),
2080
0
                   diag::note_constexpr_ctor_missing_init);
2081
0
    } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2082
0
      return false;
2083
0
    }
2084
0
  } else if (Field->isAnonymousStructOrUnion()) {
2085
0
    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2086
0
    for (auto *I : RD->fields())
2087
      // If an anonymous union contains an anonymous struct of which any member
2088
      // is initialized, all members must be initialized.
2089
0
      if (!RD->isUnion() || Inits.count(I))
2090
0
        if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2091
0
                                           Kind))
2092
0
          return false;
2093
0
  }
2094
0
  return true;
2095
0
}
2096
2097
/// Check the provided statement is allowed in a constexpr function
2098
/// definition.
2099
static bool
2100
CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2101
                           SmallVectorImpl<SourceLocation> &ReturnStmts,
2102
                           SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2103
                           SourceLocation &Cxx2bLoc,
2104
0
                           Sema::CheckConstexprKind Kind) {
2105
  // - its function-body shall be [...] a compound-statement that contains only
2106
0
  switch (S->getStmtClass()) {
2107
0
  case Stmt::NullStmtClass:
2108
    //   - null statements,
2109
0
    return true;
2110
2111
0
  case Stmt::DeclStmtClass:
2112
    //   - static_assert-declarations
2113
    //   - using-declarations,
2114
    //   - using-directives,
2115
    //   - typedef declarations and alias-declarations that do not define
2116
    //     classes or enumerations,
2117
0
    if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2118
0
      return false;
2119
0
    return true;
2120
2121
0
  case Stmt::ReturnStmtClass:
2122
    //   - and exactly one return statement;
2123
0
    if (isa<CXXConstructorDecl>(Dcl)) {
2124
      // C++1y allows return statements in constexpr constructors.
2125
0
      if (!Cxx1yLoc.isValid())
2126
0
        Cxx1yLoc = S->getBeginLoc();
2127
0
      return true;
2128
0
    }
2129
2130
0
    ReturnStmts.push_back(S->getBeginLoc());
2131
0
    return true;
2132
2133
0
  case Stmt::AttributedStmtClass:
2134
    // Attributes on a statement don't affect its formal kind and hence don't
2135
    // affect its validity in a constexpr function.
2136
0
    return CheckConstexprFunctionStmt(
2137
0
        SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2138
0
        Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2139
2140
0
  case Stmt::CompoundStmtClass: {
2141
    // C++1y allows compound-statements.
2142
0
    if (!Cxx1yLoc.isValid())
2143
0
      Cxx1yLoc = S->getBeginLoc();
2144
2145
0
    CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2146
0
    for (auto *BodyIt : CompStmt->body()) {
2147
0
      if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2148
0
                                      Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2149
0
        return false;
2150
0
    }
2151
0
    return true;
2152
0
  }
2153
2154
0
  case Stmt::IfStmtClass: {
2155
    // C++1y allows if-statements.
2156
0
    if (!Cxx1yLoc.isValid())
2157
0
      Cxx1yLoc = S->getBeginLoc();
2158
2159
0
    IfStmt *If = cast<IfStmt>(S);
2160
0
    if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2161
0
                                    Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2162
0
      return false;
2163
0
    if (If->getElse() &&
2164
0
        !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2165
0
                                    Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2166
0
      return false;
2167
0
    return true;
2168
0
  }
2169
2170
0
  case Stmt::WhileStmtClass:
2171
0
  case Stmt::DoStmtClass:
2172
0
  case Stmt::ForStmtClass:
2173
0
  case Stmt::CXXForRangeStmtClass:
2174
0
  case Stmt::ContinueStmtClass:
2175
    // C++1y allows all of these. We don't allow them as extensions in C++11,
2176
    // because they don't make sense without variable mutation.
2177
0
    if (!SemaRef.getLangOpts().CPlusPlus14)
2178
0
      break;
2179
0
    if (!Cxx1yLoc.isValid())
2180
0
      Cxx1yLoc = S->getBeginLoc();
2181
0
    for (Stmt *SubStmt : S->children()) {
2182
0
      if (SubStmt &&
2183
0
          !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2184
0
                                      Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2185
0
        return false;
2186
0
    }
2187
0
    return true;
2188
2189
0
  case Stmt::SwitchStmtClass:
2190
0
  case Stmt::CaseStmtClass:
2191
0
  case Stmt::DefaultStmtClass:
2192
0
  case Stmt::BreakStmtClass:
2193
    // C++1y allows switch-statements, and since they don't need variable
2194
    // mutation, we can reasonably allow them in C++11 as an extension.
2195
0
    if (!Cxx1yLoc.isValid())
2196
0
      Cxx1yLoc = S->getBeginLoc();
2197
0
    for (Stmt *SubStmt : S->children()) {
2198
0
      if (SubStmt &&
2199
0
          !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2200
0
                                      Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2201
0
        return false;
2202
0
    }
2203
0
    return true;
2204
2205
0
  case Stmt::LabelStmtClass:
2206
0
  case Stmt::GotoStmtClass:
2207
0
    if (Cxx2bLoc.isInvalid())
2208
0
      Cxx2bLoc = S->getBeginLoc();
2209
0
    for (Stmt *SubStmt : S->children()) {
2210
0
      if (SubStmt &&
2211
0
          !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2212
0
                                      Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2213
0
        return false;
2214
0
    }
2215
0
    return true;
2216
2217
0
  case Stmt::GCCAsmStmtClass:
2218
0
  case Stmt::MSAsmStmtClass:
2219
    // C++2a allows inline assembly statements.
2220
0
  case Stmt::CXXTryStmtClass:
2221
0
    if (Cxx2aLoc.isInvalid())
2222
0
      Cxx2aLoc = S->getBeginLoc();
2223
0
    for (Stmt *SubStmt : S->children()) {
2224
0
      if (SubStmt &&
2225
0
          !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2226
0
                                      Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2227
0
        return false;
2228
0
    }
2229
0
    return true;
2230
2231
0
  case Stmt::CXXCatchStmtClass:
2232
    // Do not bother checking the language mode (already covered by the
2233
    // try block check).
2234
0
    if (!CheckConstexprFunctionStmt(
2235
0
            SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2236
0
            Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2237
0
      return false;
2238
0
    return true;
2239
2240
0
  default:
2241
0
    if (!isa<Expr>(S))
2242
0
      break;
2243
2244
    // C++1y allows expression-statements.
2245
0
    if (!Cxx1yLoc.isValid())
2246
0
      Cxx1yLoc = S->getBeginLoc();
2247
0
    return true;
2248
0
  }
2249
2250
0
  if (Kind == Sema::CheckConstexprKind::Diagnose) {
2251
0
    SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2252
0
        << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2253
0
  }
2254
0
  return false;
2255
0
}
2256
2257
/// Check the body for the given constexpr function declaration only contains
2258
/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2259
///
2260
/// \return true if the body is OK, false if we have found or diagnosed a
2261
/// problem.
2262
static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2263
                                       Stmt *Body,
2264
0
                                       Sema::CheckConstexprKind Kind) {
2265
0
  SmallVector<SourceLocation, 4> ReturnStmts;
2266
2267
0
  if (isa<CXXTryStmt>(Body)) {
2268
    // C++11 [dcl.constexpr]p3:
2269
    //  The definition of a constexpr function shall satisfy the following
2270
    //  constraints: [...]
2271
    // - its function-body shall be = delete, = default, or a
2272
    //   compound-statement
2273
    //
2274
    // C++11 [dcl.constexpr]p4:
2275
    //  In the definition of a constexpr constructor, [...]
2276
    // - its function-body shall not be a function-try-block;
2277
    //
2278
    // This restriction is lifted in C++2a, as long as inner statements also
2279
    // apply the general constexpr rules.
2280
0
    switch (Kind) {
2281
0
    case Sema::CheckConstexprKind::CheckValid:
2282
0
      if (!SemaRef.getLangOpts().CPlusPlus20)
2283
0
        return false;
2284
0
      break;
2285
2286
0
    case Sema::CheckConstexprKind::Diagnose:
2287
0
      SemaRef.Diag(Body->getBeginLoc(),
2288
0
           !SemaRef.getLangOpts().CPlusPlus20
2289
0
               ? diag::ext_constexpr_function_try_block_cxx20
2290
0
               : diag::warn_cxx17_compat_constexpr_function_try_block)
2291
0
          << isa<CXXConstructorDecl>(Dcl);
2292
0
      break;
2293
0
    }
2294
0
  }
2295
2296
  // - its function-body shall be [...] a compound-statement that contains only
2297
  //   [... list of cases ...]
2298
  //
2299
  // Note that walking the children here is enough to properly check for
2300
  // CompoundStmt and CXXTryStmt body.
2301
0
  SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2302
0
  for (Stmt *SubStmt : Body->children()) {
2303
0
    if (SubStmt &&
2304
0
        !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2305
0
                                    Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2306
0
      return false;
2307
0
  }
2308
2309
0
  if (Kind == Sema::CheckConstexprKind::CheckValid) {
2310
    // If this is only valid as an extension, report that we don't satisfy the
2311
    // constraints of the current language.
2312
0
    if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2313
0
        (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2314
0
        (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2315
0
      return false;
2316
0
  } else if (Cxx2bLoc.isValid()) {
2317
0
    SemaRef.Diag(Cxx2bLoc,
2318
0
                 SemaRef.getLangOpts().CPlusPlus23
2319
0
                     ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2320
0
                     : diag::ext_constexpr_body_invalid_stmt_cxx23)
2321
0
        << isa<CXXConstructorDecl>(Dcl);
2322
0
  } else if (Cxx2aLoc.isValid()) {
2323
0
    SemaRef.Diag(Cxx2aLoc,
2324
0
         SemaRef.getLangOpts().CPlusPlus20
2325
0
           ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2326
0
           : diag::ext_constexpr_body_invalid_stmt_cxx20)
2327
0
      << isa<CXXConstructorDecl>(Dcl);
2328
0
  } else if (Cxx1yLoc.isValid()) {
2329
0
    SemaRef.Diag(Cxx1yLoc,
2330
0
         SemaRef.getLangOpts().CPlusPlus14
2331
0
           ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2332
0
           : diag::ext_constexpr_body_invalid_stmt)
2333
0
      << isa<CXXConstructorDecl>(Dcl);
2334
0
  }
2335
2336
0
  if (const CXXConstructorDecl *Constructor
2337
0
        = dyn_cast<CXXConstructorDecl>(Dcl)) {
2338
0
    const CXXRecordDecl *RD = Constructor->getParent();
2339
    // DR1359:
2340
    // - every non-variant non-static data member and base class sub-object
2341
    //   shall be initialized;
2342
    // DR1460:
2343
    // - if the class is a union having variant members, exactly one of them
2344
    //   shall be initialized;
2345
0
    if (RD->isUnion()) {
2346
0
      if (Constructor->getNumCtorInitializers() == 0 &&
2347
0
          RD->hasVariantMembers()) {
2348
0
        if (Kind == Sema::CheckConstexprKind::Diagnose) {
2349
0
          SemaRef.Diag(
2350
0
              Dcl->getLocation(),
2351
0
              SemaRef.getLangOpts().CPlusPlus20
2352
0
                  ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2353
0
                  : diag::ext_constexpr_union_ctor_no_init);
2354
0
        } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2355
0
          return false;
2356
0
        }
2357
0
      }
2358
0
    } else if (!Constructor->isDependentContext() &&
2359
0
               !Constructor->isDelegatingConstructor()) {
2360
0
      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2361
2362
      // Skip detailed checking if we have enough initializers, and we would
2363
      // allow at most one initializer per member.
2364
0
      bool AnyAnonStructUnionMembers = false;
2365
0
      unsigned Fields = 0;
2366
0
      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2367
0
           E = RD->field_end(); I != E; ++I, ++Fields) {
2368
0
        if (I->isAnonymousStructOrUnion()) {
2369
0
          AnyAnonStructUnionMembers = true;
2370
0
          break;
2371
0
        }
2372
0
      }
2373
      // DR1460:
2374
      // - if the class is a union-like class, but is not a union, for each of
2375
      //   its anonymous union members having variant members, exactly one of
2376
      //   them shall be initialized;
2377
0
      if (AnyAnonStructUnionMembers ||
2378
0
          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2379
        // Check initialization of non-static data members. Base classes are
2380
        // always initialized so do not need to be checked. Dependent bases
2381
        // might not have initializers in the member initializer list.
2382
0
        llvm::SmallSet<Decl*, 16> Inits;
2383
0
        for (const auto *I: Constructor->inits()) {
2384
0
          if (FieldDecl *FD = I->getMember())
2385
0
            Inits.insert(FD);
2386
0
          else if (IndirectFieldDecl *ID = I->getIndirectMember())
2387
0
            Inits.insert(ID->chain_begin(), ID->chain_end());
2388
0
        }
2389
2390
0
        bool Diagnosed = false;
2391
0
        for (auto *I : RD->fields())
2392
0
          if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2393
0
                                             Kind))
2394
0
            return false;
2395
0
      }
2396
0
    }
2397
0
  } else {
2398
0
    if (ReturnStmts.empty()) {
2399
      // C++1y doesn't require constexpr functions to contain a 'return'
2400
      // statement. We still do, unless the return type might be void, because
2401
      // otherwise if there's no return statement, the function cannot
2402
      // be used in a core constant expression.
2403
0
      bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2404
0
                (Dcl->getReturnType()->isVoidType() ||
2405
0
                 Dcl->getReturnType()->isDependentType());
2406
0
      switch (Kind) {
2407
0
      case Sema::CheckConstexprKind::Diagnose:
2408
0
        SemaRef.Diag(Dcl->getLocation(),
2409
0
                     OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2410
0
                        : diag::err_constexpr_body_no_return)
2411
0
            << Dcl->isConsteval();
2412
0
        if (!OK)
2413
0
          return false;
2414
0
        break;
2415
2416
0
      case Sema::CheckConstexprKind::CheckValid:
2417
        // The formal requirements don't include this rule in C++14, even
2418
        // though the "must be able to produce a constant expression" rules
2419
        // still imply it in some cases.
2420
0
        if (!SemaRef.getLangOpts().CPlusPlus14)
2421
0
          return false;
2422
0
        break;
2423
0
      }
2424
0
    } else if (ReturnStmts.size() > 1) {
2425
0
      switch (Kind) {
2426
0
      case Sema::CheckConstexprKind::Diagnose:
2427
0
        SemaRef.Diag(
2428
0
            ReturnStmts.back(),
2429
0
            SemaRef.getLangOpts().CPlusPlus14
2430
0
                ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2431
0
                : diag::ext_constexpr_body_multiple_return);
2432
0
        for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2433
0
          SemaRef.Diag(ReturnStmts[I],
2434
0
                       diag::note_constexpr_body_previous_return);
2435
0
        break;
2436
2437
0
      case Sema::CheckConstexprKind::CheckValid:
2438
0
        if (!SemaRef.getLangOpts().CPlusPlus14)
2439
0
          return false;
2440
0
        break;
2441
0
      }
2442
0
    }
2443
0
  }
2444
2445
  // C++11 [dcl.constexpr]p5:
2446
  //   if no function argument values exist such that the function invocation
2447
  //   substitution would produce a constant expression, the program is
2448
  //   ill-formed; no diagnostic required.
2449
  // C++11 [dcl.constexpr]p3:
2450
  //   - every constructor call and implicit conversion used in initializing the
2451
  //     return value shall be one of those allowed in a constant expression.
2452
  // C++11 [dcl.constexpr]p4:
2453
  //   - every constructor involved in initializing non-static data members and
2454
  //     base class sub-objects shall be a constexpr constructor.
2455
  //
2456
  // Note that this rule is distinct from the "requirements for a constexpr
2457
  // function", so is not checked in CheckValid mode.
2458
0
  SmallVector<PartialDiagnosticAt, 8> Diags;
2459
0
  if (Kind == Sema::CheckConstexprKind::Diagnose &&
2460
0
      !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2461
0
    SemaRef.Diag(Dcl->getLocation(),
2462
0
                 diag::ext_constexpr_function_never_constant_expr)
2463
0
        << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2464
0
        << Dcl->getNameInfo().getSourceRange();
2465
0
    for (size_t I = 0, N = Diags.size(); I != N; ++I)
2466
0
      SemaRef.Diag(Diags[I].first, Diags[I].second);
2467
    // Don't return false here: we allow this for compatibility in
2468
    // system headers.
2469
0
  }
2470
2471
0
  return true;
2472
0
}
2473
2474
bool Sema::CheckImmediateEscalatingFunctionDefinition(
2475
0
    FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2476
0
  if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
2477
0
    return true;
2478
0
  FD->setBodyContainsImmediateEscalatingExpressions(
2479
0
      FSI->FoundImmediateEscalatingExpression);
2480
0
  if (FSI->FoundImmediateEscalatingExpression) {
2481
0
    auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2482
0
    if (it != UndefinedButUsed.end()) {
2483
0
      Diag(it->second, diag::err_immediate_function_used_before_definition)
2484
0
          << it->first;
2485
0
      Diag(FD->getLocation(), diag::note_defined_here) << FD;
2486
0
      if (FD->isImmediateFunction() && !FD->isConsteval())
2487
0
        DiagnoseImmediateEscalatingReason(FD);
2488
0
      return false;
2489
0
    }
2490
0
  }
2491
0
  return true;
2492
0
}
2493
2494
0
void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {
2495
0
  assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2496
0
         "expected an immediate function");
2497
0
  assert(FD->hasBody() && "expected the function to have a body");
2498
0
  struct ImmediateEscalatingExpressionsVisitor
2499
0
      : public RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor> {
2500
2501
0
    using Base = RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor>;
2502
0
    Sema &SemaRef;
2503
2504
0
    const FunctionDecl *ImmediateFn;
2505
0
    bool ImmediateFnIsConstructor;
2506
0
    CXXConstructorDecl *CurrentConstructor = nullptr;
2507
0
    CXXCtorInitializer *CurrentInit = nullptr;
2508
2509
0
    ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2510
0
        : SemaRef(SemaRef), ImmediateFn(FD),
2511
0
          ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {}
2512
2513
0
    bool shouldVisitImplicitCode() const { return true; }
2514
0
    bool shouldVisitLambdaBody() const { return false; }
2515
2516
0
    void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2517
0
      SourceLocation Loc = E->getBeginLoc();
2518
0
      SourceRange Range = E->getSourceRange();
2519
0
      if (CurrentConstructor && CurrentInit) {
2520
0
        Loc = CurrentConstructor->getLocation();
2521
0
        Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2522
0
                                         : SourceRange();
2523
0
      }
2524
2525
0
      FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2526
2527
0
      SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2528
0
          << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2529
0
          << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2530
0
          << (InitializedField != nullptr)
2531
0
          << (CurrentInit && !CurrentInit->isWritten())
2532
0
          << InitializedField << Range;
2533
0
    }
2534
0
    bool TraverseCallExpr(CallExpr *E) {
2535
0
      if (const auto *DR =
2536
0
              dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2537
0
          DR && DR->isImmediateEscalating()) {
2538
0
        Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2539
0
        return false;
2540
0
      }
2541
2542
0
      for (Expr *A : E->arguments())
2543
0
        if (!getDerived().TraverseStmt(A))
2544
0
          return false;
2545
2546
0
      return true;
2547
0
    }
2548
2549
0
    bool VisitDeclRefExpr(DeclRefExpr *E) {
2550
0
      if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2551
0
          ReferencedFn && E->isImmediateEscalating()) {
2552
0
        Diag(E, ReferencedFn, /*IsCall=*/false);
2553
0
        return false;
2554
0
      }
2555
2556
0
      return true;
2557
0
    }
2558
2559
0
    bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2560
0
      CXXConstructorDecl *D = E->getConstructor();
2561
0
      if (E->isImmediateEscalating()) {
2562
0
        Diag(E, D, /*IsCall=*/true);
2563
0
        return false;
2564
0
      }
2565
0
      return true;
2566
0
    }
2567
2568
0
    bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
2569
0
      llvm::SaveAndRestore RAII(CurrentInit, Init);
2570
0
      return Base::TraverseConstructorInitializer(Init);
2571
0
    }
2572
2573
0
    bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) {
2574
0
      llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2575
0
      return Base::TraverseCXXConstructorDecl(Ctr);
2576
0
    }
2577
2578
0
    bool TraverseType(QualType T) { return true; }
2579
0
    bool VisitBlockExpr(BlockExpr *T) { return true; }
2580
2581
0
  } Visitor(*this, FD);
2582
0
  Visitor.TraverseDecl(FD);
2583
0
}
2584
2585
/// Get the class that is directly named by the current context. This is the
2586
/// class for which an unqualified-id in this scope could name a constructor
2587
/// or destructor.
2588
///
2589
/// If the scope specifier denotes a class, this will be that class.
2590
/// If the scope specifier is empty, this will be the class whose
2591
/// member-specification we are currently within. Otherwise, there
2592
/// is no such class.
2593
0
CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2594
0
  assert(getLangOpts().CPlusPlus && "No class names in C!");
2595
2596
0
  if (SS && SS->isInvalid())
2597
0
    return nullptr;
2598
2599
0
  if (SS && SS->isNotEmpty()) {
2600
0
    DeclContext *DC = computeDeclContext(*SS, true);
2601
0
    return dyn_cast_or_null<CXXRecordDecl>(DC);
2602
0
  }
2603
2604
0
  return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2605
0
}
2606
2607
/// isCurrentClassName - Determine whether the identifier II is the
2608
/// name of the class type currently being defined. In the case of
2609
/// nested classes, this will only return true if II is the name of
2610
/// the innermost class.
2611
bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2612
0
                              const CXXScopeSpec *SS) {
2613
0
  CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2614
0
  return CurDecl && &II == CurDecl->getIdentifier();
2615
0
}
2616
2617
/// Determine whether the identifier II is a typo for the name of
2618
/// the class type currently being defined. If so, update it to the identifier
2619
/// that should have been used.
2620
0
bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2621
0
  assert(getLangOpts().CPlusPlus && "No class names in C!");
2622
2623
0
  if (!getLangOpts().SpellChecking)
2624
0
    return false;
2625
2626
0
  CXXRecordDecl *CurDecl;
2627
0
  if (SS && SS->isSet() && !SS->isInvalid()) {
2628
0
    DeclContext *DC = computeDeclContext(*SS, true);
2629
0
    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2630
0
  } else
2631
0
    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2632
2633
0
  if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2634
0
      3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2635
0
          < II->getLength()) {
2636
0
    II = CurDecl->getIdentifier();
2637
0
    return true;
2638
0
  }
2639
2640
0
  return false;
2641
0
}
2642
2643
/// Determine whether the given class is a base class of the given
2644
/// class, including looking at dependent bases.
2645
static bool findCircularInheritance(const CXXRecordDecl *Class,
2646
0
                                    const CXXRecordDecl *Current) {
2647
0
  SmallVector<const CXXRecordDecl*, 8> Queue;
2648
2649
0
  Class = Class->getCanonicalDecl();
2650
0
  while (true) {
2651
0
    for (const auto &I : Current->bases()) {
2652
0
      CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2653
0
      if (!Base)
2654
0
        continue;
2655
2656
0
      Base = Base->getDefinition();
2657
0
      if (!Base)
2658
0
        continue;
2659
2660
0
      if (Base->getCanonicalDecl() == Class)
2661
0
        return true;
2662
2663
0
      Queue.push_back(Base);
2664
0
    }
2665
2666
0
    if (Queue.empty())
2667
0
      return false;
2668
2669
0
    Current = Queue.pop_back_val();
2670
0
  }
2671
2672
0
  return false;
2673
0
}
2674
2675
/// Check the validity of a C++ base class specifier.
2676
///
2677
/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2678
/// and returns NULL otherwise.
2679
CXXBaseSpecifier *
2680
Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2681
                         SourceRange SpecifierRange,
2682
                         bool Virtual, AccessSpecifier Access,
2683
                         TypeSourceInfo *TInfo,
2684
0
                         SourceLocation EllipsisLoc) {
2685
  // In HLSL, unspecified class access is public rather than private.
2686
0
  if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2687
0
      Access == AS_none)
2688
0
    Access = AS_public;
2689
2690
0
  QualType BaseType = TInfo->getType();
2691
0
  if (BaseType->containsErrors()) {
2692
    // Already emitted a diagnostic when parsing the error type.
2693
0
    return nullptr;
2694
0
  }
2695
  // C++ [class.union]p1:
2696
  //   A union shall not have base classes.
2697
0
  if (Class->isUnion()) {
2698
0
    Diag(Class->getLocation(), diag::err_base_clause_on_union)
2699
0
      << SpecifierRange;
2700
0
    return nullptr;
2701
0
  }
2702
2703
0
  if (EllipsisLoc.isValid() &&
2704
0
      !TInfo->getType()->containsUnexpandedParameterPack()) {
2705
0
    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2706
0
      << TInfo->getTypeLoc().getSourceRange();
2707
0
    EllipsisLoc = SourceLocation();
2708
0
  }
2709
2710
0
  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2711
2712
0
  if (BaseType->isDependentType()) {
2713
    // Make sure that we don't have circular inheritance among our dependent
2714
    // bases. For non-dependent bases, the check for completeness below handles
2715
    // this.
2716
0
    if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2717
0
      if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2718
0
          ((BaseDecl = BaseDecl->getDefinition()) &&
2719
0
           findCircularInheritance(Class, BaseDecl))) {
2720
0
        Diag(BaseLoc, diag::err_circular_inheritance)
2721
0
          << BaseType << Context.getTypeDeclType(Class);
2722
2723
0
        if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2724
0
          Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2725
0
            << BaseType;
2726
2727
0
        return nullptr;
2728
0
      }
2729
0
    }
2730
2731
    // Make sure that we don't make an ill-formed AST where the type of the
2732
    // Class is non-dependent and its attached base class specifier is an
2733
    // dependent type, which violates invariants in many clang code paths (e.g.
2734
    // constexpr evaluator). If this case happens (in errory-recovery mode), we
2735
    // explicitly mark the Class decl invalid. The diagnostic was already
2736
    // emitted.
2737
0
    if (!Class->getTypeForDecl()->isDependentType())
2738
0
      Class->setInvalidDecl();
2739
0
    return new (Context) CXXBaseSpecifier(
2740
0
        SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2741
0
        Access, TInfo, EllipsisLoc);
2742
0
  }
2743
2744
  // Base specifiers must be record types.
2745
0
  if (!BaseType->isRecordType()) {
2746
0
    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2747
0
    return nullptr;
2748
0
  }
2749
2750
  // C++ [class.union]p1:
2751
  //   A union shall not be used as a base class.
2752
0
  if (BaseType->isUnionType()) {
2753
0
    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2754
0
    return nullptr;
2755
0
  }
2756
2757
  // For the MS ABI, propagate DLL attributes to base class templates.
2758
0
  if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2759
0
      Context.getTargetInfo().getTriple().isPS()) {
2760
0
    if (Attr *ClassAttr = getDLLAttr(Class)) {
2761
0
      if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2762
0
              BaseType->getAsCXXRecordDecl())) {
2763
0
        propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2764
0
                                            BaseLoc);
2765
0
      }
2766
0
    }
2767
0
  }
2768
2769
  // C++ [class.derived]p2:
2770
  //   The class-name in a base-specifier shall not be an incompletely
2771
  //   defined class.
2772
0
  if (RequireCompleteType(BaseLoc, BaseType,
2773
0
                          diag::err_incomplete_base_class, SpecifierRange)) {
2774
0
    Class->setInvalidDecl();
2775
0
    return nullptr;
2776
0
  }
2777
2778
  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2779
0
  RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2780
0
  assert(BaseDecl && "Record type has no declaration");
2781
0
  BaseDecl = BaseDecl->getDefinition();
2782
0
  assert(BaseDecl && "Base type is not incomplete, but has no definition");
2783
0
  CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2784
0
  assert(CXXBaseDecl && "Base type is not a C++ type");
2785
2786
  // Microsoft docs say:
2787
  // "If a base-class has a code_seg attribute, derived classes must have the
2788
  // same attribute."
2789
0
  const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2790
0
  const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2791
0
  if ((DerivedCSA || BaseCSA) &&
2792
0
      (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2793
0
    Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2794
0
    Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2795
0
      << CXXBaseDecl;
2796
0
    return nullptr;
2797
0
  }
2798
2799
  // A class which contains a flexible array member is not suitable for use as a
2800
  // base class:
2801
  //   - If the layout determines that a base comes before another base,
2802
  //     the flexible array member would index into the subsequent base.
2803
  //   - If the layout determines that base comes before the derived class,
2804
  //     the flexible array member would index into the derived class.
2805
0
  if (CXXBaseDecl->hasFlexibleArrayMember()) {
2806
0
    Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2807
0
      << CXXBaseDecl->getDeclName();
2808
0
    return nullptr;
2809
0
  }
2810
2811
  // C++ [class]p3:
2812
  //   If a class is marked final and it appears as a base-type-specifier in
2813
  //   base-clause, the program is ill-formed.
2814
0
  if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2815
0
    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2816
0
      << CXXBaseDecl->getDeclName()
2817
0
      << FA->isSpelledAsSealed();
2818
0
    Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2819
0
        << CXXBaseDecl->getDeclName() << FA->getRange();
2820
0
    return nullptr;
2821
0
  }
2822
2823
0
  if (BaseDecl->isInvalidDecl())
2824
0
    Class->setInvalidDecl();
2825
2826
  // Create the base specifier.
2827
0
  return new (Context) CXXBaseSpecifier(
2828
0
      SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2829
0
      Access, TInfo, EllipsisLoc);
2830
0
}
2831
2832
/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2833
/// one entry in the base class list of a class specifier, for
2834
/// example:
2835
///    class foo : public bar, virtual private baz {
2836
/// 'public bar' and 'virtual private baz' are each base-specifiers.
2837
BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2838
                                    const ParsedAttributesView &Attributes,
2839
                                    bool Virtual, AccessSpecifier Access,
2840
                                    ParsedType basetype, SourceLocation BaseLoc,
2841
0
                                    SourceLocation EllipsisLoc) {
2842
0
  if (!classdecl)
2843
0
    return true;
2844
2845
0
  AdjustDeclIfTemplate(classdecl);
2846
0
  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2847
0
  if (!Class)
2848
0
    return true;
2849
2850
  // We haven't yet attached the base specifiers.
2851
0
  Class->setIsParsingBaseSpecifiers();
2852
2853
  // We do not support any C++11 attributes on base-specifiers yet.
2854
  // Diagnose any attributes we see.
2855
0
  for (const ParsedAttr &AL : Attributes) {
2856
0
    if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2857
0
      continue;
2858
0
    if (AL.getKind() == ParsedAttr::UnknownAttribute)
2859
0
      Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2860
0
          << AL << AL.getRange();
2861
0
    else
2862
0
      Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2863
0
          << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2864
0
  }
2865
2866
0
  TypeSourceInfo *TInfo = nullptr;
2867
0
  GetTypeFromParser(basetype, &TInfo);
2868
2869
0
  if (EllipsisLoc.isInvalid() &&
2870
0
      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2871
0
                                      UPPC_BaseType))
2872
0
    return true;
2873
2874
0
  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2875
0
                                                      Virtual, Access, TInfo,
2876
0
                                                      EllipsisLoc))
2877
0
    return BaseSpec;
2878
0
  else
2879
0
    Class->setInvalidDecl();
2880
2881
0
  return true;
2882
0
}
2883
2884
/// Use small set to collect indirect bases.  As this is only used
2885
/// locally, there's no need to abstract the small size parameter.
2886
typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2887
2888
/// Recursively add the bases of Type.  Don't add Type itself.
2889
static void
2890
NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2891
                  const QualType &Type)
2892
0
{
2893
  // Even though the incoming type is a base, it might not be
2894
  // a class -- it could be a template parm, for instance.
2895
0
  if (auto Rec = Type->getAs<RecordType>()) {
2896
0
    auto Decl = Rec->getAsCXXRecordDecl();
2897
2898
    // Iterate over its bases.
2899
0
    for (const auto &BaseSpec : Decl->bases()) {
2900
0
      QualType Base = Context.getCanonicalType(BaseSpec.getType())
2901
0
        .getUnqualifiedType();
2902
0
      if (Set.insert(Base).second)
2903
        // If we've not already seen it, recurse.
2904
0
        NoteIndirectBases(Context, Set, Base);
2905
0
    }
2906
0
  }
2907
0
}
2908
2909
/// Performs the actual work of attaching the given base class
2910
/// specifiers to a C++ class.
2911
bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2912
0
                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2913
0
 if (Bases.empty())
2914
0
    return false;
2915
2916
  // Used to keep track of which base types we have already seen, so
2917
  // that we can properly diagnose redundant direct base types. Note
2918
  // that the key is always the unqualified canonical type of the base
2919
  // class.
2920
0
  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2921
2922
  // Used to track indirect bases so we can see if a direct base is
2923
  // ambiguous.
2924
0
  IndirectBaseSet IndirectBaseTypes;
2925
2926
  // Copy non-redundant base specifiers into permanent storage.
2927
0
  unsigned NumGoodBases = 0;
2928
0
  bool Invalid = false;
2929
0
  for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2930
0
    QualType NewBaseType
2931
0
      = Context.getCanonicalType(Bases[idx]->getType());
2932
0
    NewBaseType = NewBaseType.getLocalUnqualifiedType();
2933
2934
0
    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2935
0
    if (KnownBase) {
2936
      // C++ [class.mi]p3:
2937
      //   A class shall not be specified as a direct base class of a
2938
      //   derived class more than once.
2939
0
      Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2940
0
          << KnownBase->getType() << Bases[idx]->getSourceRange();
2941
2942
      // Delete the duplicate base class specifier; we're going to
2943
      // overwrite its pointer later.
2944
0
      Context.Deallocate(Bases[idx]);
2945
2946
0
      Invalid = true;
2947
0
    } else {
2948
      // Okay, add this new base class.
2949
0
      KnownBase = Bases[idx];
2950
0
      Bases[NumGoodBases++] = Bases[idx];
2951
2952
0
      if (NewBaseType->isDependentType())
2953
0
        continue;
2954
      // Note this base's direct & indirect bases, if there could be ambiguity.
2955
0
      if (Bases.size() > 1)
2956
0
        NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2957
2958
0
      if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2959
0
        const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2960
0
        if (Class->isInterface() &&
2961
0
              (!RD->isInterfaceLike() ||
2962
0
               KnownBase->getAccessSpecifier() != AS_public)) {
2963
          // The Microsoft extension __interface does not permit bases that
2964
          // are not themselves public interfaces.
2965
0
          Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2966
0
              << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2967
0
              << RD->getSourceRange();
2968
0
          Invalid = true;
2969
0
        }
2970
0
        if (RD->hasAttr<WeakAttr>())
2971
0
          Class->addAttr(WeakAttr::CreateImplicit(Context));
2972
0
      }
2973
0
    }
2974
0
  }
2975
2976
  // Attach the remaining base class specifiers to the derived class.
2977
0
  Class->setBases(Bases.data(), NumGoodBases);
2978
2979
  // Check that the only base classes that are duplicate are virtual.
2980
0
  for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2981
    // Check whether this direct base is inaccessible due to ambiguity.
2982
0
    QualType BaseType = Bases[idx]->getType();
2983
2984
    // Skip all dependent types in templates being used as base specifiers.
2985
    // Checks below assume that the base specifier is a CXXRecord.
2986
0
    if (BaseType->isDependentType())
2987
0
      continue;
2988
2989
0
    CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2990
0
      .getUnqualifiedType();
2991
2992
0
    if (IndirectBaseTypes.count(CanonicalBase)) {
2993
0
      CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2994
0
                         /*DetectVirtual=*/true);
2995
0
      bool found
2996
0
        = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2997
0
      assert(found);
2998
0
      (void)found;
2999
3000
0
      if (Paths.isAmbiguous(CanonicalBase))
3001
0
        Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3002
0
            << BaseType << getAmbiguousPathsDisplayString(Paths)
3003
0
            << Bases[idx]->getSourceRange();
3004
0
      else
3005
0
        assert(Bases[idx]->isVirtual());
3006
0
    }
3007
3008
    // Delete the base class specifier, since its data has been copied
3009
    // into the CXXRecordDecl.
3010
0
    Context.Deallocate(Bases[idx]);
3011
0
  }
3012
3013
0
  return Invalid;
3014
0
}
3015
3016
/// ActOnBaseSpecifiers - Attach the given base specifiers to the
3017
/// class, after checking whether there are any duplicate base
3018
/// classes.
3019
void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
3020
0
                               MutableArrayRef<CXXBaseSpecifier *> Bases) {
3021
0
  if (!ClassDecl || Bases.empty())
3022
0
    return;
3023
3024
0
  AdjustDeclIfTemplate(ClassDecl);
3025
0
  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3026
0
}
3027
3028
/// Determine whether the type \p Derived is a C++ class that is
3029
/// derived from the type \p Base.
3030
0
bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
3031
0
  if (!getLangOpts().CPlusPlus)
3032
0
    return false;
3033
3034
0
  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3035
0
  if (!DerivedRD)
3036
0
    return false;
3037
3038
0
  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3039
0
  if (!BaseRD)
3040
0
    return false;
3041
3042
  // If either the base or the derived type is invalid, don't try to
3043
  // check whether one is derived from the other.
3044
0
  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
3045
0
    return false;
3046
3047
  // FIXME: In a modules build, do we need the entire path to be visible for us
3048
  // to be able to use the inheritance relationship?
3049
0
  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3050
0
    return false;
3051
3052
0
  return DerivedRD->isDerivedFrom(BaseRD);
3053
0
}
3054
3055
/// Determine whether the type \p Derived is a C++ class that is
3056
/// derived from the type \p Base.
3057
bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3058
0
                         CXXBasePaths &Paths) {
3059
0
  if (!getLangOpts().CPlusPlus)
3060
0
    return false;
3061
3062
0
  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3063
0
  if (!DerivedRD)
3064
0
    return false;
3065
3066
0
  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3067
0
  if (!BaseRD)
3068
0
    return false;
3069
3070
0
  if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3071
0
    return false;
3072
3073
0
  return DerivedRD->isDerivedFrom(BaseRD, Paths);
3074
0
}
3075
3076
static void BuildBasePathArray(const CXXBasePath &Path,
3077
0
                               CXXCastPath &BasePathArray) {
3078
  // We first go backward and check if we have a virtual base.
3079
  // FIXME: It would be better if CXXBasePath had the base specifier for
3080
  // the nearest virtual base.
3081
0
  unsigned Start = 0;
3082
0
  for (unsigned I = Path.size(); I != 0; --I) {
3083
0
    if (Path[I - 1].Base->isVirtual()) {
3084
0
      Start = I - 1;
3085
0
      break;
3086
0
    }
3087
0
  }
3088
3089
  // Now add all bases.
3090
0
  for (unsigned I = Start, E = Path.size(); I != E; ++I)
3091
0
    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3092
0
}
3093
3094
3095
void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3096
0
                              CXXCastPath &BasePathArray) {
3097
0
  assert(BasePathArray.empty() && "Base path array must be empty!");
3098
0
  assert(Paths.isRecordingPaths() && "Must record paths!");
3099
0
  return ::BuildBasePathArray(Paths.front(), BasePathArray);
3100
0
}
3101
/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
3102
/// conversion (where Derived and Base are class types) is
3103
/// well-formed, meaning that the conversion is unambiguous (and
3104
/// that all of the base classes are accessible). Returns true
3105
/// and emits a diagnostic if the code is ill-formed, returns false
3106
/// otherwise. Loc is the location where this routine should point to
3107
/// if there is an error, and Range is the source range to highlight
3108
/// if there is an error.
3109
///
3110
/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
3111
/// diagnostic for the respective type of error will be suppressed, but the
3112
/// check for ill-formed code will still be performed.
3113
bool
3114
Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3115
                                   unsigned InaccessibleBaseID,
3116
                                   unsigned AmbiguousBaseConvID,
3117
                                   SourceLocation Loc, SourceRange Range,
3118
                                   DeclarationName Name,
3119
                                   CXXCastPath *BasePath,
3120
0
                                   bool IgnoreAccess) {
3121
  // First, determine whether the path from Derived to Base is
3122
  // ambiguous. This is slightly more expensive than checking whether
3123
  // the Derived to Base conversion exists, because here we need to
3124
  // explore multiple paths to determine if there is an ambiguity.
3125
0
  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3126
0
                     /*DetectVirtual=*/false);
3127
0
  bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3128
0
  if (!DerivationOkay)
3129
0
    return true;
3130
3131
0
  const CXXBasePath *Path = nullptr;
3132
0
  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3133
0
    Path = &Paths.front();
3134
3135
  // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3136
  // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3137
  // user to access such bases.
3138
0
  if (!Path && getLangOpts().MSVCCompat) {
3139
0
    for (const CXXBasePath &PossiblePath : Paths) {
3140
0
      if (PossiblePath.size() == 1) {
3141
0
        Path = &PossiblePath;
3142
0
        if (AmbiguousBaseConvID)
3143
0
          Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3144
0
              << Base << Derived << Range;
3145
0
        break;
3146
0
      }
3147
0
    }
3148
0
  }
3149
3150
0
  if (Path) {
3151
0
    if (!IgnoreAccess) {
3152
      // Check that the base class can be accessed.
3153
0
      switch (
3154
0
          CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3155
0
      case AR_inaccessible:
3156
0
        return true;
3157
0
      case AR_accessible:
3158
0
      case AR_dependent:
3159
0
      case AR_delayed:
3160
0
        break;
3161
0
      }
3162
0
    }
3163
3164
    // Build a base path if necessary.
3165
0
    if (BasePath)
3166
0
      ::BuildBasePathArray(*Path, *BasePath);
3167
0
    return false;
3168
0
  }
3169
3170
0
  if (AmbiguousBaseConvID) {
3171
    // We know that the derived-to-base conversion is ambiguous, and
3172
    // we're going to produce a diagnostic. Perform the derived-to-base
3173
    // search just one more time to compute all of the possible paths so
3174
    // that we can print them out. This is more expensive than any of
3175
    // the previous derived-to-base checks we've done, but at this point
3176
    // performance isn't as much of an issue.
3177
0
    Paths.clear();
3178
0
    Paths.setRecordingPaths(true);
3179
0
    bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3180
0
    assert(StillOkay && "Can only be used with a derived-to-base conversion");
3181
0
    (void)StillOkay;
3182
3183
    // Build up a textual representation of the ambiguous paths, e.g.,
3184
    // D -> B -> A, that will be used to illustrate the ambiguous
3185
    // conversions in the diagnostic. We only print one of the paths
3186
    // to each base class subobject.
3187
0
    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3188
3189
0
    Diag(Loc, AmbiguousBaseConvID)
3190
0
    << Derived << Base << PathDisplayStr << Range << Name;
3191
0
  }
3192
0
  return true;
3193
0
}
3194
3195
bool
3196
Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3197
                                   SourceLocation Loc, SourceRange Range,
3198
                                   CXXCastPath *BasePath,
3199
0
                                   bool IgnoreAccess) {
3200
0
  return CheckDerivedToBaseConversion(
3201
0
      Derived, Base, diag::err_upcast_to_inaccessible_base,
3202
0
      diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3203
0
      BasePath, IgnoreAccess);
3204
0
}
3205
3206
3207
/// Builds a string representing ambiguous paths from a
3208
/// specific derived class to different subobjects of the same base
3209
/// class.
3210
///
3211
/// This function builds a string that can be used in error messages
3212
/// to show the different paths that one can take through the
3213
/// inheritance hierarchy to go from the derived class to different
3214
/// subobjects of a base class. The result looks something like this:
3215
/// @code
3216
/// struct D -> struct B -> struct A
3217
/// struct D -> struct C -> struct A
3218
/// @endcode
3219
0
std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3220
0
  std::string PathDisplayStr;
3221
0
  std::set<unsigned> DisplayedPaths;
3222
0
  for (CXXBasePaths::paths_iterator Path = Paths.begin();
3223
0
       Path != Paths.end(); ++Path) {
3224
0
    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3225
      // We haven't displayed a path to this particular base
3226
      // class subobject yet.
3227
0
      PathDisplayStr += "\n    ";
3228
0
      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3229
0
      for (CXXBasePath::const_iterator Element = Path->begin();
3230
0
           Element != Path->end(); ++Element)
3231
0
        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3232
0
    }
3233
0
  }
3234
3235
0
  return PathDisplayStr;
3236
0
}
3237
3238
//===----------------------------------------------------------------------===//
3239
// C++ class member Handling
3240
//===----------------------------------------------------------------------===//
3241
3242
/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3243
bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3244
                                SourceLocation ColonLoc,
3245
0
                                const ParsedAttributesView &Attrs) {
3246
0
  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3247
0
  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3248
0
                                                  ASLoc, ColonLoc);
3249
0
  CurContext->addHiddenDecl(ASDecl);
3250
0
  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3251
0
}
3252
3253
/// CheckOverrideControl - Check C++11 override control semantics.
3254
0
void Sema::CheckOverrideControl(NamedDecl *D) {
3255
0
  if (D->isInvalidDecl())
3256
0
    return;
3257
3258
  // We only care about "override" and "final" declarations.
3259
0
  if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3260
0
    return;
3261
3262
0
  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3263
3264
  // We can't check dependent instance methods.
3265
0
  if (MD && MD->isInstance() &&
3266
0
      (MD->getParent()->hasAnyDependentBases() ||
3267
0
       MD->getType()->isDependentType()))
3268
0
    return;
3269
3270
0
  if (MD && !MD->isVirtual()) {
3271
    // If we have a non-virtual method, check if it hides a virtual method.
3272
    // (In that case, it's most likely the method has the wrong type.)
3273
0
    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3274
0
    FindHiddenVirtualMethods(MD, OverloadedMethods);
3275
3276
0
    if (!OverloadedMethods.empty()) {
3277
0
      if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3278
0
        Diag(OA->getLocation(),
3279
0
             diag::override_keyword_hides_virtual_member_function)
3280
0
          << "override" << (OverloadedMethods.size() > 1);
3281
0
      } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3282
0
        Diag(FA->getLocation(),
3283
0
             diag::override_keyword_hides_virtual_member_function)
3284
0
          << (FA->isSpelledAsSealed() ? "sealed" : "final")
3285
0
          << (OverloadedMethods.size() > 1);
3286
0
      }
3287
0
      NoteHiddenVirtualMethods(MD, OverloadedMethods);
3288
0
      MD->setInvalidDecl();
3289
0
      return;
3290
0
    }
3291
    // Fall through into the general case diagnostic.
3292
    // FIXME: We might want to attempt typo correction here.
3293
0
  }
3294
3295
0
  if (!MD || !MD->isVirtual()) {
3296
0
    if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3297
0
      Diag(OA->getLocation(),
3298
0
           diag::override_keyword_only_allowed_on_virtual_member_functions)
3299
0
        << "override" << FixItHint::CreateRemoval(OA->getLocation());
3300
0
      D->dropAttr<OverrideAttr>();
3301
0
    }
3302
0
    if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3303
0
      Diag(FA->getLocation(),
3304
0
           diag::override_keyword_only_allowed_on_virtual_member_functions)
3305
0
        << (FA->isSpelledAsSealed() ? "sealed" : "final")
3306
0
        << FixItHint::CreateRemoval(FA->getLocation());
3307
0
      D->dropAttr<FinalAttr>();
3308
0
    }
3309
0
    return;
3310
0
  }
3311
3312
  // C++11 [class.virtual]p5:
3313
  //   If a function is marked with the virt-specifier override and
3314
  //   does not override a member function of a base class, the program is
3315
  //   ill-formed.
3316
0
  bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3317
0
  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3318
0
    Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3319
0
      << MD->getDeclName();
3320
0
}
3321
3322
0
void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3323
0
  if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3324
0
    return;
3325
0
  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3326
0
  if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3327
0
    return;
3328
3329
0
  SourceLocation Loc = MD->getLocation();
3330
0
  SourceLocation SpellingLoc = Loc;
3331
0
  if (getSourceManager().isMacroArgExpansion(Loc))
3332
0
    SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3333
0
  SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3334
0
  if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3335
0
      return;
3336
3337
0
  if (MD->size_overridden_methods() > 0) {
3338
0
    auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3339
0
      unsigned DiagID =
3340
0
          Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3341
0
              ? DiagInconsistent
3342
0
              : DiagSuggest;
3343
0
      Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3344
0
      const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3345
0
      Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3346
0
    };
3347
0
    if (isa<CXXDestructorDecl>(MD))
3348
0
      EmitDiag(
3349
0
          diag::warn_inconsistent_destructor_marked_not_override_overriding,
3350
0
          diag::warn_suggest_destructor_marked_not_override_overriding);
3351
0
    else
3352
0
      EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3353
0
               diag::warn_suggest_function_marked_not_override_overriding);
3354
0
  }
3355
0
}
3356
3357
/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3358
/// function overrides a virtual member function marked 'final', according to
3359
/// C++11 [class.virtual]p4.
3360
bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3361
0
                                                  const CXXMethodDecl *Old) {
3362
0
  FinalAttr *FA = Old->getAttr<FinalAttr>();
3363
0
  if (!FA)
3364
0
    return false;
3365
3366
0
  Diag(New->getLocation(), diag::err_final_function_overridden)
3367
0
    << New->getDeclName()
3368
0
    << FA->isSpelledAsSealed();
3369
0
  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3370
0
  return true;
3371
0
}
3372
3373
0
static bool InitializationHasSideEffects(const FieldDecl &FD) {
3374
0
  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3375
  // FIXME: Destruction of ObjC lifetime types has side-effects.
3376
0
  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3377
0
    return !RD->isCompleteDefinition() ||
3378
0
           !RD->hasTrivialDefaultConstructor() ||
3379
0
           !RD->hasTrivialDestructor();
3380
0
  return false;
3381
0
}
3382
3383
// Check if there is a field shadowing.
3384
void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3385
                                      DeclarationName FieldName,
3386
                                      const CXXRecordDecl *RD,
3387
0
                                      bool DeclIsField) {
3388
0
  if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3389
0
    return;
3390
3391
  // To record a shadowed field in a base
3392
0
  std::map<CXXRecordDecl*, NamedDecl*> Bases;
3393
0
  auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3394
0
                           CXXBasePath &Path) {
3395
0
    const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3396
    // Record an ambiguous path directly
3397
0
    if (Bases.find(Base) != Bases.end())
3398
0
      return true;
3399
0
    for (const auto Field : Base->lookup(FieldName)) {
3400
0
      if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3401
0
          Field->getAccess() != AS_private) {
3402
0
        assert(Field->getAccess() != AS_none);
3403
0
        assert(Bases.find(Base) == Bases.end());
3404
0
        Bases[Base] = Field;
3405
0
        return true;
3406
0
      }
3407
0
    }
3408
0
    return false;
3409
0
  };
3410
3411
0
  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3412
0
                     /*DetectVirtual=*/true);
3413
0
  if (!RD->lookupInBases(FieldShadowed, Paths))
3414
0
    return;
3415
3416
0
  for (const auto &P : Paths) {
3417
0
    auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3418
0
    auto It = Bases.find(Base);
3419
    // Skip duplicated bases
3420
0
    if (It == Bases.end())
3421
0
      continue;
3422
0
    auto BaseField = It->second;
3423
0
    assert(BaseField->getAccess() != AS_private);
3424
0
    if (AS_none !=
3425
0
        CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3426
0
      Diag(Loc, diag::warn_shadow_field)
3427
0
        << FieldName << RD << Base << DeclIsField;
3428
0
      Diag(BaseField->getLocation(), diag::note_shadow_field);
3429
0
      Bases.erase(It);
3430
0
    }
3431
0
  }
3432
0
}
3433
3434
/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3435
/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3436
/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3437
/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3438
/// present (but parsing it has been deferred).
3439
NamedDecl *
3440
Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3441
                               MultiTemplateParamsArg TemplateParameterLists,
3442
                               Expr *BW, const VirtSpecifiers &VS,
3443
0
                               InClassInitStyle InitStyle) {
3444
0
  const DeclSpec &DS = D.getDeclSpec();
3445
0
  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3446
0
  DeclarationName Name = NameInfo.getName();
3447
0
  SourceLocation Loc = NameInfo.getLoc();
3448
3449
  // For anonymous bitfields, the location should point to the type.
3450
0
  if (Loc.isInvalid())
3451
0
    Loc = D.getBeginLoc();
3452
3453
0
  Expr *BitWidth = static_cast<Expr*>(BW);
3454
3455
0
  assert(isa<CXXRecordDecl>(CurContext));
3456
0
  assert(!DS.isFriendSpecified());
3457
3458
0
  bool isFunc = D.isDeclarationOfFunction();
3459
0
  const ParsedAttr *MSPropertyAttr =
3460
0
      D.getDeclSpec().getAttributes().getMSPropertyAttr();
3461
3462
0
  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3463
    // The Microsoft extension __interface only permits public member functions
3464
    // and prohibits constructors, destructors, operators, non-public member
3465
    // functions, static methods and data members.
3466
0
    unsigned InvalidDecl;
3467
0
    bool ShowDeclName = true;
3468
0
    if (!isFunc &&
3469
0
        (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3470
0
      InvalidDecl = 0;
3471
0
    else if (!isFunc)
3472
0
      InvalidDecl = 1;
3473
0
    else if (AS != AS_public)
3474
0
      InvalidDecl = 2;
3475
0
    else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3476
0
      InvalidDecl = 3;
3477
0
    else switch (Name.getNameKind()) {
3478
0
      case DeclarationName::CXXConstructorName:
3479
0
        InvalidDecl = 4;
3480
0
        ShowDeclName = false;
3481
0
        break;
3482
3483
0
      case DeclarationName::CXXDestructorName:
3484
0
        InvalidDecl = 5;
3485
0
        ShowDeclName = false;
3486
0
        break;
3487
3488
0
      case DeclarationName::CXXOperatorName:
3489
0
      case DeclarationName::CXXConversionFunctionName:
3490
0
        InvalidDecl = 6;
3491
0
        break;
3492
3493
0
      default:
3494
0
        InvalidDecl = 0;
3495
0
        break;
3496
0
    }
3497
3498
0
    if (InvalidDecl) {
3499
0
      if (ShowDeclName)
3500
0
        Diag(Loc, diag::err_invalid_member_in_interface)
3501
0
          << (InvalidDecl-1) << Name;
3502
0
      else
3503
0
        Diag(Loc, diag::err_invalid_member_in_interface)
3504
0
          << (InvalidDecl-1) << "";
3505
0
      return nullptr;
3506
0
    }
3507
0
  }
3508
3509
  // C++ 9.2p6: A member shall not be declared to have automatic storage
3510
  // duration (auto, register) or with the extern storage-class-specifier.
3511
  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3512
  // data members and cannot be applied to names declared const or static,
3513
  // and cannot be applied to reference members.
3514
0
  switch (DS.getStorageClassSpec()) {
3515
0
  case DeclSpec::SCS_unspecified:
3516
0
  case DeclSpec::SCS_typedef:
3517
0
  case DeclSpec::SCS_static:
3518
0
    break;
3519
0
  case DeclSpec::SCS_mutable:
3520
0
    if (isFunc) {
3521
0
      Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3522
3523
      // FIXME: It would be nicer if the keyword was ignored only for this
3524
      // declarator. Otherwise we could get follow-up errors.
3525
0
      D.getMutableDeclSpec().ClearStorageClassSpecs();
3526
0
    }
3527
0
    break;
3528
0
  default:
3529
0
    Diag(DS.getStorageClassSpecLoc(),
3530
0
         diag::err_storageclass_invalid_for_member);
3531
0
    D.getMutableDeclSpec().ClearStorageClassSpecs();
3532
0
    break;
3533
0
  }
3534
3535
0
  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3536
0
                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3537
0
                      !isFunc);
3538
3539
0
  if (DS.hasConstexprSpecifier() && isInstField) {
3540
0
    SemaDiagnosticBuilder B =
3541
0
        Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3542
0
    SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3543
0
    if (InitStyle == ICIS_NoInit) {
3544
0
      B << 0 << 0;
3545
0
      if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3546
0
        B << FixItHint::CreateRemoval(ConstexprLoc);
3547
0
      else {
3548
0
        B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3549
0
        D.getMutableDeclSpec().ClearConstexprSpec();
3550
0
        const char *PrevSpec;
3551
0
        unsigned DiagID;
3552
0
        bool Failed = D.getMutableDeclSpec().SetTypeQual(
3553
0
            DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3554
0
        (void)Failed;
3555
0
        assert(!Failed && "Making a constexpr member const shouldn't fail");
3556
0
      }
3557
0
    } else {
3558
0
      B << 1;
3559
0
      const char *PrevSpec;
3560
0
      unsigned DiagID;
3561
0
      if (D.getMutableDeclSpec().SetStorageClassSpec(
3562
0
          *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3563
0
          Context.getPrintingPolicy())) {
3564
0
        assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3565
0
               "This is the only DeclSpec that should fail to be applied");
3566
0
        B << 1;
3567
0
      } else {
3568
0
        B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3569
0
        isInstField = false;
3570
0
      }
3571
0
    }
3572
0
  }
3573
3574
0
  NamedDecl *Member;
3575
0
  if (isInstField) {
3576
0
    CXXScopeSpec &SS = D.getCXXScopeSpec();
3577
3578
    // Data members must have identifiers for names.
3579
0
    if (!Name.isIdentifier()) {
3580
0
      Diag(Loc, diag::err_bad_variable_name)
3581
0
        << Name;
3582
0
      return nullptr;
3583
0
    }
3584
3585
0
    IdentifierInfo *II = Name.getAsIdentifierInfo();
3586
3587
    // Member field could not be with "template" keyword.
3588
    // So TemplateParameterLists should be empty in this case.
3589
0
    if (TemplateParameterLists.size()) {
3590
0
      TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3591
0
      if (TemplateParams->size()) {
3592
        // There is no such thing as a member field template.
3593
0
        Diag(D.getIdentifierLoc(), diag::err_template_member)
3594
0
            << II
3595
0
            << SourceRange(TemplateParams->getTemplateLoc(),
3596
0
                TemplateParams->getRAngleLoc());
3597
0
      } else {
3598
        // There is an extraneous 'template<>' for this member.
3599
0
        Diag(TemplateParams->getTemplateLoc(),
3600
0
            diag::err_template_member_noparams)
3601
0
            << II
3602
0
            << SourceRange(TemplateParams->getTemplateLoc(),
3603
0
                TemplateParams->getRAngleLoc());
3604
0
      }
3605
0
      return nullptr;
3606
0
    }
3607
3608
0
    if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3609
0
      Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3610
0
          << II
3611
0
          << SourceRange(D.getName().TemplateId->LAngleLoc,
3612
0
                         D.getName().TemplateId->RAngleLoc)
3613
0
          << D.getName().TemplateId->LAngleLoc;
3614
0
      D.SetIdentifier(II, Loc);
3615
0
    }
3616
3617
0
    if (SS.isSet() && !SS.isInvalid()) {
3618
      // The user provided a superfluous scope specifier inside a class
3619
      // definition:
3620
      //
3621
      // class X {
3622
      //   int X::member;
3623
      // };
3624
0
      if (DeclContext *DC = computeDeclContext(SS, false))
3625
0
        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3626
0
                                     D.getName().getKind() ==
3627
0
                                         UnqualifiedIdKind::IK_TemplateId);
3628
0
      else
3629
0
        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3630
0
          << Name << SS.getRange();
3631
3632
0
      SS.clear();
3633
0
    }
3634
3635
0
    if (MSPropertyAttr) {
3636
0
      Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3637
0
                                BitWidth, InitStyle, AS, *MSPropertyAttr);
3638
0
      if (!Member)
3639
0
        return nullptr;
3640
0
      isInstField = false;
3641
0
    } else {
3642
0
      Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3643
0
                                BitWidth, InitStyle, AS);
3644
0
      if (!Member)
3645
0
        return nullptr;
3646
0
    }
3647
3648
0
    CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3649
0
  } else {
3650
0
    Member = HandleDeclarator(S, D, TemplateParameterLists);
3651
0
    if (!Member)
3652
0
      return nullptr;
3653
3654
    // Non-instance-fields can't have a bitfield.
3655
0
    if (BitWidth) {
3656
0
      if (Member->isInvalidDecl()) {
3657
        // don't emit another diagnostic.
3658
0
      } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3659
        // C++ 9.6p3: A bit-field shall not be a static member.
3660
        // "static member 'A' cannot be a bit-field"
3661
0
        Diag(Loc, diag::err_static_not_bitfield)
3662
0
          << Name << BitWidth->getSourceRange();
3663
0
      } else if (isa<TypedefDecl>(Member)) {
3664
        // "typedef member 'x' cannot be a bit-field"
3665
0
        Diag(Loc, diag::err_typedef_not_bitfield)
3666
0
          << Name << BitWidth->getSourceRange();
3667
0
      } else {
3668
        // A function typedef ("typedef int f(); f a;").
3669
        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3670
0
        Diag(Loc, diag::err_not_integral_type_bitfield)
3671
0
          << Name << cast<ValueDecl>(Member)->getType()
3672
0
          << BitWidth->getSourceRange();
3673
0
      }
3674
3675
0
      BitWidth = nullptr;
3676
0
      Member->setInvalidDecl();
3677
0
    }
3678
3679
0
    NamedDecl *NonTemplateMember = Member;
3680
0
    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3681
0
      NonTemplateMember = FunTmpl->getTemplatedDecl();
3682
0
    else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3683
0
      NonTemplateMember = VarTmpl->getTemplatedDecl();
3684
3685
0
    Member->setAccess(AS);
3686
3687
    // If we have declared a member function template or static data member
3688
    // template, set the access of the templated declaration as well.
3689
0
    if (NonTemplateMember != Member)
3690
0
      NonTemplateMember->setAccess(AS);
3691
3692
    // C++ [temp.deduct.guide]p3:
3693
    //   A deduction guide [...] for a member class template [shall be
3694
    //   declared] with the same access [as the template].
3695
0
    if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3696
0
      auto *TD = DG->getDeducedTemplate();
3697
      // Access specifiers are only meaningful if both the template and the
3698
      // deduction guide are from the same scope.
3699
0
      if (AS != TD->getAccess() &&
3700
0
          TD->getDeclContext()->getRedeclContext()->Equals(
3701
0
              DG->getDeclContext()->getRedeclContext())) {
3702
0
        Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3703
0
        Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3704
0
            << TD->getAccess();
3705
0
        const AccessSpecDecl *LastAccessSpec = nullptr;
3706
0
        for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3707
0
          if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3708
0
            LastAccessSpec = AccessSpec;
3709
0
        }
3710
0
        assert(LastAccessSpec && "differing access with no access specifier");
3711
0
        Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3712
0
            << AS;
3713
0
      }
3714
0
    }
3715
0
  }
3716
3717
0
  if (VS.isOverrideSpecified())
3718
0
    Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3719
0
  if (VS.isFinalSpecified())
3720
0
    Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3721
0
                                      VS.isFinalSpelledSealed()
3722
0
                                          ? FinalAttr::Keyword_sealed
3723
0
                                          : FinalAttr::Keyword_final));
3724
3725
0
  if (VS.getLastLocation().isValid()) {
3726
    // Update the end location of a method that has a virt-specifiers.
3727
0
    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3728
0
      MD->setRangeEnd(VS.getLastLocation());
3729
0
  }
3730
3731
0
  CheckOverrideControl(Member);
3732
3733
0
  assert((Name || isInstField) && "No identifier for non-field ?");
3734
3735
0
  if (isInstField) {
3736
0
    FieldDecl *FD = cast<FieldDecl>(Member);
3737
0
    FieldCollector->Add(FD);
3738
3739
0
    if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3740
      // Remember all explicit private FieldDecls that have a name, no side
3741
      // effects and are not part of a dependent type declaration.
3742
3743
0
      auto DeclHasUnusedAttr = [](const QualType &T) {
3744
0
        if (const TagDecl *TD = T->getAsTagDecl())
3745
0
          return TD->hasAttr<UnusedAttr>();
3746
0
        if (const TypedefType *TDT = T->getAs<TypedefType>())
3747
0
          return TDT->getDecl()->hasAttr<UnusedAttr>();
3748
0
        return false;
3749
0
      };
3750
3751
0
      if (!FD->isImplicit() && FD->getDeclName() &&
3752
0
          FD->getAccess() == AS_private &&
3753
0
          !FD->hasAttr<UnusedAttr>() &&
3754
0
          !FD->getParent()->isDependentContext() &&
3755
0
          !DeclHasUnusedAttr(FD->getType()) &&
3756
0
          !InitializationHasSideEffects(*FD))
3757
0
        UnusedPrivateFields.insert(FD);
3758
0
    }
3759
0
  }
3760
3761
0
  return Member;
3762
0
}
3763
3764
namespace {
3765
  class UninitializedFieldVisitor
3766
      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3767
    Sema &S;
3768
    // List of Decls to generate a warning on.  Also remove Decls that become
3769
    // initialized.
3770
    llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3771
    // List of base classes of the record.  Classes are removed after their
3772
    // initializers.
3773
    llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3774
    // Vector of decls to be removed from the Decl set prior to visiting the
3775
    // nodes.  These Decls may have been initialized in the prior initializer.
3776
    llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3777
    // If non-null, add a note to the warning pointing back to the constructor.
3778
    const CXXConstructorDecl *Constructor;
3779
    // Variables to hold state when processing an initializer list.  When
3780
    // InitList is true, special case initialization of FieldDecls matching
3781
    // InitListFieldDecl.
3782
    bool InitList;
3783
    FieldDecl *InitListFieldDecl;
3784
    llvm::SmallVector<unsigned, 4> InitFieldIndex;
3785
3786
  public:
3787
    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3788
    UninitializedFieldVisitor(Sema &S,
3789
                              llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3790
                              llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3791
      : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3792
0
        Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3793
3794
    // Returns true if the use of ME is not an uninitialized use.
3795
    bool IsInitListMemberExprInitialized(MemberExpr *ME,
3796
0
                                         bool CheckReferenceOnly) {
3797
0
      llvm::SmallVector<FieldDecl*, 4> Fields;
3798
0
      bool ReferenceField = false;
3799
0
      while (ME) {
3800
0
        FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3801
0
        if (!FD)
3802
0
          return false;
3803
0
        Fields.push_back(FD);
3804
0
        if (FD->getType()->isReferenceType())
3805
0
          ReferenceField = true;
3806
0
        ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3807
0
      }
3808
3809
      // Binding a reference to an uninitialized field is not an
3810
      // uninitialized use.
3811
0
      if (CheckReferenceOnly && !ReferenceField)
3812
0
        return true;
3813
3814
0
      llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3815
      // Discard the first field since it is the field decl that is being
3816
      // initialized.
3817
0
      for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3818
0
        UsedFieldIndex.push_back(FD->getFieldIndex());
3819
3820
0
      for (auto UsedIter = UsedFieldIndex.begin(),
3821
0
                UsedEnd = UsedFieldIndex.end(),
3822
0
                OrigIter = InitFieldIndex.begin(),
3823
0
                OrigEnd = InitFieldIndex.end();
3824
0
           UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3825
0
        if (*UsedIter < *OrigIter)
3826
0
          return true;
3827
0
        if (*UsedIter > *OrigIter)
3828
0
          break;
3829
0
      }
3830
3831
0
      return false;
3832
0
    }
3833
3834
    void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3835
0
                          bool AddressOf) {
3836
0
      if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3837
0
        return;
3838
3839
      // FieldME is the inner-most MemberExpr that is not an anonymous struct
3840
      // or union.
3841
0
      MemberExpr *FieldME = ME;
3842
3843
0
      bool AllPODFields = FieldME->getType().isPODType(S.Context);
3844
3845
0
      Expr *Base = ME;
3846
0
      while (MemberExpr *SubME =
3847
0
                 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3848
3849
0
        if (isa<VarDecl>(SubME->getMemberDecl()))
3850
0
          return;
3851
3852
0
        if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3853
0
          if (!FD->isAnonymousStructOrUnion())
3854
0
            FieldME = SubME;
3855
3856
0
        if (!FieldME->getType().isPODType(S.Context))
3857
0
          AllPODFields = false;
3858
3859
0
        Base = SubME->getBase();
3860
0
      }
3861
3862
0
      if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3863
0
        Visit(Base);
3864
0
        return;
3865
0
      }
3866
3867
0
      if (AddressOf && AllPODFields)
3868
0
        return;
3869
3870
0
      ValueDecl* FoundVD = FieldME->getMemberDecl();
3871
3872
0
      if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3873
0
        while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3874
0
          BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3875
0
        }
3876
3877
0
        if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3878
0
          QualType T = BaseCast->getType();
3879
0
          if (T->isPointerType() &&
3880
0
              BaseClasses.count(T->getPointeeType())) {
3881
0
            S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3882
0
                << T->getPointeeType() << FoundVD;
3883
0
          }
3884
0
        }
3885
0
      }
3886
3887
0
      if (!Decls.count(FoundVD))
3888
0
        return;
3889
3890
0
      const bool IsReference = FoundVD->getType()->isReferenceType();
3891
3892
0
      if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3893
        // Special checking for initializer lists.
3894
0
        if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3895
0
          return;
3896
0
        }
3897
0
      } else {
3898
        // Prevent double warnings on use of unbounded references.
3899
0
        if (CheckReferenceOnly && !IsReference)
3900
0
          return;
3901
0
      }
3902
3903
0
      unsigned diag = IsReference
3904
0
          ? diag::warn_reference_field_is_uninit
3905
0
          : diag::warn_field_is_uninit;
3906
0
      S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3907
0
      if (Constructor)
3908
0
        S.Diag(Constructor->getLocation(),
3909
0
               diag::note_uninit_in_this_constructor)
3910
0
          << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3911
3912
0
    }
3913
3914
0
    void HandleValue(Expr *E, bool AddressOf) {
3915
0
      E = E->IgnoreParens();
3916
3917
0
      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3918
0
        HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3919
0
                         AddressOf /*AddressOf*/);
3920
0
        return;
3921
0
      }
3922
3923
0
      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3924
0
        Visit(CO->getCond());
3925
0
        HandleValue(CO->getTrueExpr(), AddressOf);
3926
0
        HandleValue(CO->getFalseExpr(), AddressOf);
3927
0
        return;
3928
0
      }
3929
3930
0
      if (BinaryConditionalOperator *BCO =
3931
0
              dyn_cast<BinaryConditionalOperator>(E)) {
3932
0
        Visit(BCO->getCond());
3933
0
        HandleValue(BCO->getFalseExpr(), AddressOf);
3934
0
        return;
3935
0
      }
3936
3937
0
      if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3938
0
        HandleValue(OVE->getSourceExpr(), AddressOf);
3939
0
        return;
3940
0
      }
3941
3942
0
      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3943
0
        switch (BO->getOpcode()) {
3944
0
        default:
3945
0
          break;
3946
0
        case(BO_PtrMemD):
3947
0
        case(BO_PtrMemI):
3948
0
          HandleValue(BO->getLHS(), AddressOf);
3949
0
          Visit(BO->getRHS());
3950
0
          return;
3951
0
        case(BO_Comma):
3952
0
          Visit(BO->getLHS());
3953
0
          HandleValue(BO->getRHS(), AddressOf);
3954
0
          return;
3955
0
        }
3956
0
      }
3957
3958
0
      Visit(E);
3959
0
    }
3960
3961
0
    void CheckInitListExpr(InitListExpr *ILE) {
3962
0
      InitFieldIndex.push_back(0);
3963
0
      for (auto *Child : ILE->children()) {
3964
0
        if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3965
0
          CheckInitListExpr(SubList);
3966
0
        } else {
3967
0
          Visit(Child);
3968
0
        }
3969
0
        ++InitFieldIndex.back();
3970
0
      }
3971
0
      InitFieldIndex.pop_back();
3972
0
    }
3973
3974
    void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3975
0
                          FieldDecl *Field, const Type *BaseClass) {
3976
      // Remove Decls that may have been initialized in the previous
3977
      // initializer.
3978
0
      for (ValueDecl* VD : DeclsToRemove)
3979
0
        Decls.erase(VD);
3980
0
      DeclsToRemove.clear();
3981
3982
0
      Constructor = FieldConstructor;
3983
0
      InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3984
3985
0
      if (ILE && Field) {
3986
0
        InitList = true;
3987
0
        InitListFieldDecl = Field;
3988
0
        InitFieldIndex.clear();
3989
0
        CheckInitListExpr(ILE);
3990
0
      } else {
3991
0
        InitList = false;
3992
0
        Visit(E);
3993
0
      }
3994
3995
0
      if (Field)
3996
0
        Decls.erase(Field);
3997
0
      if (BaseClass)
3998
0
        BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3999
0
    }
4000
4001
0
    void VisitMemberExpr(MemberExpr *ME) {
4002
      // All uses of unbounded reference fields will warn.
4003
0
      HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
4004
0
    }
4005
4006
0
    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4007
0
      if (E->getCastKind() == CK_LValueToRValue) {
4008
0
        HandleValue(E->getSubExpr(), false /*AddressOf*/);
4009
0
        return;
4010
0
      }
4011
4012
0
      Inherited::VisitImplicitCastExpr(E);
4013
0
    }
4014
4015
0
    void VisitCXXConstructExpr(CXXConstructExpr *E) {
4016
0
      if (E->getConstructor()->isCopyConstructor()) {
4017
0
        Expr *ArgExpr = E->getArg(0);
4018
0
        if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
4019
0
          if (ILE->getNumInits() == 1)
4020
0
            ArgExpr = ILE->getInit(0);
4021
0
        if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4022
0
          if (ICE->getCastKind() == CK_NoOp)
4023
0
            ArgExpr = ICE->getSubExpr();
4024
0
        HandleValue(ArgExpr, false /*AddressOf*/);
4025
0
        return;
4026
0
      }
4027
0
      Inherited::VisitCXXConstructExpr(E);
4028
0
    }
4029
4030
0
    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4031
0
      Expr *Callee = E->getCallee();
4032
0
      if (isa<MemberExpr>(Callee)) {
4033
0
        HandleValue(Callee, false /*AddressOf*/);
4034
0
        for (auto *Arg : E->arguments())
4035
0
          Visit(Arg);
4036
0
        return;
4037
0
      }
4038
4039
0
      Inherited::VisitCXXMemberCallExpr(E);
4040
0
    }
4041
4042
0
    void VisitCallExpr(CallExpr *E) {
4043
      // Treat std::move as a use.
4044
0
      if (E->isCallToStdMove()) {
4045
0
        HandleValue(E->getArg(0), /*AddressOf=*/false);
4046
0
        return;
4047
0
      }
4048
4049
0
      Inherited::VisitCallExpr(E);
4050
0
    }
4051
4052
0
    void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4053
0
      Expr *Callee = E->getCallee();
4054
4055
0
      if (isa<UnresolvedLookupExpr>(Callee))
4056
0
        return Inherited::VisitCXXOperatorCallExpr(E);
4057
4058
0
      Visit(Callee);
4059
0
      for (auto *Arg : E->arguments())
4060
0
        HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4061
0
    }
4062
4063
0
    void VisitBinaryOperator(BinaryOperator *E) {
4064
      // If a field assignment is detected, remove the field from the
4065
      // uninitiailized field set.
4066
0
      if (E->getOpcode() == BO_Assign)
4067
0
        if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4068
0
          if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4069
0
            if (!FD->getType()->isReferenceType())
4070
0
              DeclsToRemove.push_back(FD);
4071
4072
0
      if (E->isCompoundAssignmentOp()) {
4073
0
        HandleValue(E->getLHS(), false /*AddressOf*/);
4074
0
        Visit(E->getRHS());
4075
0
        return;
4076
0
      }
4077
4078
0
      Inherited::VisitBinaryOperator(E);
4079
0
    }
4080
4081
0
    void VisitUnaryOperator(UnaryOperator *E) {
4082
0
      if (E->isIncrementDecrementOp()) {
4083
0
        HandleValue(E->getSubExpr(), false /*AddressOf*/);
4084
0
        return;
4085
0
      }
4086
0
      if (E->getOpcode() == UO_AddrOf) {
4087
0
        if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4088
0
          HandleValue(ME->getBase(), true /*AddressOf*/);
4089
0
          return;
4090
0
        }
4091
0
      }
4092
4093
0
      Inherited::VisitUnaryOperator(E);
4094
0
    }
4095
  };
4096
4097
  // Diagnose value-uses of fields to initialize themselves, e.g.
4098
  //   foo(foo)
4099
  // where foo is not also a parameter to the constructor.
4100
  // Also diagnose across field uninitialized use such as
4101
  //   x(y), y(x)
4102
  // TODO: implement -Wuninitialized and fold this into that framework.
4103
  static void DiagnoseUninitializedFields(
4104
0
      Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4105
4106
0
    if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4107
0
                                           Constructor->getLocation())) {
4108
0
      return;
4109
0
    }
4110
4111
0
    if (Constructor->isInvalidDecl())
4112
0
      return;
4113
4114
0
    const CXXRecordDecl *RD = Constructor->getParent();
4115
4116
0
    if (RD->isDependentContext())
4117
0
      return;
4118
4119
    // Holds fields that are uninitialized.
4120
0
    llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4121
4122
    // At the beginning, all fields are uninitialized.
4123
0
    for (auto *I : RD->decls()) {
4124
0
      if (auto *FD = dyn_cast<FieldDecl>(I)) {
4125
0
        UninitializedFields.insert(FD);
4126
0
      } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4127
0
        UninitializedFields.insert(IFD->getAnonField());
4128
0
      }
4129
0
    }
4130
4131
0
    llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4132
0
    for (const auto &I : RD->bases())
4133
0
      UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4134
4135
0
    if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4136
0
      return;
4137
4138
0
    UninitializedFieldVisitor UninitializedChecker(SemaRef,
4139
0
                                                   UninitializedFields,
4140
0
                                                   UninitializedBaseClasses);
4141
4142
0
    for (const auto *FieldInit : Constructor->inits()) {
4143
0
      if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4144
0
        break;
4145
4146
0
      Expr *InitExpr = FieldInit->getInit();
4147
0
      if (!InitExpr)
4148
0
        continue;
4149
4150
0
      if (CXXDefaultInitExpr *Default =
4151
0
              dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4152
0
        InitExpr = Default->getExpr();
4153
0
        if (!InitExpr)
4154
0
          continue;
4155
        // In class initializers will point to the constructor.
4156
0
        UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4157
0
                                              FieldInit->getAnyMember(),
4158
0
                                              FieldInit->getBaseClass());
4159
0
      } else {
4160
0
        UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4161
0
                                              FieldInit->getAnyMember(),
4162
0
                                              FieldInit->getBaseClass());
4163
0
      }
4164
0
    }
4165
0
  }
4166
} // namespace
4167
4168
/// Enter a new C++ default initializer scope. After calling this, the
4169
/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
4170
/// parsing or instantiating the initializer failed.
4171
0
void Sema::ActOnStartCXXInClassMemberInitializer() {
4172
  // Create a synthetic function scope to represent the call to the constructor
4173
  // that notionally surrounds a use of this initializer.
4174
0
  PushFunctionScope();
4175
0
}
4176
4177
0
void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4178
0
  if (!D.isFunctionDeclarator())
4179
0
    return;
4180
0
  auto &FTI = D.getFunctionTypeInfo();
4181
0
  if (!FTI.Params)
4182
0
    return;
4183
0
  for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4184
0
                                                          FTI.NumParams)) {
4185
0
    auto *ParamDecl = cast<NamedDecl>(Param.Param);
4186
0
    if (ParamDecl->getDeclName())
4187
0
      PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4188
0
  }
4189
0
}
4190
4191
0
ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4192
0
  return ActOnRequiresClause(ConstraintExpr);
4193
0
}
4194
4195
0
ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4196
0
  if (ConstraintExpr.isInvalid())
4197
0
    return ExprError();
4198
4199
0
  ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4200
0
  if (ConstraintExpr.isInvalid())
4201
0
    return ExprError();
4202
4203
0
  if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4204
0
                                      UPPC_RequiresClause))
4205
0
    return ExprError();
4206
4207
0
  return ConstraintExpr;
4208
0
}
4209
4210
ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4211
                                                    Expr *InitExpr,
4212
0
                                                    SourceLocation InitLoc) {
4213
0
  InitializedEntity Entity =
4214
0
      InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4215
0
  InitializationKind Kind =
4216
0
      FD->getInClassInitStyle() == ICIS_ListInit
4217
0
          ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4218
0
                                                 InitExpr->getBeginLoc(),
4219
0
                                                 InitExpr->getEndLoc())
4220
0
          : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4221
0
  InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4222
0
  return Seq.Perform(*this, Entity, Kind, InitExpr);
4223
0
}
4224
4225
/// This is invoked after parsing an in-class initializer for a
4226
/// non-static C++ class member, and after instantiating an in-class initializer
4227
/// in a class template. Such actions are deferred until the class is complete.
4228
void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4229
                                                  SourceLocation InitLoc,
4230
0
                                                  Expr *InitExpr) {
4231
  // Pop the notional constructor scope we created earlier.
4232
0
  PopFunctionScopeInfo(nullptr, D);
4233
4234
0
  FieldDecl *FD = dyn_cast<FieldDecl>(D);
4235
0
  assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4236
0
         "must set init style when field is created");
4237
4238
0
  if (!InitExpr) {
4239
0
    D->setInvalidDecl();
4240
0
    if (FD)
4241
0
      FD->removeInClassInitializer();
4242
0
    return;
4243
0
  }
4244
4245
0
  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
4246
0
    FD->setInvalidDecl();
4247
0
    FD->removeInClassInitializer();
4248
0
    return;
4249
0
  }
4250
4251
0
  ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
4252
0
                                              /*RecoverUncorrectedTypos=*/true);
4253
0
  assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4254
0
  if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4255
0
    Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
4256
    // C++11 [class.base.init]p7:
4257
    //   The initialization of each base and member constitutes a
4258
    //   full-expression.
4259
0
    if (!Init.isInvalid())
4260
0
      Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4261
0
    if (Init.isInvalid()) {
4262
0
      FD->setInvalidDecl();
4263
0
      return;
4264
0
    }
4265
0
  }
4266
4267
0
  FD->setInClassInitializer(Init.get());
4268
0
}
4269
4270
/// Find the direct and/or virtual base specifiers that
4271
/// correspond to the given base type, for use in base initialization
4272
/// within a constructor.
4273
static bool FindBaseInitializer(Sema &SemaRef,
4274
                                CXXRecordDecl *ClassDecl,
4275
                                QualType BaseType,
4276
                                const CXXBaseSpecifier *&DirectBaseSpec,
4277
0
                                const CXXBaseSpecifier *&VirtualBaseSpec) {
4278
  // First, check for a direct base class.
4279
0
  DirectBaseSpec = nullptr;
4280
0
  for (const auto &Base : ClassDecl->bases()) {
4281
0
    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4282
      // We found a direct base of this type. That's what we're
4283
      // initializing.
4284
0
      DirectBaseSpec = &Base;
4285
0
      break;
4286
0
    }
4287
0
  }
4288
4289
  // Check for a virtual base class.
4290
  // FIXME: We might be able to short-circuit this if we know in advance that
4291
  // there are no virtual bases.
4292
0
  VirtualBaseSpec = nullptr;
4293
0
  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4294
    // We haven't found a base yet; search the class hierarchy for a
4295
    // virtual base class.
4296
0
    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4297
0
                       /*DetectVirtual=*/false);
4298
0
    if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4299
0
                              SemaRef.Context.getTypeDeclType(ClassDecl),
4300
0
                              BaseType, Paths)) {
4301
0
      for (CXXBasePaths::paths_iterator Path = Paths.begin();
4302
0
           Path != Paths.end(); ++Path) {
4303
0
        if (Path->back().Base->isVirtual()) {
4304
0
          VirtualBaseSpec = Path->back().Base;
4305
0
          break;
4306
0
        }
4307
0
      }
4308
0
    }
4309
0
  }
4310
4311
0
  return DirectBaseSpec || VirtualBaseSpec;
4312
0
}
4313
4314
/// Handle a C++ member initializer using braced-init-list syntax.
4315
MemInitResult
4316
Sema::ActOnMemInitializer(Decl *ConstructorD,
4317
                          Scope *S,
4318
                          CXXScopeSpec &SS,
4319
                          IdentifierInfo *MemberOrBase,
4320
                          ParsedType TemplateTypeTy,
4321
                          const DeclSpec &DS,
4322
                          SourceLocation IdLoc,
4323
                          Expr *InitList,
4324
0
                          SourceLocation EllipsisLoc) {
4325
0
  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4326
0
                             DS, IdLoc, InitList,
4327
0
                             EllipsisLoc);
4328
0
}
4329
4330
/// Handle a C++ member initializer using parentheses syntax.
4331
MemInitResult
4332
Sema::ActOnMemInitializer(Decl *ConstructorD,
4333
                          Scope *S,
4334
                          CXXScopeSpec &SS,
4335
                          IdentifierInfo *MemberOrBase,
4336
                          ParsedType TemplateTypeTy,
4337
                          const DeclSpec &DS,
4338
                          SourceLocation IdLoc,
4339
                          SourceLocation LParenLoc,
4340
                          ArrayRef<Expr *> Args,
4341
                          SourceLocation RParenLoc,
4342
0
                          SourceLocation EllipsisLoc) {
4343
0
  Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4344
0
  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4345
0
                             DS, IdLoc, List, EllipsisLoc);
4346
0
}
4347
4348
namespace {
4349
4350
// Callback to only accept typo corrections that can be a valid C++ member
4351
// initializer: either a non-static field member or a base class.
4352
class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4353
public:
4354
  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4355
0
      : ClassDecl(ClassDecl) {}
4356
4357
0
  bool ValidateCandidate(const TypoCorrection &candidate) override {
4358
0
    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4359
0
      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4360
0
        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4361
0
      return isa<TypeDecl>(ND);
4362
0
    }
4363
0
    return false;
4364
0
  }
4365
4366
0
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
4367
0
    return std::make_unique<MemInitializerValidatorCCC>(*this);
4368
0
  }
4369
4370
private:
4371
  CXXRecordDecl *ClassDecl;
4372
};
4373
4374
}
4375
4376
bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
4377
                                             RecordDecl *ClassDecl,
4378
0
                                             const IdentifierInfo *Name) {
4379
0
  DeclContextLookupResult Result = ClassDecl->lookup(Name);
4380
0
  DeclContextLookupResult::iterator Found =
4381
0
      llvm::find_if(Result, [this](const NamedDecl *Elem) {
4382
0
        return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4383
0
               Elem->isPlaceholderVar(getLangOpts());
4384
0
      });
4385
  // We did not find a placeholder variable
4386
0
  if (Found == Result.end())
4387
0
    return false;
4388
0
  Diag(Loc, diag::err_using_placeholder_variable) << Name;
4389
0
  for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4390
0
    const NamedDecl *ND = *It;
4391
0
    if (ND->getDeclContext() != ND->getDeclContext())
4392
0
      break;
4393
0
    if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4394
0
        ND->isPlaceholderVar(getLangOpts()))
4395
0
      Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4396
0
  }
4397
0
  return true;
4398
0
}
4399
4400
ValueDecl *
4401
Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4402
0
                                    const IdentifierInfo *MemberOrBase) {
4403
0
  ValueDecl *ND = nullptr;
4404
0
  for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4405
0
    if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4406
0
      bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4407
0
      if (ND) {
4408
0
        if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4409
0
          return nullptr;
4410
0
        break;
4411
0
      }
4412
0
      if (!IsPlaceholder)
4413
0
        return cast<ValueDecl>(D);
4414
0
      ND = cast<ValueDecl>(D);
4415
0
    }
4416
0
  }
4417
0
  return ND;
4418
0
}
4419
4420
ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4421
                                             CXXScopeSpec &SS,
4422
                                             ParsedType TemplateTypeTy,
4423
0
                                             IdentifierInfo *MemberOrBase) {
4424
0
  if (SS.getScopeRep() || TemplateTypeTy)
4425
0
    return nullptr;
4426
0
  return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4427
0
}
4428
4429
/// Handle a C++ member initializer.
4430
MemInitResult
4431
Sema::BuildMemInitializer(Decl *ConstructorD,
4432
                          Scope *S,
4433
                          CXXScopeSpec &SS,
4434
                          IdentifierInfo *MemberOrBase,
4435
                          ParsedType TemplateTypeTy,
4436
                          const DeclSpec &DS,
4437
                          SourceLocation IdLoc,
4438
                          Expr *Init,
4439
0
                          SourceLocation EllipsisLoc) {
4440
0
  ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4441
0
                                             /*RecoverUncorrectedTypos=*/true);
4442
0
  if (!Res.isUsable())
4443
0
    return true;
4444
0
  Init = Res.get();
4445
4446
0
  if (!ConstructorD)
4447
0
    return true;
4448
4449
0
  AdjustDeclIfTemplate(ConstructorD);
4450
4451
0
  CXXConstructorDecl *Constructor
4452
0
    = dyn_cast<CXXConstructorDecl>(ConstructorD);
4453
0
  if (!Constructor) {
4454
    // The user wrote a constructor initializer on a function that is
4455
    // not a C++ constructor. Ignore the error for now, because we may
4456
    // have more member initializers coming; we'll diagnose it just
4457
    // once in ActOnMemInitializers.
4458
0
    return true;
4459
0
  }
4460
4461
0
  CXXRecordDecl *ClassDecl = Constructor->getParent();
4462
4463
  // C++ [class.base.init]p2:
4464
  //   Names in a mem-initializer-id are looked up in the scope of the
4465
  //   constructor's class and, if not found in that scope, are looked
4466
  //   up in the scope containing the constructor's definition.
4467
  //   [Note: if the constructor's class contains a member with the
4468
  //   same name as a direct or virtual base class of the class, a
4469
  //   mem-initializer-id naming the member or base class and composed
4470
  //   of a single identifier refers to the class member. A
4471
  //   mem-initializer-id for the hidden base class may be specified
4472
  //   using a qualified name. ]
4473
4474
  // Look for a member, first.
4475
0
  if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4476
0
          ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4477
0
    if (EllipsisLoc.isValid())
4478
0
      Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4479
0
          << MemberOrBase
4480
0
          << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4481
4482
0
    return BuildMemberInitializer(Member, Init, IdLoc);
4483
0
  }
4484
  // It didn't name a member, so see if it names a class.
4485
0
  QualType BaseType;
4486
0
  TypeSourceInfo *TInfo = nullptr;
4487
4488
0
  if (TemplateTypeTy) {
4489
0
    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4490
0
    if (BaseType.isNull())
4491
0
      return true;
4492
0
  } else if (DS.getTypeSpecType() == TST_decltype) {
4493
0
    BaseType = BuildDecltypeType(DS.getRepAsExpr());
4494
0
  } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4495
0
    Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4496
0
    return true;
4497
0
  } else {
4498
0
    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4499
0
    LookupParsedName(R, S, &SS);
4500
4501
0
    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4502
0
    if (!TyD) {
4503
0
      if (R.isAmbiguous()) return true;
4504
4505
      // We don't want access-control diagnostics here.
4506
0
      R.suppressDiagnostics();
4507
4508
0
      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4509
0
        bool NotUnknownSpecialization = false;
4510
0
        DeclContext *DC = computeDeclContext(SS, false);
4511
0
        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4512
0
          NotUnknownSpecialization = !Record->hasAnyDependentBases();
4513
4514
0
        if (!NotUnknownSpecialization) {
4515
          // When the scope specifier can refer to a member of an unknown
4516
          // specialization, we take it as a type name.
4517
0
          BaseType = CheckTypenameType(
4518
0
              ElaboratedTypeKeyword::None, SourceLocation(),
4519
0
              SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4520
0
          if (BaseType.isNull())
4521
0
            return true;
4522
4523
0
          TInfo = Context.CreateTypeSourceInfo(BaseType);
4524
0
          DependentNameTypeLoc TL =
4525
0
              TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4526
0
          if (!TL.isNull()) {
4527
0
            TL.setNameLoc(IdLoc);
4528
0
            TL.setElaboratedKeywordLoc(SourceLocation());
4529
0
            TL.setQualifierLoc(SS.getWithLocInContext(Context));
4530
0
          }
4531
4532
0
          R.clear();
4533
0
          R.setLookupName(MemberOrBase);
4534
0
        }
4535
0
      }
4536
4537
0
      if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4538
0
        if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4539
0
          auto *TempSpec = cast<TemplateSpecializationType>(
4540
0
              UnqualifiedBase->getInjectedClassNameSpecialization());
4541
0
          TemplateName TN = TempSpec->getTemplateName();
4542
0
          for (auto const &Base : ClassDecl->bases()) {
4543
0
            auto BaseTemplate =
4544
0
                Base.getType()->getAs<TemplateSpecializationType>();
4545
0
            if (BaseTemplate && Context.hasSameTemplateName(
4546
0
                                    BaseTemplate->getTemplateName(), TN)) {
4547
0
              Diag(IdLoc, diag::ext_unqualified_base_class)
4548
0
                  << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4549
0
              BaseType = Base.getType();
4550
0
              break;
4551
0
            }
4552
0
          }
4553
0
        }
4554
0
      }
4555
4556
      // If no results were found, try to correct typos.
4557
0
      TypoCorrection Corr;
4558
0
      MemInitializerValidatorCCC CCC(ClassDecl);
4559
0
      if (R.empty() && BaseType.isNull() &&
4560
0
          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4561
0
                              CCC, CTK_ErrorRecovery, ClassDecl))) {
4562
0
        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4563
          // We have found a non-static data member with a similar
4564
          // name to what was typed; complain and initialize that
4565
          // member.
4566
0
          diagnoseTypo(Corr,
4567
0
                       PDiag(diag::err_mem_init_not_member_or_class_suggest)
4568
0
                         << MemberOrBase << true);
4569
0
          return BuildMemberInitializer(Member, Init, IdLoc);
4570
0
        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4571
0
          const CXXBaseSpecifier *DirectBaseSpec;
4572
0
          const CXXBaseSpecifier *VirtualBaseSpec;
4573
0
          if (FindBaseInitializer(*this, ClassDecl,
4574
0
                                  Context.getTypeDeclType(Type),
4575
0
                                  DirectBaseSpec, VirtualBaseSpec)) {
4576
            // We have found a direct or virtual base class with a
4577
            // similar name to what was typed; complain and initialize
4578
            // that base class.
4579
0
            diagnoseTypo(Corr,
4580
0
                         PDiag(diag::err_mem_init_not_member_or_class_suggest)
4581
0
                           << MemberOrBase << false,
4582
0
                         PDiag() /*Suppress note, we provide our own.*/);
4583
4584
0
            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4585
0
                                                              : VirtualBaseSpec;
4586
0
            Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4587
0
                << BaseSpec->getType() << BaseSpec->getSourceRange();
4588
4589
0
            TyD = Type;
4590
0
          }
4591
0
        }
4592
0
      }
4593
4594
0
      if (!TyD && BaseType.isNull()) {
4595
0
        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4596
0
          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4597
0
        return true;
4598
0
      }
4599
0
    }
4600
4601
0
    if (BaseType.isNull()) {
4602
0
      BaseType = getElaboratedType(ElaboratedTypeKeyword::None, SS,
4603
0
                                   Context.getTypeDeclType(TyD));
4604
0
      MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4605
0
      TInfo = Context.CreateTypeSourceInfo(BaseType);
4606
0
      ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4607
0
      TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4608
0
      TL.setElaboratedKeywordLoc(SourceLocation());
4609
0
      TL.setQualifierLoc(SS.getWithLocInContext(Context));
4610
0
    }
4611
0
  }
4612
4613
0
  if (!TInfo)
4614
0
    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4615
4616
0
  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4617
0
}
4618
4619
MemInitResult
4620
Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4621
0
                             SourceLocation IdLoc) {
4622
0
  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4623
0
  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4624
0
  assert((DirectMember || IndirectMember) &&
4625
0
         "Member must be a FieldDecl or IndirectFieldDecl");
4626
4627
0
  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4628
0
    return true;
4629
4630
0
  if (Member->isInvalidDecl())
4631
0
    return true;
4632
4633
0
  MultiExprArg Args;
4634
0
  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4635
0
    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4636
0
  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4637
0
    Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4638
0
  } else {
4639
    // Template instantiation doesn't reconstruct ParenListExprs for us.
4640
0
    Args = Init;
4641
0
  }
4642
4643
0
  SourceRange InitRange = Init->getSourceRange();
4644
4645
0
  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4646
    // Can't check initialization for a member of dependent type or when
4647
    // any of the arguments are type-dependent expressions.
4648
0
    DiscardCleanupsInEvaluationContext();
4649
0
  } else {
4650
0
    bool InitList = false;
4651
0
    if (isa<InitListExpr>(Init)) {
4652
0
      InitList = true;
4653
0
      Args = Init;
4654
0
    }
4655
4656
    // Initialize the member.
4657
0
    InitializedEntity MemberEntity =
4658
0
      DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4659
0
                   : InitializedEntity::InitializeMember(IndirectMember,
4660
0
                                                         nullptr);
4661
0
    InitializationKind Kind =
4662
0
        InitList ? InitializationKind::CreateDirectList(
4663
0
                       IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4664
0
                 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4665
0
                                                    InitRange.getEnd());
4666
4667
0
    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4668
0
    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4669
0
                                            nullptr);
4670
0
    if (!MemberInit.isInvalid()) {
4671
      // C++11 [class.base.init]p7:
4672
      //   The initialization of each base and member constitutes a
4673
      //   full-expression.
4674
0
      MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4675
0
                                       /*DiscardedValue*/ false);
4676
0
    }
4677
4678
0
    if (MemberInit.isInvalid()) {
4679
      // Args were sensible expressions but we couldn't initialize the member
4680
      // from them. Preserve them in a RecoveryExpr instead.
4681
0
      Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4682
0
                                Member->getType())
4683
0
                 .get();
4684
0
      if (!Init)
4685
0
        return true;
4686
0
    } else {
4687
0
      Init = MemberInit.get();
4688
0
    }
4689
0
  }
4690
4691
0
  if (DirectMember) {
4692
0
    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4693
0
                                            InitRange.getBegin(), Init,
4694
0
                                            InitRange.getEnd());
4695
0
  } else {
4696
0
    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4697
0
                                            InitRange.getBegin(), Init,
4698
0
                                            InitRange.getEnd());
4699
0
  }
4700
0
}
4701
4702
MemInitResult
4703
Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4704
0
                                 CXXRecordDecl *ClassDecl) {
4705
0
  SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4706
0
  if (!LangOpts.CPlusPlus11)
4707
0
    return Diag(NameLoc, diag::err_delegating_ctor)
4708
0
           << TInfo->getTypeLoc().getSourceRange();
4709
0
  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4710
4711
0
  bool InitList = true;
4712
0
  MultiExprArg Args = Init;
4713
0
  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4714
0
    InitList = false;
4715
0
    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4716
0
  }
4717
4718
0
  SourceRange InitRange = Init->getSourceRange();
4719
  // Initialize the object.
4720
0
  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4721
0
                                     QualType(ClassDecl->getTypeForDecl(), 0));
4722
0
  InitializationKind Kind =
4723
0
      InitList ? InitializationKind::CreateDirectList(
4724
0
                     NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4725
0
               : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4726
0
                                                  InitRange.getEnd());
4727
0
  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4728
0
  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4729
0
                                              Args, nullptr);
4730
0
  if (!DelegationInit.isInvalid()) {
4731
0
    assert((DelegationInit.get()->containsErrors() ||
4732
0
            cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4733
0
           "Delegating constructor with no target?");
4734
4735
    // C++11 [class.base.init]p7:
4736
    //   The initialization of each base and member constitutes a
4737
    //   full-expression.
4738
0
    DelegationInit = ActOnFinishFullExpr(
4739
0
        DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4740
0
  }
4741
4742
0
  if (DelegationInit.isInvalid()) {
4743
0
    DelegationInit =
4744
0
        CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4745
0
                           QualType(ClassDecl->getTypeForDecl(), 0));
4746
0
    if (DelegationInit.isInvalid())
4747
0
      return true;
4748
0
  } else {
4749
    // If we are in a dependent context, template instantiation will
4750
    // perform this type-checking again. Just save the arguments that we
4751
    // received in a ParenListExpr.
4752
    // FIXME: This isn't quite ideal, since our ASTs don't capture all
4753
    // of the information that we have about the base
4754
    // initializer. However, deconstructing the ASTs is a dicey process,
4755
    // and this approach is far more likely to get the corner cases right.
4756
0
    if (CurContext->isDependentContext())
4757
0
      DelegationInit = Init;
4758
0
  }
4759
4760
0
  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4761
0
                                          DelegationInit.getAs<Expr>(),
4762
0
                                          InitRange.getEnd());
4763
0
}
4764
4765
MemInitResult
4766
Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4767
                           Expr *Init, CXXRecordDecl *ClassDecl,
4768
0
                           SourceLocation EllipsisLoc) {
4769
0
  SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4770
4771
0
  if (!BaseType->isDependentType() && !BaseType->isRecordType())
4772
0
    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4773
0
           << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4774
4775
  // C++ [class.base.init]p2:
4776
  //   [...] Unless the mem-initializer-id names a nonstatic data
4777
  //   member of the constructor's class or a direct or virtual base
4778
  //   of that class, the mem-initializer is ill-formed. A
4779
  //   mem-initializer-list can initialize a base class using any
4780
  //   name that denotes that base class type.
4781
4782
  // We can store the initializers in "as-written" form and delay analysis until
4783
  // instantiation if the constructor is dependent. But not for dependent
4784
  // (broken) code in a non-template! SetCtorInitializers does not expect this.
4785
0
  bool Dependent = CurContext->isDependentContext() &&
4786
0
                   (BaseType->isDependentType() || Init->isTypeDependent());
4787
4788
0
  SourceRange InitRange = Init->getSourceRange();
4789
0
  if (EllipsisLoc.isValid()) {
4790
    // This is a pack expansion.
4791
0
    if (!BaseType->containsUnexpandedParameterPack())  {
4792
0
      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4793
0
        << SourceRange(BaseLoc, InitRange.getEnd());
4794
4795
0
      EllipsisLoc = SourceLocation();
4796
0
    }
4797
0
  } else {
4798
    // Check for any unexpanded parameter packs.
4799
0
    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4800
0
      return true;
4801
4802
0
    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4803
0
      return true;
4804
0
  }
4805
4806
  // Check for direct and virtual base classes.
4807
0
  const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4808
0
  const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4809
0
  if (!Dependent) {
4810
0
    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4811
0
                                       BaseType))
4812
0
      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4813
4814
0
    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4815
0
                        VirtualBaseSpec);
4816
4817
    // C++ [base.class.init]p2:
4818
    // Unless the mem-initializer-id names a nonstatic data member of the
4819
    // constructor's class or a direct or virtual base of that class, the
4820
    // mem-initializer is ill-formed.
4821
0
    if (!DirectBaseSpec && !VirtualBaseSpec) {
4822
      // If the class has any dependent bases, then it's possible that
4823
      // one of those types will resolve to the same type as
4824
      // BaseType. Therefore, just treat this as a dependent base
4825
      // class initialization.  FIXME: Should we try to check the
4826
      // initialization anyway? It seems odd.
4827
0
      if (ClassDecl->hasAnyDependentBases())
4828
0
        Dependent = true;
4829
0
      else
4830
0
        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4831
0
               << BaseType << Context.getTypeDeclType(ClassDecl)
4832
0
               << BaseTInfo->getTypeLoc().getSourceRange();
4833
0
    }
4834
0
  }
4835
4836
0
  if (Dependent) {
4837
0
    DiscardCleanupsInEvaluationContext();
4838
4839
0
    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4840
0
                                            /*IsVirtual=*/false,
4841
0
                                            InitRange.getBegin(), Init,
4842
0
                                            InitRange.getEnd(), EllipsisLoc);
4843
0
  }
4844
4845
  // C++ [base.class.init]p2:
4846
  //   If a mem-initializer-id is ambiguous because it designates both
4847
  //   a direct non-virtual base class and an inherited virtual base
4848
  //   class, the mem-initializer is ill-formed.
4849
0
  if (DirectBaseSpec && VirtualBaseSpec)
4850
0
    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4851
0
      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4852
4853
0
  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4854
0
  if (!BaseSpec)
4855
0
    BaseSpec = VirtualBaseSpec;
4856
4857
  // Initialize the base.
4858
0
  bool InitList = true;
4859
0
  MultiExprArg Args = Init;
4860
0
  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4861
0
    InitList = false;
4862
0
    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4863
0
  }
4864
4865
0
  InitializedEntity BaseEntity =
4866
0
    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4867
0
  InitializationKind Kind =
4868
0
      InitList ? InitializationKind::CreateDirectList(BaseLoc)
4869
0
               : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4870
0
                                                  InitRange.getEnd());
4871
0
  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4872
0
  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4873
0
  if (!BaseInit.isInvalid()) {
4874
    // C++11 [class.base.init]p7:
4875
    //   The initialization of each base and member constitutes a
4876
    //   full-expression.
4877
0
    BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4878
0
                                   /*DiscardedValue*/ false);
4879
0
  }
4880
4881
0
  if (BaseInit.isInvalid()) {
4882
0
    BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4883
0
                                  Args, BaseType);
4884
0
    if (BaseInit.isInvalid())
4885
0
      return true;
4886
0
  } else {
4887
    // If we are in a dependent context, template instantiation will
4888
    // perform this type-checking again. Just save the arguments that we
4889
    // received in a ParenListExpr.
4890
    // FIXME: This isn't quite ideal, since our ASTs don't capture all
4891
    // of the information that we have about the base
4892
    // initializer. However, deconstructing the ASTs is a dicey process,
4893
    // and this approach is far more likely to get the corner cases right.
4894
0
    if (CurContext->isDependentContext())
4895
0
      BaseInit = Init;
4896
0
  }
4897
4898
0
  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4899
0
                                          BaseSpec->isVirtual(),
4900
0
                                          InitRange.getBegin(),
4901
0
                                          BaseInit.getAs<Expr>(),
4902
0
                                          InitRange.getEnd(), EllipsisLoc);
4903
0
}
4904
4905
// Create a static_cast\<T&&>(expr).
4906
0
static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4907
0
  QualType TargetType =
4908
0
      SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4909
0
                                 SourceLocation(), DeclarationName());
4910
0
  SourceLocation ExprLoc = E->getBeginLoc();
4911
0
  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4912
0
      TargetType, ExprLoc);
4913
4914
0
  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4915
0
                                   SourceRange(ExprLoc, ExprLoc),
4916
0
                                   E->getSourceRange()).get();
4917
0
}
4918
4919
/// ImplicitInitializerKind - How an implicit base or member initializer should
4920
/// initialize its base or member.
4921
enum ImplicitInitializerKind {
4922
  IIK_Default,
4923
  IIK_Copy,
4924
  IIK_Move,
4925
  IIK_Inherit
4926
};
4927
4928
static bool
4929
BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4930
                             ImplicitInitializerKind ImplicitInitKind,
4931
                             CXXBaseSpecifier *BaseSpec,
4932
                             bool IsInheritedVirtualBase,
4933
0
                             CXXCtorInitializer *&CXXBaseInit) {
4934
0
  InitializedEntity InitEntity
4935
0
    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4936
0
                                        IsInheritedVirtualBase);
4937
4938
0
  ExprResult BaseInit;
4939
4940
0
  switch (ImplicitInitKind) {
4941
0
  case IIK_Inherit:
4942
0
  case IIK_Default: {
4943
0
    InitializationKind InitKind
4944
0
      = InitializationKind::CreateDefault(Constructor->getLocation());
4945
0
    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4946
0
    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4947
0
    break;
4948
0
  }
4949
4950
0
  case IIK_Move:
4951
0
  case IIK_Copy: {
4952
0
    bool Moving = ImplicitInitKind == IIK_Move;
4953
0
    ParmVarDecl *Param = Constructor->getParamDecl(0);
4954
0
    QualType ParamType = Param->getType().getNonReferenceType();
4955
4956
0
    Expr *CopyCtorArg =
4957
0
      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4958
0
                          SourceLocation(), Param, false,
4959
0
                          Constructor->getLocation(), ParamType,
4960
0
                          VK_LValue, nullptr);
4961
4962
0
    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4963
4964
    // Cast to the base class to avoid ambiguities.
4965
0
    QualType ArgTy =
4966
0
      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4967
0
                                       ParamType.getQualifiers());
4968
4969
0
    if (Moving) {
4970
0
      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4971
0
    }
4972
4973
0
    CXXCastPath BasePath;
4974
0
    BasePath.push_back(BaseSpec);
4975
0
    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4976
0
                                            CK_UncheckedDerivedToBase,
4977
0
                                            Moving ? VK_XValue : VK_LValue,
4978
0
                                            &BasePath).get();
4979
4980
0
    InitializationKind InitKind
4981
0
      = InitializationKind::CreateDirect(Constructor->getLocation(),
4982
0
                                         SourceLocation(), SourceLocation());
4983
0
    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4984
0
    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4985
0
    break;
4986
0
  }
4987
0
  }
4988
4989
0
  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4990
0
  if (BaseInit.isInvalid())
4991
0
    return true;
4992
4993
0
  CXXBaseInit =
4994
0
    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4995
0
               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4996
0
                                                        SourceLocation()),
4997
0
                                             BaseSpec->isVirtual(),
4998
0
                                             SourceLocation(),
4999
0
                                             BaseInit.getAs<Expr>(),
5000
0
                                             SourceLocation(),
5001
0
                                             SourceLocation());
5002
5003
0
  return false;
5004
0
}
5005
5006
0
static bool RefersToRValueRef(Expr *MemRef) {
5007
0
  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
5008
0
  return Referenced->getType()->isRValueReferenceType();
5009
0
}
5010
5011
static bool
5012
BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
5013
                               ImplicitInitializerKind ImplicitInitKind,
5014
                               FieldDecl *Field, IndirectFieldDecl *Indirect,
5015
0
                               CXXCtorInitializer *&CXXMemberInit) {
5016
0
  if (Field->isInvalidDecl())
5017
0
    return true;
5018
5019
0
  SourceLocation Loc = Constructor->getLocation();
5020
5021
0
  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5022
0
    bool Moving = ImplicitInitKind == IIK_Move;
5023
0
    ParmVarDecl *Param = Constructor->getParamDecl(0);
5024
0
    QualType ParamType = Param->getType().getNonReferenceType();
5025
5026
    // Suppress copying zero-width bitfields.
5027
0
    if (Field->isZeroLengthBitField(SemaRef.Context))
5028
0
      return false;
5029
5030
0
    Expr *MemberExprBase =
5031
0
      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
5032
0
                          SourceLocation(), Param, false,
5033
0
                          Loc, ParamType, VK_LValue, nullptr);
5034
5035
0
    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
5036
5037
0
    if (Moving) {
5038
0
      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
5039
0
    }
5040
5041
    // Build a reference to this field within the parameter.
5042
0
    CXXScopeSpec SS;
5043
0
    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5044
0
                              Sema::LookupMemberName);
5045
0
    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
5046
0
                                  : cast<ValueDecl>(Field), AS_public);
5047
0
    MemberLookup.resolveKind();
5048
0
    ExprResult CtorArg
5049
0
      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
5050
0
                                         ParamType, Loc,
5051
0
                                         /*IsArrow=*/false,
5052
0
                                         SS,
5053
0
                                         /*TemplateKWLoc=*/SourceLocation(),
5054
0
                                         /*FirstQualifierInScope=*/nullptr,
5055
0
                                         MemberLookup,
5056
0
                                         /*TemplateArgs=*/nullptr,
5057
0
                                         /*S*/nullptr);
5058
0
    if (CtorArg.isInvalid())
5059
0
      return true;
5060
5061
    // C++11 [class.copy]p15:
5062
    //   - if a member m has rvalue reference type T&&, it is direct-initialized
5063
    //     with static_cast<T&&>(x.m);
5064
0
    if (RefersToRValueRef(CtorArg.get())) {
5065
0
      CtorArg = CastForMoving(SemaRef, CtorArg.get());
5066
0
    }
5067
5068
0
    InitializedEntity Entity =
5069
0
        Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5070
0
                                                       /*Implicit*/ true)
5071
0
                 : InitializedEntity::InitializeMember(Field, nullptr,
5072
0
                                                       /*Implicit*/ true);
5073
5074
    // Direct-initialize to use the copy constructor.
5075
0
    InitializationKind InitKind =
5076
0
      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
5077
5078
0
    Expr *CtorArgE = CtorArg.getAs<Expr>();
5079
0
    InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5080
0
    ExprResult MemberInit =
5081
0
        InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
5082
0
    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5083
0
    if (MemberInit.isInvalid())
5084
0
      return true;
5085
5086
0
    if (Indirect)
5087
0
      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5088
0
          SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5089
0
    else
5090
0
      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5091
0
          SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5092
0
    return false;
5093
0
  }
5094
5095
0
  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5096
0
         "Unhandled implicit init kind!");
5097
5098
0
  QualType FieldBaseElementType =
5099
0
    SemaRef.Context.getBaseElementType(Field->getType());
5100
5101
0
  if (FieldBaseElementType->isRecordType()) {
5102
0
    InitializedEntity InitEntity =
5103
0
        Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
5104
0
                                                       /*Implicit*/ true)
5105
0
                 : InitializedEntity::InitializeMember(Field, nullptr,
5106
0
                                                       /*Implicit*/ true);
5107
0
    InitializationKind InitKind =
5108
0
      InitializationKind::CreateDefault(Loc);
5109
5110
0
    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
5111
0
    ExprResult MemberInit =
5112
0
        InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
5113
5114
0
    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5115
0
    if (MemberInit.isInvalid())
5116
0
      return true;
5117
5118
0
    if (Indirect)
5119
0
      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5120
0
                                                               Indirect, Loc,
5121
0
                                                               Loc,
5122
0
                                                               MemberInit.get(),
5123
0
                                                               Loc);
5124
0
    else
5125
0
      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5126
0
                                                               Field, Loc, Loc,
5127
0
                                                               MemberInit.get(),
5128
0
                                                               Loc);
5129
0
    return false;
5130
0
  }
5131
5132
0
  if (!Field->getParent()->isUnion()) {
5133
0
    if (FieldBaseElementType->isReferenceType()) {
5134
0
      SemaRef.Diag(Constructor->getLocation(),
5135
0
                   diag::err_uninitialized_member_in_ctor)
5136
0
      << (int)Constructor->isImplicit()
5137
0
      << SemaRef.Context.getTagDeclType(Constructor->getParent())
5138
0
      << 0 << Field->getDeclName();
5139
0
      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5140
0
      return true;
5141
0
    }
5142
5143
0
    if (FieldBaseElementType.isConstQualified()) {
5144
0
      SemaRef.Diag(Constructor->getLocation(),
5145
0
                   diag::err_uninitialized_member_in_ctor)
5146
0
      << (int)Constructor->isImplicit()
5147
0
      << SemaRef.Context.getTagDeclType(Constructor->getParent())
5148
0
      << 1 << Field->getDeclName();
5149
0
      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
5150
0
      return true;
5151
0
    }
5152
0
  }
5153
5154
0
  if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5155
    // ARC and Weak:
5156
    //   Default-initialize Objective-C pointers to NULL.
5157
0
    CXXMemberInit
5158
0
      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5159
0
                                                 Loc, Loc,
5160
0
                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5161
0
                                                 Loc);
5162
0
    return false;
5163
0
  }
5164
5165
  // Nothing to initialize.
5166
0
  CXXMemberInit = nullptr;
5167
0
  return false;
5168
0
}
5169
5170
namespace {
5171
struct BaseAndFieldInfo {
5172
  Sema &S;
5173
  CXXConstructorDecl *Ctor;
5174
  bool AnyErrorsInInits;
5175
  ImplicitInitializerKind IIK;
5176
  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5177
  SmallVector<CXXCtorInitializer*, 8> AllToInit;
5178
  llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5179
5180
  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5181
0
    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5182
0
    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5183
0
    if (Ctor->getInheritedConstructor())
5184
0
      IIK = IIK_Inherit;
5185
0
    else if (Generated && Ctor->isCopyConstructor())
5186
0
      IIK = IIK_Copy;
5187
0
    else if (Generated && Ctor->isMoveConstructor())
5188
0
      IIK = IIK_Move;
5189
0
    else
5190
0
      IIK = IIK_Default;
5191
0
  }
5192
5193
0
  bool isImplicitCopyOrMove() const {
5194
0
    switch (IIK) {
5195
0
    case IIK_Copy:
5196
0
    case IIK_Move:
5197
0
      return true;
5198
5199
0
    case IIK_Default:
5200
0
    case IIK_Inherit:
5201
0
      return false;
5202
0
    }
5203
5204
0
    llvm_unreachable("Invalid ImplicitInitializerKind!");
5205
0
  }
5206
5207
0
  bool addFieldInitializer(CXXCtorInitializer *Init) {
5208
0
    AllToInit.push_back(Init);
5209
5210
    // Check whether this initializer makes the field "used".
5211
0
    if (Init->getInit()->HasSideEffects(S.Context))
5212
0
      S.UnusedPrivateFields.remove(Init->getAnyMember());
5213
5214
0
    return false;
5215
0
  }
5216
5217
0
  bool isInactiveUnionMember(FieldDecl *Field) {
5218
0
    RecordDecl *Record = Field->getParent();
5219
0
    if (!Record->isUnion())
5220
0
      return false;
5221
5222
0
    if (FieldDecl *Active =
5223
0
            ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5224
0
      return Active != Field->getCanonicalDecl();
5225
5226
    // In an implicit copy or move constructor, ignore any in-class initializer.
5227
0
    if (isImplicitCopyOrMove())
5228
0
      return true;
5229
5230
    // If there's no explicit initialization, the field is active only if it
5231
    // has an in-class initializer...
5232
0
    if (Field->hasInClassInitializer())
5233
0
      return false;
5234
    // ... or it's an anonymous struct or union whose class has an in-class
5235
    // initializer.
5236
0
    if (!Field->isAnonymousStructOrUnion())
5237
0
      return true;
5238
0
    CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5239
0
    return !FieldRD->hasInClassInitializer();
5240
0
  }
5241
5242
  /// Determine whether the given field is, or is within, a union member
5243
  /// that is inactive (because there was an initializer given for a different
5244
  /// member of the union, or because the union was not initialized at all).
5245
  bool isWithinInactiveUnionMember(FieldDecl *Field,
5246
0
                                   IndirectFieldDecl *Indirect) {
5247
0
    if (!Indirect)
5248
0
      return isInactiveUnionMember(Field);
5249
5250
0
    for (auto *C : Indirect->chain()) {
5251
0
      FieldDecl *Field = dyn_cast<FieldDecl>(C);
5252
0
      if (Field && isInactiveUnionMember(Field))
5253
0
        return true;
5254
0
    }
5255
0
    return false;
5256
0
  }
5257
};
5258
}
5259
5260
/// Determine whether the given type is an incomplete or zero-lenfgth
5261
/// array type.
5262
0
static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5263
0
  if (T->isIncompleteArrayType())
5264
0
    return true;
5265
5266
0
  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5267
0
    if (!ArrayT->getSize())
5268
0
      return true;
5269
5270
0
    T = ArrayT->getElementType();
5271
0
  }
5272
5273
0
  return false;
5274
0
}
5275
5276
static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5277
                                    FieldDecl *Field,
5278
0
                                    IndirectFieldDecl *Indirect = nullptr) {
5279
0
  if (Field->isInvalidDecl())
5280
0
    return false;
5281
5282
  // Overwhelmingly common case: we have a direct initializer for this field.
5283
0
  if (CXXCtorInitializer *Init =
5284
0
          Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5285
0
    return Info.addFieldInitializer(Init);
5286
5287
  // C++11 [class.base.init]p8:
5288
  //   if the entity is a non-static data member that has a
5289
  //   brace-or-equal-initializer and either
5290
  //   -- the constructor's class is a union and no other variant member of that
5291
  //      union is designated by a mem-initializer-id or
5292
  //   -- the constructor's class is not a union, and, if the entity is a member
5293
  //      of an anonymous union, no other member of that union is designated by
5294
  //      a mem-initializer-id,
5295
  //   the entity is initialized as specified in [dcl.init].
5296
  //
5297
  // We also apply the same rules to handle anonymous structs within anonymous
5298
  // unions.
5299
0
  if (Info.isWithinInactiveUnionMember(Field, Indirect))
5300
0
    return false;
5301
5302
0
  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5303
0
    ExprResult DIE =
5304
0
        SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5305
0
    if (DIE.isInvalid())
5306
0
      return true;
5307
5308
0
    auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5309
0
    SemaRef.checkInitializerLifetime(Entity, DIE.get());
5310
5311
0
    CXXCtorInitializer *Init;
5312
0
    if (Indirect)
5313
0
      Init = new (SemaRef.Context)
5314
0
          CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5315
0
                             SourceLocation(), DIE.get(), SourceLocation());
5316
0
    else
5317
0
      Init = new (SemaRef.Context)
5318
0
          CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5319
0
                             SourceLocation(), DIE.get(), SourceLocation());
5320
0
    return Info.addFieldInitializer(Init);
5321
0
  }
5322
5323
  // Don't initialize incomplete or zero-length arrays.
5324
0
  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5325
0
    return false;
5326
5327
  // Don't try to build an implicit initializer if there were semantic
5328
  // errors in any of the initializers (and therefore we might be
5329
  // missing some that the user actually wrote).
5330
0
  if (Info.AnyErrorsInInits)
5331
0
    return false;
5332
5333
0
  CXXCtorInitializer *Init = nullptr;
5334
0
  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5335
0
                                     Indirect, Init))
5336
0
    return true;
5337
5338
0
  if (!Init)
5339
0
    return false;
5340
5341
0
  return Info.addFieldInitializer(Init);
5342
0
}
5343
5344
bool
5345
Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5346
0
                               CXXCtorInitializer *Initializer) {
5347
0
  assert(Initializer->isDelegatingInitializer());
5348
0
  Constructor->setNumCtorInitializers(1);
5349
0
  CXXCtorInitializer **initializer =
5350
0
    new (Context) CXXCtorInitializer*[1];
5351
0
  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5352
0
  Constructor->setCtorInitializers(initializer);
5353
5354
0
  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5355
0
    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5356
0
    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5357
0
  }
5358
5359
0
  DelegatingCtorDecls.push_back(Constructor);
5360
5361
0
  DiagnoseUninitializedFields(*this, Constructor);
5362
5363
0
  return false;
5364
0
}
5365
5366
bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5367
0
                               ArrayRef<CXXCtorInitializer *> Initializers) {
5368
0
  if (Constructor->isDependentContext()) {
5369
    // Just store the initializers as written, they will be checked during
5370
    // instantiation.
5371
0
    if (!Initializers.empty()) {
5372
0
      Constructor->setNumCtorInitializers(Initializers.size());
5373
0
      CXXCtorInitializer **baseOrMemberInitializers =
5374
0
        new (Context) CXXCtorInitializer*[Initializers.size()];
5375
0
      memcpy(baseOrMemberInitializers, Initializers.data(),
5376
0
             Initializers.size() * sizeof(CXXCtorInitializer*));
5377
0
      Constructor->setCtorInitializers(baseOrMemberInitializers);
5378
0
    }
5379
5380
    // Let template instantiation know whether we had errors.
5381
0
    if (AnyErrors)
5382
0
      Constructor->setInvalidDecl();
5383
5384
0
    return false;
5385
0
  }
5386
5387
0
  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5388
5389
  // We need to build the initializer AST according to order of construction
5390
  // and not what user specified in the Initializers list.
5391
0
  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5392
0
  if (!ClassDecl)
5393
0
    return true;
5394
5395
0
  bool HadError = false;
5396
5397
0
  for (unsigned i = 0; i < Initializers.size(); i++) {
5398
0
    CXXCtorInitializer *Member = Initializers[i];
5399
5400
0
    if (Member->isBaseInitializer())
5401
0
      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5402
0
    else {
5403
0
      Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5404
5405
0
      if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5406
0
        for (auto *C : F->chain()) {
5407
0
          FieldDecl *FD = dyn_cast<FieldDecl>(C);
5408
0
          if (FD && FD->getParent()->isUnion())
5409
0
            Info.ActiveUnionMember.insert(std::make_pair(
5410
0
                FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5411
0
        }
5412
0
      } else if (FieldDecl *FD = Member->getMember()) {
5413
0
        if (FD->getParent()->isUnion())
5414
0
          Info.ActiveUnionMember.insert(std::make_pair(
5415
0
              FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5416
0
      }
5417
0
    }
5418
0
  }
5419
5420
  // Keep track of the direct virtual bases.
5421
0
  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5422
0
  for (auto &I : ClassDecl->bases()) {
5423
0
    if (I.isVirtual())
5424
0
      DirectVBases.insert(&I);
5425
0
  }
5426
5427
  // Push virtual bases before others.
5428
0
  for (auto &VBase : ClassDecl->vbases()) {
5429
0
    if (CXXCtorInitializer *Value
5430
0
        = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5431
      // [class.base.init]p7, per DR257:
5432
      //   A mem-initializer where the mem-initializer-id names a virtual base
5433
      //   class is ignored during execution of a constructor of any class that
5434
      //   is not the most derived class.
5435
0
      if (ClassDecl->isAbstract()) {
5436
        // FIXME: Provide a fixit to remove the base specifier. This requires
5437
        // tracking the location of the associated comma for a base specifier.
5438
0
        Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5439
0
          << VBase.getType() << ClassDecl;
5440
0
        DiagnoseAbstractType(ClassDecl);
5441
0
      }
5442
5443
0
      Info.AllToInit.push_back(Value);
5444
0
    } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5445
      // [class.base.init]p8, per DR257:
5446
      //   If a given [...] base class is not named by a mem-initializer-id
5447
      //   [...] and the entity is not a virtual base class of an abstract
5448
      //   class, then [...] the entity is default-initialized.
5449
0
      bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5450
0
      CXXCtorInitializer *CXXBaseInit;
5451
0
      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5452
0
                                       &VBase, IsInheritedVirtualBase,
5453
0
                                       CXXBaseInit)) {
5454
0
        HadError = true;
5455
0
        continue;
5456
0
      }
5457
5458
0
      Info.AllToInit.push_back(CXXBaseInit);
5459
0
    }
5460
0
  }
5461
5462
  // Non-virtual bases.
5463
0
  for (auto &Base : ClassDecl->bases()) {
5464
    // Virtuals are in the virtual base list and already constructed.
5465
0
    if (Base.isVirtual())
5466
0
      continue;
5467
5468
0
    if (CXXCtorInitializer *Value
5469
0
          = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5470
0
      Info.AllToInit.push_back(Value);
5471
0
    } else if (!AnyErrors) {
5472
0
      CXXCtorInitializer *CXXBaseInit;
5473
0
      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5474
0
                                       &Base, /*IsInheritedVirtualBase=*/false,
5475
0
                                       CXXBaseInit)) {
5476
0
        HadError = true;
5477
0
        continue;
5478
0
      }
5479
5480
0
      Info.AllToInit.push_back(CXXBaseInit);
5481
0
    }
5482
0
  }
5483
5484
  // Fields.
5485
0
  for (auto *Mem : ClassDecl->decls()) {
5486
0
    if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5487
      // C++ [class.bit]p2:
5488
      //   A declaration for a bit-field that omits the identifier declares an
5489
      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5490
      //   initialized.
5491
0
      if (F->isUnnamedBitfield())
5492
0
        continue;
5493
5494
      // If we're not generating the implicit copy/move constructor, then we'll
5495
      // handle anonymous struct/union fields based on their individual
5496
      // indirect fields.
5497
0
      if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5498
0
        continue;
5499
5500
0
      if (CollectFieldInitializer(*this, Info, F))
5501
0
        HadError = true;
5502
0
      continue;
5503
0
    }
5504
5505
    // Beyond this point, we only consider default initialization.
5506
0
    if (Info.isImplicitCopyOrMove())
5507
0
      continue;
5508
5509
0
    if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5510
0
      if (F->getType()->isIncompleteArrayType()) {
5511
0
        assert(ClassDecl->hasFlexibleArrayMember() &&
5512
0
               "Incomplete array type is not valid");
5513
0
        continue;
5514
0
      }
5515
5516
      // Initialize each field of an anonymous struct individually.
5517
0
      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5518
0
        HadError = true;
5519
5520
0
      continue;
5521
0
    }
5522
0
  }
5523
5524
0
  unsigned NumInitializers = Info.AllToInit.size();
5525
0
  if (NumInitializers > 0) {
5526
0
    Constructor->setNumCtorInitializers(NumInitializers);
5527
0
    CXXCtorInitializer **baseOrMemberInitializers =
5528
0
      new (Context) CXXCtorInitializer*[NumInitializers];
5529
0
    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5530
0
           NumInitializers * sizeof(CXXCtorInitializer*));
5531
0
    Constructor->setCtorInitializers(baseOrMemberInitializers);
5532
5533
    // Constructors implicitly reference the base and member
5534
    // destructors.
5535
0
    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5536
0
                                           Constructor->getParent());
5537
0
  }
5538
5539
0
  return HadError;
5540
0
}
5541
5542
0
static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5543
0
  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5544
0
    const RecordDecl *RD = RT->getDecl();
5545
0
    if (RD->isAnonymousStructOrUnion()) {
5546
0
      for (auto *Field : RD->fields())
5547
0
        PopulateKeysForFields(Field, IdealInits);
5548
0
      return;
5549
0
    }
5550
0
  }
5551
0
  IdealInits.push_back(Field->getCanonicalDecl());
5552
0
}
5553
5554
0
static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5555
0
  return Context.getCanonicalType(BaseType).getTypePtr();
5556
0
}
5557
5558
static const void *GetKeyForMember(ASTContext &Context,
5559
0
                                   CXXCtorInitializer *Member) {
5560
0
  if (!Member->isAnyMemberInitializer())
5561
0
    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5562
5563
0
  return Member->getAnyMember()->getCanonicalDecl();
5564
0
}
5565
5566
static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5567
                                 const CXXCtorInitializer *Previous,
5568
0
                                 const CXXCtorInitializer *Current) {
5569
0
  if (Previous->isAnyMemberInitializer())
5570
0
    Diag << 0 << Previous->getAnyMember();
5571
0
  else
5572
0
    Diag << 1 << Previous->getTypeSourceInfo()->getType();
5573
5574
0
  if (Current->isAnyMemberInitializer())
5575
0
    Diag << 0 << Current->getAnyMember();
5576
0
  else
5577
0
    Diag << 1 << Current->getTypeSourceInfo()->getType();
5578
0
}
5579
5580
static void DiagnoseBaseOrMemInitializerOrder(
5581
    Sema &SemaRef, const CXXConstructorDecl *Constructor,
5582
0
    ArrayRef<CXXCtorInitializer *> Inits) {
5583
0
  if (Constructor->getDeclContext()->isDependentContext())
5584
0
    return;
5585
5586
  // Don't check initializers order unless the warning is enabled at the
5587
  // location of at least one initializer.
5588
0
  bool ShouldCheckOrder = false;
5589
0
  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5590
0
    CXXCtorInitializer *Init = Inits[InitIndex];
5591
0
    if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5592
0
                                 Init->getSourceLocation())) {
5593
0
      ShouldCheckOrder = true;
5594
0
      break;
5595
0
    }
5596
0
  }
5597
0
  if (!ShouldCheckOrder)
5598
0
    return;
5599
5600
  // Build the list of bases and members in the order that they'll
5601
  // actually be initialized.  The explicit initializers should be in
5602
  // this same order but may be missing things.
5603
0
  SmallVector<const void*, 32> IdealInitKeys;
5604
5605
0
  const CXXRecordDecl *ClassDecl = Constructor->getParent();
5606
5607
  // 1. Virtual bases.
5608
0
  for (const auto &VBase : ClassDecl->vbases())
5609
0
    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5610
5611
  // 2. Non-virtual bases.
5612
0
  for (const auto &Base : ClassDecl->bases()) {
5613
0
    if (Base.isVirtual())
5614
0
      continue;
5615
0
    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5616
0
  }
5617
5618
  // 3. Direct fields.
5619
0
  for (auto *Field : ClassDecl->fields()) {
5620
0
    if (Field->isUnnamedBitfield())
5621
0
      continue;
5622
5623
0
    PopulateKeysForFields(Field, IdealInitKeys);
5624
0
  }
5625
5626
0
  unsigned NumIdealInits = IdealInitKeys.size();
5627
0
  unsigned IdealIndex = 0;
5628
5629
  // Track initializers that are in an incorrect order for either a warning or
5630
  // note if multiple ones occur.
5631
0
  SmallVector<unsigned> WarnIndexes;
5632
  // Correlates the index of an initializer in the init-list to the index of
5633
  // the field/base in the class.
5634
0
  SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5635
5636
0
  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5637
0
    const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5638
5639
    // Scan forward to try to find this initializer in the idealized
5640
    // initializers list.
5641
0
    for (; IdealIndex != NumIdealInits; ++IdealIndex)
5642
0
      if (InitKey == IdealInitKeys[IdealIndex])
5643
0
        break;
5644
5645
    // If we didn't find this initializer, it must be because we
5646
    // scanned past it on a previous iteration.  That can only
5647
    // happen if we're out of order;  emit a warning.
5648
0
    if (IdealIndex == NumIdealInits && InitIndex) {
5649
0
      WarnIndexes.push_back(InitIndex);
5650
5651
      // Move back to the initializer's location in the ideal list.
5652
0
      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5653
0
        if (InitKey == IdealInitKeys[IdealIndex])
5654
0
          break;
5655
5656
0
      assert(IdealIndex < NumIdealInits &&
5657
0
             "initializer not found in initializer list");
5658
0
    }
5659
0
    CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5660
0
  }
5661
5662
0
  if (WarnIndexes.empty())
5663
0
    return;
5664
5665
  // Sort based on the ideal order, first in the pair.
5666
0
  llvm::sort(CorrelatedInitOrder, llvm::less_first());
5667
5668
  // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5669
  // emit the diagnostic before we can try adding notes.
5670
0
  {
5671
0
    Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5672
0
        Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5673
0
        WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5674
0
                                : diag::warn_some_initializers_out_of_order);
5675
5676
0
    for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5677
0
      if (CorrelatedInitOrder[I].second == I)
5678
0
        continue;
5679
      // Ideally we would be using InsertFromRange here, but clang doesn't
5680
      // appear to handle InsertFromRange correctly when the source range is
5681
      // modified by another fix-it.
5682
0
      D << FixItHint::CreateReplacement(
5683
0
          Inits[I]->getSourceRange(),
5684
0
          Lexer::getSourceText(
5685
0
              CharSourceRange::getTokenRange(
5686
0
                  Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5687
0
              SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5688
0
    }
5689
5690
    // If there is only 1 item out of order, the warning expects the name and
5691
    // type of each being added to it.
5692
0
    if (WarnIndexes.size() == 1) {
5693
0
      AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5694
0
                           Inits[WarnIndexes.front()]);
5695
0
      return;
5696
0
    }
5697
0
  }
5698
  // More than 1 item to warn, create notes letting the user know which ones
5699
  // are bad.
5700
0
  for (unsigned WarnIndex : WarnIndexes) {
5701
0
    const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5702
0
    auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5703
0
                          diag::note_initializer_out_of_order);
5704
0
    AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5705
0
    D << PrevInit->getSourceRange();
5706
0
  }
5707
0
}
5708
5709
namespace {
5710
bool CheckRedundantInit(Sema &S,
5711
                        CXXCtorInitializer *Init,
5712
0
                        CXXCtorInitializer *&PrevInit) {
5713
0
  if (!PrevInit) {
5714
0
    PrevInit = Init;
5715
0
    return false;
5716
0
  }
5717
5718
0
  if (FieldDecl *Field = Init->getAnyMember())
5719
0
    S.Diag(Init->getSourceLocation(),
5720
0
           diag::err_multiple_mem_initialization)
5721
0
      << Field->getDeclName()
5722
0
      << Init->getSourceRange();
5723
0
  else {
5724
0
    const Type *BaseClass = Init->getBaseClass();
5725
0
    assert(BaseClass && "neither field nor base");
5726
0
    S.Diag(Init->getSourceLocation(),
5727
0
           diag::err_multiple_base_initialization)
5728
0
      << QualType(BaseClass, 0)
5729
0
      << Init->getSourceRange();
5730
0
  }
5731
0
  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5732
0
    << 0 << PrevInit->getSourceRange();
5733
5734
0
  return true;
5735
0
}
5736
5737
typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5738
typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5739
5740
bool CheckRedundantUnionInit(Sema &S,
5741
                             CXXCtorInitializer *Init,
5742
0
                             RedundantUnionMap &Unions) {
5743
0
  FieldDecl *Field = Init->getAnyMember();
5744
0
  RecordDecl *Parent = Field->getParent();
5745
0
  NamedDecl *Child = Field;
5746
5747
0
  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5748
0
    if (Parent->isUnion()) {
5749
0
      UnionEntry &En = Unions[Parent];
5750
0
      if (En.first && En.first != Child) {
5751
0
        S.Diag(Init->getSourceLocation(),
5752
0
               diag::err_multiple_mem_union_initialization)
5753
0
          << Field->getDeclName()
5754
0
          << Init->getSourceRange();
5755
0
        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5756
0
          << 0 << En.second->getSourceRange();
5757
0
        return true;
5758
0
      }
5759
0
      if (!En.first) {
5760
0
        En.first = Child;
5761
0
        En.second = Init;
5762
0
      }
5763
0
      if (!Parent->isAnonymousStructOrUnion())
5764
0
        return false;
5765
0
    }
5766
5767
0
    Child = Parent;
5768
0
    Parent = cast<RecordDecl>(Parent->getDeclContext());
5769
0
  }
5770
5771
0
  return false;
5772
0
}
5773
} // namespace
5774
5775
/// ActOnMemInitializers - Handle the member initializers for a constructor.
5776
void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5777
                                SourceLocation ColonLoc,
5778
                                ArrayRef<CXXCtorInitializer*> MemInits,
5779
0
                                bool AnyErrors) {
5780
0
  if (!ConstructorDecl)
5781
0
    return;
5782
5783
0
  AdjustDeclIfTemplate(ConstructorDecl);
5784
5785
0
  CXXConstructorDecl *Constructor
5786
0
    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5787
5788
0
  if (!Constructor) {
5789
0
    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5790
0
    return;
5791
0
  }
5792
5793
  // Mapping for the duplicate initializers check.
5794
  // For member initializers, this is keyed with a FieldDecl*.
5795
  // For base initializers, this is keyed with a Type*.
5796
0
  llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5797
5798
  // Mapping for the inconsistent anonymous-union initializers check.
5799
0
  RedundantUnionMap MemberUnions;
5800
5801
0
  bool HadError = false;
5802
0
  for (unsigned i = 0; i < MemInits.size(); i++) {
5803
0
    CXXCtorInitializer *Init = MemInits[i];
5804
5805
    // Set the source order index.
5806
0
    Init->setSourceOrder(i);
5807
5808
0
    if (Init->isAnyMemberInitializer()) {
5809
0
      const void *Key = GetKeyForMember(Context, Init);
5810
0
      if (CheckRedundantInit(*this, Init, Members[Key]) ||
5811
0
          CheckRedundantUnionInit(*this, Init, MemberUnions))
5812
0
        HadError = true;
5813
0
    } else if (Init->isBaseInitializer()) {
5814
0
      const void *Key = GetKeyForMember(Context, Init);
5815
0
      if (CheckRedundantInit(*this, Init, Members[Key]))
5816
0
        HadError = true;
5817
0
    } else {
5818
0
      assert(Init->isDelegatingInitializer());
5819
      // This must be the only initializer
5820
0
      if (MemInits.size() != 1) {
5821
0
        Diag(Init->getSourceLocation(),
5822
0
             diag::err_delegating_initializer_alone)
5823
0
          << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5824
        // We will treat this as being the only initializer.
5825
0
      }
5826
0
      SetDelegatingInitializer(Constructor, MemInits[i]);
5827
      // Return immediately as the initializer is set.
5828
0
      return;
5829
0
    }
5830
0
  }
5831
5832
0
  if (HadError)
5833
0
    return;
5834
5835
0
  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5836
5837
0
  SetCtorInitializers(Constructor, AnyErrors, MemInits);
5838
5839
0
  DiagnoseUninitializedFields(*this, Constructor);
5840
0
}
5841
5842
void
5843
Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5844
0
                                             CXXRecordDecl *ClassDecl) {
5845
  // Ignore dependent contexts. Also ignore unions, since their members never
5846
  // have destructors implicitly called.
5847
0
  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5848
0
    return;
5849
5850
  // FIXME: all the access-control diagnostics are positioned on the
5851
  // field/base declaration.  That's probably good; that said, the
5852
  // user might reasonably want to know why the destructor is being
5853
  // emitted, and we currently don't say.
5854
5855
  // Non-static data members.
5856
0
  for (auto *Field : ClassDecl->fields()) {
5857
0
    if (Field->isInvalidDecl())
5858
0
      continue;
5859
5860
    // Don't destroy incomplete or zero-length arrays.
5861
0
    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5862
0
      continue;
5863
5864
0
    QualType FieldType = Context.getBaseElementType(Field->getType());
5865
5866
0
    const RecordType* RT = FieldType->getAs<RecordType>();
5867
0
    if (!RT)
5868
0
      continue;
5869
5870
0
    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5871
0
    if (FieldClassDecl->isInvalidDecl())
5872
0
      continue;
5873
0
    if (FieldClassDecl->hasIrrelevantDestructor())
5874
0
      continue;
5875
    // The destructor for an implicit anonymous union member is never invoked.
5876
0
    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5877
0
      continue;
5878
5879
0
    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5880
    // Dtor might still be missing, e.g because it's invalid.
5881
0
    if (!Dtor)
5882
0
      continue;
5883
0
    CheckDestructorAccess(Field->getLocation(), Dtor,
5884
0
                          PDiag(diag::err_access_dtor_field)
5885
0
                            << Field->getDeclName()
5886
0
                            << FieldType);
5887
5888
0
    MarkFunctionReferenced(Location, Dtor);
5889
0
    DiagnoseUseOfDecl(Dtor, Location);
5890
0
  }
5891
5892
  // We only potentially invoke the destructors of potentially constructed
5893
  // subobjects.
5894
0
  bool VisitVirtualBases = !ClassDecl->isAbstract();
5895
5896
  // If the destructor exists and has already been marked used in the MS ABI,
5897
  // then virtual base destructors have already been checked and marked used.
5898
  // Skip checking them again to avoid duplicate diagnostics.
5899
0
  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5900
0
    CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5901
0
    if (Dtor && Dtor->isUsed())
5902
0
      VisitVirtualBases = false;
5903
0
  }
5904
5905
0
  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5906
5907
  // Bases.
5908
0
  for (const auto &Base : ClassDecl->bases()) {
5909
0
    const RecordType *RT = Base.getType()->getAs<RecordType>();
5910
0
    if (!RT)
5911
0
      continue;
5912
5913
    // Remember direct virtual bases.
5914
0
    if (Base.isVirtual()) {
5915
0
      if (!VisitVirtualBases)
5916
0
        continue;
5917
0
      DirectVirtualBases.insert(RT);
5918
0
    }
5919
5920
0
    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5921
    // If our base class is invalid, we probably can't get its dtor anyway.
5922
0
    if (BaseClassDecl->isInvalidDecl())
5923
0
      continue;
5924
0
    if (BaseClassDecl->hasIrrelevantDestructor())
5925
0
      continue;
5926
5927
0
    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5928
    // Dtor might still be missing, e.g because it's invalid.
5929
0
    if (!Dtor)
5930
0
      continue;
5931
5932
    // FIXME: caret should be on the start of the class name
5933
0
    CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5934
0
                          PDiag(diag::err_access_dtor_base)
5935
0
                              << Base.getType() << Base.getSourceRange(),
5936
0
                          Context.getTypeDeclType(ClassDecl));
5937
5938
0
    MarkFunctionReferenced(Location, Dtor);
5939
0
    DiagnoseUseOfDecl(Dtor, Location);
5940
0
  }
5941
5942
0
  if (VisitVirtualBases)
5943
0
    MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5944
0
                                         &DirectVirtualBases);
5945
0
}
5946
5947
void Sema::MarkVirtualBaseDestructorsReferenced(
5948
    SourceLocation Location, CXXRecordDecl *ClassDecl,
5949
0
    llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5950
  // Virtual bases.
5951
0
  for (const auto &VBase : ClassDecl->vbases()) {
5952
    // Bases are always records in a well-formed non-dependent class.
5953
0
    const RecordType *RT = VBase.getType()->castAs<RecordType>();
5954
5955
    // Ignore already visited direct virtual bases.
5956
0
    if (DirectVirtualBases && DirectVirtualBases->count(RT))
5957
0
      continue;
5958
5959
0
    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5960
    // If our base class is invalid, we probably can't get its dtor anyway.
5961
0
    if (BaseClassDecl->isInvalidDecl())
5962
0
      continue;
5963
0
    if (BaseClassDecl->hasIrrelevantDestructor())
5964
0
      continue;
5965
5966
0
    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5967
    // Dtor might still be missing, e.g because it's invalid.
5968
0
    if (!Dtor)
5969
0
      continue;
5970
0
    if (CheckDestructorAccess(
5971
0
            ClassDecl->getLocation(), Dtor,
5972
0
            PDiag(diag::err_access_dtor_vbase)
5973
0
                << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5974
0
            Context.getTypeDeclType(ClassDecl)) ==
5975
0
        AR_accessible) {
5976
0
      CheckDerivedToBaseConversion(
5977
0
          Context.getTypeDeclType(ClassDecl), VBase.getType(),
5978
0
          diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5979
0
          SourceRange(), DeclarationName(), nullptr);
5980
0
    }
5981
5982
0
    MarkFunctionReferenced(Location, Dtor);
5983
0
    DiagnoseUseOfDecl(Dtor, Location);
5984
0
  }
5985
0
}
5986
5987
0
void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5988
0
  if (!CDtorDecl)
5989
0
    return;
5990
5991
0
  if (CXXConstructorDecl *Constructor
5992
0
      = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5993
0
    SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5994
0
    DiagnoseUninitializedFields(*this, Constructor);
5995
0
  }
5996
0
}
5997
5998
73
bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5999
73
  if (!getLangOpts().CPlusPlus)
6000
51
    return false;
6001
6002
22
  const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
6003
22
  if (!RD)
6004
22
    return false;
6005
6006
  // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6007
  // class template specialization here, but doing so breaks a lot of code.
6008
6009
  // We can't answer whether something is abstract until it has a
6010
  // definition. If it's currently being defined, we'll walk back
6011
  // over all the declarations when we have a full definition.
6012
0
  const CXXRecordDecl *Def = RD->getDefinition();
6013
0
  if (!Def || Def->isBeingDefined())
6014
0
    return false;
6015
6016
0
  return RD->isAbstract();
6017
0
}
6018
6019
bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
6020
73
                                  TypeDiagnoser &Diagnoser) {
6021
73
  if (!isAbstractType(Loc, T))
6022
73
    return false;
6023
6024
0
  T = Context.getBaseElementType(T);
6025
0
  Diagnoser.diagnose(*this, Loc, T);
6026
0
  DiagnoseAbstractType(T->getAsCXXRecordDecl());
6027
0
  return true;
6028
73
}
6029
6030
0
void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
6031
  // Check if we've already emitted the list of pure virtual functions
6032
  // for this class.
6033
0
  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
6034
0
    return;
6035
6036
  // If the diagnostic is suppressed, don't emit the notes. We're only
6037
  // going to emit them once, so try to attach them to a diagnostic we're
6038
  // actually going to show.
6039
0
  if (Diags.isLastDiagnosticIgnored())
6040
0
    return;
6041
6042
0
  CXXFinalOverriderMap FinalOverriders;
6043
0
  RD->getFinalOverriders(FinalOverriders);
6044
6045
  // Keep a set of seen pure methods so we won't diagnose the same method
6046
  // more than once.
6047
0
  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
6048
6049
0
  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
6050
0
                                   MEnd = FinalOverriders.end();
6051
0
       M != MEnd;
6052
0
       ++M) {
6053
0
    for (OverridingMethods::iterator SO = M->second.begin(),
6054
0
                                  SOEnd = M->second.end();
6055
0
         SO != SOEnd; ++SO) {
6056
      // C++ [class.abstract]p4:
6057
      //   A class is abstract if it contains or inherits at least one
6058
      //   pure virtual function for which the final overrider is pure
6059
      //   virtual.
6060
6061
      //
6062
0
      if (SO->second.size() != 1)
6063
0
        continue;
6064
6065
0
      if (!SO->second.front().Method->isPure())
6066
0
        continue;
6067
6068
0
      if (!SeenPureMethods.insert(SO->second.front().Method).second)
6069
0
        continue;
6070
6071
0
      Diag(SO->second.front().Method->getLocation(),
6072
0
           diag::note_pure_virtual_function)
6073
0
        << SO->second.front().Method->getDeclName() << RD->getDeclName();
6074
0
    }
6075
0
  }
6076
6077
0
  if (!PureVirtualClassDiagSet)
6078
0
    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
6079
0
  PureVirtualClassDiagSet->insert(RD);
6080
0
}
6081
6082
namespace {
6083
struct AbstractUsageInfo {
6084
  Sema &S;
6085
  CXXRecordDecl *Record;
6086
  CanQualType AbstractType;
6087
  bool Invalid;
6088
6089
  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6090
    : S(S), Record(Record),
6091
      AbstractType(S.Context.getCanonicalType(
6092
                   S.Context.getTypeDeclType(Record))),
6093
0
      Invalid(false) {}
6094
6095
0
  void DiagnoseAbstractType() {
6096
0
    if (Invalid) return;
6097
0
    S.DiagnoseAbstractType(Record);
6098
0
    Invalid = true;
6099
0
  }
6100
6101
  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6102
};
6103
6104
struct CheckAbstractUsage {
6105
  AbstractUsageInfo &Info;
6106
  const NamedDecl *Ctx;
6107
6108
  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6109
0
    : Info(Info), Ctx(Ctx) {}
6110
6111
0
  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6112
0
    switch (TL.getTypeLocClass()) {
6113
0
#define ABSTRACT_TYPELOC(CLASS, PARENT)
6114
0
#define TYPELOC(CLASS, PARENT) \
6115
0
    case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6116
0
#include "clang/AST/TypeLocNodes.def"
6117
0
    }
6118
0
  }
6119
6120
0
  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6121
0
    Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
6122
0
    for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6123
0
      if (!TL.getParam(I))
6124
0
        continue;
6125
6126
0
      TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
6127
0
      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
6128
0
    }
6129
0
  }
6130
6131
0
  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6132
0
    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
6133
0
  }
6134
6135
0
  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6136
    // Visit the type parameters from a permissive context.
6137
0
    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6138
0
      TemplateArgumentLoc TAL = TL.getArgLoc(I);
6139
0
      if (TAL.getArgument().getKind() == TemplateArgument::Type)
6140
0
        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6141
0
          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
6142
      // TODO: other template argument types?
6143
0
    }
6144
0
  }
6145
6146
  // Visit pointee types from a permissive context.
6147
#define CheckPolymorphic(Type) \
6148
0
  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6149
0
    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6150
0
  }
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::CheckAbstractUsage::Check(clang::AtomicTypeLoc, clang::Sema::AbstractDiagSelID)
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::CheckAbstractUsage::Check(clang::BlockPointerTypeLoc, clang::Sema::AbstractDiagSelID)
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::CheckAbstractUsage::Check(clang::MemberPointerTypeLoc, clang::Sema::AbstractDiagSelID)
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::CheckAbstractUsage::Check(clang::PointerTypeLoc, clang::Sema::AbstractDiagSelID)
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::CheckAbstractUsage::Check(clang::ReferenceTypeLoc, clang::Sema::AbstractDiagSelID)
6151
  CheckPolymorphic(PointerTypeLoc)
6152
  CheckPolymorphic(ReferenceTypeLoc)
6153
  CheckPolymorphic(MemberPointerTypeLoc)
6154
  CheckPolymorphic(BlockPointerTypeLoc)
6155
  CheckPolymorphic(AtomicTypeLoc)
6156
6157
  /// Handle all the types we haven't given a more specific
6158
  /// implementation for above.
6159
0
  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6160
    // Every other kind of type that we haven't called out already
6161
    // that has an inner type is either (1) sugar or (2) contains that
6162
    // inner type in some way as a subobject.
6163
0
    if (TypeLoc Next = TL.getNextTypeLoc())
6164
0
      return Visit(Next, Sel);
6165
6166
    // If there's no inner type and we're in a permissive context,
6167
    // don't diagnose.
6168
0
    if (Sel == Sema::AbstractNone) return;
6169
6170
    // Check whether the type matches the abstract type.
6171
0
    QualType T = TL.getType();
6172
0
    if (T->isArrayType()) {
6173
0
      Sel = Sema::AbstractArrayType;
6174
0
      T = Info.S.Context.getBaseElementType(T);
6175
0
    }
6176
0
    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
6177
0
    if (CT != Info.AbstractType) return;
6178
6179
    // It matched; do some magic.
6180
    // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6181
0
    if (Sel == Sema::AbstractArrayType) {
6182
0
      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
6183
0
        << T << TL.getSourceRange();
6184
0
    } else {
6185
0
      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
6186
0
        << Sel << T << TL.getSourceRange();
6187
0
    }
6188
0
    Info.DiagnoseAbstractType();
6189
0
  }
6190
};
6191
6192
void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6193
0
                                  Sema::AbstractDiagSelID Sel) {
6194
0
  CheckAbstractUsage(*this, D).Visit(TL, Sel);
6195
0
}
6196
6197
}
6198
6199
/// Check for invalid uses of an abstract type in a function declaration.
6200
static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6201
0
                                    FunctionDecl *FD) {
6202
  // Only definitions are required to refer to complete and
6203
  // non-abstract types.
6204
0
  if (!FD->doesThisDeclarationHaveABody())
6205
0
    return;
6206
6207
  // For safety's sake, just ignore it if we don't have type source
6208
  // information.  This should never happen for non-implicit methods,
6209
  // but...
6210
0
  if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6211
0
    Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6212
0
}
6213
6214
/// Check for invalid uses of an abstract type in a variable0 declaration.
6215
static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6216
0
                                    VarDecl *VD) {
6217
  // No need to do the check on definitions, which require that
6218
  // the type is complete.
6219
0
  if (VD->isThisDeclarationADefinition())
6220
0
    return;
6221
6222
0
  Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6223
0
                 Sema::AbstractVariableType);
6224
0
}
6225
6226
/// Check for invalid uses of an abstract type within a class definition.
6227
static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6228
0
                                    CXXRecordDecl *RD) {
6229
0
  for (auto *D : RD->decls()) {
6230
0
    if (D->isImplicit()) continue;
6231
6232
    // Step through friends to the befriended declaration.
6233
0
    if (auto *FD = dyn_cast<FriendDecl>(D)) {
6234
0
      D = FD->getFriendDecl();
6235
0
      if (!D) continue;
6236
0
    }
6237
6238
    // Functions and function templates.
6239
0
    if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6240
0
      CheckAbstractClassUsage(Info, FD);
6241
0
    } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6242
0
      CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6243
6244
    // Fields and static variables.
6245
0
    } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6246
0
      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6247
0
        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6248
0
    } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6249
0
      CheckAbstractClassUsage(Info, VD);
6250
0
    } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6251
0
      CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6252
6253
    // Nested classes and class templates.
6254
0
    } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6255
0
      CheckAbstractClassUsage(Info, RD);
6256
0
    } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6257
0
      CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6258
0
    }
6259
0
  }
6260
0
}
6261
6262
0
static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6263
0
  Attr *ClassAttr = getDLLAttr(Class);
6264
0
  if (!ClassAttr)
6265
0
    return;
6266
6267
0
  assert(ClassAttr->getKind() == attr::DLLExport);
6268
6269
0
  TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6270
6271
0
  if (TSK == TSK_ExplicitInstantiationDeclaration)
6272
    // Don't go any further if this is just an explicit instantiation
6273
    // declaration.
6274
0
    return;
6275
6276
  // Add a context note to explain how we got to any diagnostics produced below.
6277
0
  struct MarkingClassDllexported {
6278
0
    Sema &S;
6279
0
    MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6280
0
                            SourceLocation AttrLoc)
6281
0
        : S(S) {
6282
0
      Sema::CodeSynthesisContext Ctx;
6283
0
      Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6284
0
      Ctx.PointOfInstantiation = AttrLoc;
6285
0
      Ctx.Entity = Class;
6286
0
      S.pushCodeSynthesisContext(Ctx);
6287
0
    }
6288
0
    ~MarkingClassDllexported() {
6289
0
      S.popCodeSynthesisContext();
6290
0
    }
6291
0
  } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6292
6293
0
  if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6294
0
    S.MarkVTableUsed(Class->getLocation(), Class, true);
6295
6296
0
  for (Decl *Member : Class->decls()) {
6297
    // Skip members that were not marked exported.
6298
0
    if (!Member->hasAttr<DLLExportAttr>())
6299
0
      continue;
6300
6301
    // Defined static variables that are members of an exported base
6302
    // class must be marked export too.
6303
0
    auto *VD = dyn_cast<VarDecl>(Member);
6304
0
    if (VD && VD->getStorageClass() == SC_Static &&
6305
0
        TSK == TSK_ImplicitInstantiation)
6306
0
      S.MarkVariableReferenced(VD->getLocation(), VD);
6307
6308
0
    auto *MD = dyn_cast<CXXMethodDecl>(Member);
6309
0
    if (!MD)
6310
0
      continue;
6311
6312
0
    if (MD->isUserProvided()) {
6313
      // Instantiate non-default class member functions ...
6314
6315
      // .. except for certain kinds of template specializations.
6316
0
      if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6317
0
        continue;
6318
6319
      // If this is an MS ABI dllexport default constructor, instantiate any
6320
      // default arguments.
6321
0
      if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6322
0
        auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6323
0
        if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6324
0
          S.InstantiateDefaultCtorDefaultArgs(CD);
6325
0
        }
6326
0
      }
6327
6328
0
      S.MarkFunctionReferenced(Class->getLocation(), MD);
6329
6330
      // The function will be passed to the consumer when its definition is
6331
      // encountered.
6332
0
    } else if (MD->isExplicitlyDefaulted()) {
6333
      // Synthesize and instantiate explicitly defaulted methods.
6334
0
      S.MarkFunctionReferenced(Class->getLocation(), MD);
6335
6336
0
      if (TSK != TSK_ExplicitInstantiationDefinition) {
6337
        // Except for explicit instantiation defs, we will not see the
6338
        // definition again later, so pass it to the consumer now.
6339
0
        S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6340
0
      }
6341
0
    } else if (!MD->isTrivial() ||
6342
0
               MD->isCopyAssignmentOperator() ||
6343
0
               MD->isMoveAssignmentOperator()) {
6344
      // Synthesize and instantiate non-trivial implicit methods, and the copy
6345
      // and move assignment operators. The latter are exported even if they
6346
      // are trivial, because the address of an operator can be taken and
6347
      // should compare equal across libraries.
6348
0
      S.MarkFunctionReferenced(Class->getLocation(), MD);
6349
6350
      // There is no later point when we will see the definition of this
6351
      // function, so pass it to the consumer now.
6352
0
      S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6353
0
    }
6354
0
  }
6355
0
}
6356
6357
static void checkForMultipleExportedDefaultConstructors(Sema &S,
6358
0
                                                        CXXRecordDecl *Class) {
6359
  // Only the MS ABI has default constructor closures, so we don't need to do
6360
  // this semantic checking anywhere else.
6361
0
  if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6362
0
    return;
6363
6364
0
  CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6365
0
  for (Decl *Member : Class->decls()) {
6366
    // Look for exported default constructors.
6367
0
    auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6368
0
    if (!CD || !CD->isDefaultConstructor())
6369
0
      continue;
6370
0
    auto *Attr = CD->getAttr<DLLExportAttr>();
6371
0
    if (!Attr)
6372
0
      continue;
6373
6374
    // If the class is non-dependent, mark the default arguments as ODR-used so
6375
    // that we can properly codegen the constructor closure.
6376
0
    if (!Class->isDependentContext()) {
6377
0
      for (ParmVarDecl *PD : CD->parameters()) {
6378
0
        (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6379
0
        S.DiscardCleanupsInEvaluationContext();
6380
0
      }
6381
0
    }
6382
6383
0
    if (LastExportedDefaultCtor) {
6384
0
      S.Diag(LastExportedDefaultCtor->getLocation(),
6385
0
             diag::err_attribute_dll_ambiguous_default_ctor)
6386
0
          << Class;
6387
0
      S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6388
0
          << CD->getDeclName();
6389
0
      return;
6390
0
    }
6391
0
    LastExportedDefaultCtor = CD;
6392
0
  }
6393
0
}
6394
6395
static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6396
0
                                                       CXXRecordDecl *Class) {
6397
0
  bool ErrorReported = false;
6398
0
  auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6399
0
                                                     ClassTemplateDecl *TD) {
6400
0
    if (ErrorReported)
6401
0
      return;
6402
0
    S.Diag(TD->getLocation(),
6403
0
           diag::err_cuda_device_builtin_surftex_cls_template)
6404
0
        << /*surface*/ 0 << TD;
6405
0
    ErrorReported = true;
6406
0
  };
6407
6408
0
  ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6409
0
  if (!TD) {
6410
0
    auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6411
0
    if (!SD) {
6412
0
      S.Diag(Class->getLocation(),
6413
0
             diag::err_cuda_device_builtin_surftex_ref_decl)
6414
0
          << /*surface*/ 0 << Class;
6415
0
      S.Diag(Class->getLocation(),
6416
0
             diag::note_cuda_device_builtin_surftex_should_be_template_class)
6417
0
          << Class;
6418
0
      return;
6419
0
    }
6420
0
    TD = SD->getSpecializedTemplate();
6421
0
  }
6422
6423
0
  TemplateParameterList *Params = TD->getTemplateParameters();
6424
0
  unsigned N = Params->size();
6425
6426
0
  if (N != 2) {
6427
0
    reportIllegalClassTemplate(S, TD);
6428
0
    S.Diag(TD->getLocation(),
6429
0
           diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6430
0
        << TD << 2;
6431
0
  }
6432
0
  if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6433
0
    reportIllegalClassTemplate(S, TD);
6434
0
    S.Diag(TD->getLocation(),
6435
0
           diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6436
0
        << TD << /*1st*/ 0 << /*type*/ 0;
6437
0
  }
6438
0
  if (N > 1) {
6439
0
    auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6440
0
    if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6441
0
      reportIllegalClassTemplate(S, TD);
6442
0
      S.Diag(TD->getLocation(),
6443
0
             diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6444
0
          << TD << /*2nd*/ 1 << /*integer*/ 1;
6445
0
    }
6446
0
  }
6447
0
}
6448
6449
static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6450
0
                                                       CXXRecordDecl *Class) {
6451
0
  bool ErrorReported = false;
6452
0
  auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6453
0
                                                     ClassTemplateDecl *TD) {
6454
0
    if (ErrorReported)
6455
0
      return;
6456
0
    S.Diag(TD->getLocation(),
6457
0
           diag::err_cuda_device_builtin_surftex_cls_template)
6458
0
        << /*texture*/ 1 << TD;
6459
0
    ErrorReported = true;
6460
0
  };
6461
6462
0
  ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6463
0
  if (!TD) {
6464
0
    auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6465
0
    if (!SD) {
6466
0
      S.Diag(Class->getLocation(),
6467
0
             diag::err_cuda_device_builtin_surftex_ref_decl)
6468
0
          << /*texture*/ 1 << Class;
6469
0
      S.Diag(Class->getLocation(),
6470
0
             diag::note_cuda_device_builtin_surftex_should_be_template_class)
6471
0
          << Class;
6472
0
      return;
6473
0
    }
6474
0
    TD = SD->getSpecializedTemplate();
6475
0
  }
6476
6477
0
  TemplateParameterList *Params = TD->getTemplateParameters();
6478
0
  unsigned N = Params->size();
6479
6480
0
  if (N != 3) {
6481
0
    reportIllegalClassTemplate(S, TD);
6482
0
    S.Diag(TD->getLocation(),
6483
0
           diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6484
0
        << TD << 3;
6485
0
  }
6486
0
  if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6487
0
    reportIllegalClassTemplate(S, TD);
6488
0
    S.Diag(TD->getLocation(),
6489
0
           diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6490
0
        << TD << /*1st*/ 0 << /*type*/ 0;
6491
0
  }
6492
0
  if (N > 1) {
6493
0
    auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6494
0
    if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6495
0
      reportIllegalClassTemplate(S, TD);
6496
0
      S.Diag(TD->getLocation(),
6497
0
             diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6498
0
          << TD << /*2nd*/ 1 << /*integer*/ 1;
6499
0
    }
6500
0
  }
6501
0
  if (N > 2) {
6502
0
    auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6503
0
    if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6504
0
      reportIllegalClassTemplate(S, TD);
6505
0
      S.Diag(TD->getLocation(),
6506
0
             diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6507
0
          << TD << /*3rd*/ 2 << /*integer*/ 1;
6508
0
    }
6509
0
  }
6510
0
}
6511
6512
0
void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6513
  // Mark any compiler-generated routines with the implicit code_seg attribute.
6514
0
  for (auto *Method : Class->methods()) {
6515
0
    if (Method->isUserProvided())
6516
0
      continue;
6517
0
    if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6518
0
      Method->addAttr(A);
6519
0
  }
6520
0
}
6521
6522
/// Check class-level dllimport/dllexport attribute.
6523
0
void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6524
0
  Attr *ClassAttr = getDLLAttr(Class);
6525
6526
  // MSVC inherits DLL attributes to partial class template specializations.
6527
0
  if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6528
0
    if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6529
0
      if (Attr *TemplateAttr =
6530
0
              getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6531
0
        auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6532
0
        A->setInherited(true);
6533
0
        ClassAttr = A;
6534
0
      }
6535
0
    }
6536
0
  }
6537
6538
0
  if (!ClassAttr)
6539
0
    return;
6540
6541
  // MSVC allows imported or exported template classes that have UniqueExternal
6542
  // linkage. This occurs when the template class has been instantiated with
6543
  // a template parameter which itself has internal linkage.
6544
  // We drop the attribute to avoid exporting or importing any members.
6545
0
  if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6546
0
       Context.getTargetInfo().getTriple().isPS()) &&
6547
0
      (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6548
0
    Class->dropAttr<DLLExportAttr>();
6549
0
    Class->dropAttr<DLLImportAttr>();
6550
0
    return;
6551
0
  }
6552
6553
0
  if (!Class->isExternallyVisible()) {
6554
0
    Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6555
0
        << Class << ClassAttr;
6556
0
    return;
6557
0
  }
6558
6559
0
  if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6560
0
      !ClassAttr->isInherited()) {
6561
    // Diagnose dll attributes on members of class with dll attribute.
6562
0
    for (Decl *Member : Class->decls()) {
6563
0
      if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6564
0
        continue;
6565
0
      InheritableAttr *MemberAttr = getDLLAttr(Member);
6566
0
      if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6567
0
        continue;
6568
6569
0
      Diag(MemberAttr->getLocation(),
6570
0
             diag::err_attribute_dll_member_of_dll_class)
6571
0
          << MemberAttr << ClassAttr;
6572
0
      Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6573
0
      Member->setInvalidDecl();
6574
0
    }
6575
0
  }
6576
6577
0
  if (Class->getDescribedClassTemplate())
6578
    // Don't inherit dll attribute until the template is instantiated.
6579
0
    return;
6580
6581
  // The class is either imported or exported.
6582
0
  const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6583
6584
  // Check if this was a dllimport attribute propagated from a derived class to
6585
  // a base class template specialization. We don't apply these attributes to
6586
  // static data members.
6587
0
  const bool PropagatedImport =
6588
0
      !ClassExported &&
6589
0
      cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6590
6591
0
  TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6592
6593
  // Ignore explicit dllexport on explicit class template instantiation
6594
  // declarations, except in MinGW mode.
6595
0
  if (ClassExported && !ClassAttr->isInherited() &&
6596
0
      TSK == TSK_ExplicitInstantiationDeclaration &&
6597
0
      !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6598
0
    Class->dropAttr<DLLExportAttr>();
6599
0
    return;
6600
0
  }
6601
6602
  // Force declaration of implicit members so they can inherit the attribute.
6603
0
  ForceDeclarationOfImplicitMembers(Class);
6604
6605
  // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6606
  // seem to be true in practice?
6607
6608
0
  for (Decl *Member : Class->decls()) {
6609
0
    VarDecl *VD = dyn_cast<VarDecl>(Member);
6610
0
    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6611
6612
    // Only methods and static fields inherit the attributes.
6613
0
    if (!VD && !MD)
6614
0
      continue;
6615
6616
0
    if (MD) {
6617
      // Don't process deleted methods.
6618
0
      if (MD->isDeleted())
6619
0
        continue;
6620
6621
0
      if (MD->isInlined()) {
6622
        // MinGW does not import or export inline methods. But do it for
6623
        // template instantiations.
6624
0
        if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6625
0
            TSK != TSK_ExplicitInstantiationDeclaration &&
6626
0
            TSK != TSK_ExplicitInstantiationDefinition)
6627
0
          continue;
6628
6629
        // MSVC versions before 2015 don't export the move assignment operators
6630
        // and move constructor, so don't attempt to import/export them if
6631
        // we have a definition.
6632
0
        auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6633
0
        if ((MD->isMoveAssignmentOperator() ||
6634
0
             (Ctor && Ctor->isMoveConstructor())) &&
6635
0
            !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6636
0
          continue;
6637
6638
        // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6639
        // operator is exported anyway.
6640
0
        if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6641
0
            (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6642
0
          continue;
6643
0
      }
6644
0
    }
6645
6646
    // Don't apply dllimport attributes to static data members of class template
6647
    // instantiations when the attribute is propagated from a derived class.
6648
0
    if (VD && PropagatedImport)
6649
0
      continue;
6650
6651
0
    if (!cast<NamedDecl>(Member)->isExternallyVisible())
6652
0
      continue;
6653
6654
0
    if (!getDLLAttr(Member)) {
6655
0
      InheritableAttr *NewAttr = nullptr;
6656
6657
      // Do not export/import inline function when -fno-dllexport-inlines is
6658
      // passed. But add attribute for later local static var check.
6659
0
      if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6660
0
          TSK != TSK_ExplicitInstantiationDeclaration &&
6661
0
          TSK != TSK_ExplicitInstantiationDefinition) {
6662
0
        if (ClassExported) {
6663
0
          NewAttr = ::new (getASTContext())
6664
0
              DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6665
0
        } else {
6666
0
          NewAttr = ::new (getASTContext())
6667
0
              DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6668
0
        }
6669
0
      } else {
6670
0
        NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6671
0
      }
6672
6673
0
      NewAttr->setInherited(true);
6674
0
      Member->addAttr(NewAttr);
6675
6676
0
      if (MD) {
6677
        // Propagate DLLAttr to friend re-declarations of MD that have already
6678
        // been constructed.
6679
0
        for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6680
0
             FD = FD->getPreviousDecl()) {
6681
0
          if (FD->getFriendObjectKind() == Decl::FOK_None)
6682
0
            continue;
6683
0
          assert(!getDLLAttr(FD) &&
6684
0
                 "friend re-decl should not already have a DLLAttr");
6685
0
          NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6686
0
          NewAttr->setInherited(true);
6687
0
          FD->addAttr(NewAttr);
6688
0
        }
6689
0
      }
6690
0
    }
6691
0
  }
6692
6693
0
  if (ClassExported)
6694
0
    DelayedDllExportClasses.push_back(Class);
6695
0
}
6696
6697
/// Perform propagation of DLL attributes from a derived class to a
6698
/// templated base class for MS compatibility.
6699
void Sema::propagateDLLAttrToBaseClassTemplate(
6700
    CXXRecordDecl *Class, Attr *ClassAttr,
6701
0
    ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6702
0
  if (getDLLAttr(
6703
0
          BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6704
    // If the base class template has a DLL attribute, don't try to change it.
6705
0
    return;
6706
0
  }
6707
6708
0
  auto TSK = BaseTemplateSpec->getSpecializationKind();
6709
0
  if (!getDLLAttr(BaseTemplateSpec) &&
6710
0
      (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6711
0
       TSK == TSK_ImplicitInstantiation)) {
6712
    // The template hasn't been instantiated yet (or it has, but only as an
6713
    // explicit instantiation declaration or implicit instantiation, which means
6714
    // we haven't codegenned any members yet), so propagate the attribute.
6715
0
    auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6716
0
    NewAttr->setInherited(true);
6717
0
    BaseTemplateSpec->addAttr(NewAttr);
6718
6719
    // If this was an import, mark that we propagated it from a derived class to
6720
    // a base class template specialization.
6721
0
    if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6722
0
      ImportAttr->setPropagatedToBaseTemplate();
6723
6724
    // If the template is already instantiated, checkDLLAttributeRedeclaration()
6725
    // needs to be run again to work see the new attribute. Otherwise this will
6726
    // get run whenever the template is instantiated.
6727
0
    if (TSK != TSK_Undeclared)
6728
0
      checkClassLevelDLLAttribute(BaseTemplateSpec);
6729
6730
0
    return;
6731
0
  }
6732
6733
0
  if (getDLLAttr(BaseTemplateSpec)) {
6734
    // The template has already been specialized or instantiated with an
6735
    // attribute, explicitly or through propagation. We should not try to change
6736
    // it.
6737
0
    return;
6738
0
  }
6739
6740
  // The template was previously instantiated or explicitly specialized without
6741
  // a dll attribute, It's too late for us to add an attribute, so warn that
6742
  // this is unsupported.
6743
0
  Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6744
0
      << BaseTemplateSpec->isExplicitSpecialization();
6745
0
  Diag(ClassAttr->getLocation(), diag::note_attribute);
6746
0
  if (BaseTemplateSpec->isExplicitSpecialization()) {
6747
0
    Diag(BaseTemplateSpec->getLocation(),
6748
0
           diag::note_template_class_explicit_specialization_was_here)
6749
0
        << BaseTemplateSpec;
6750
0
  } else {
6751
0
    Diag(BaseTemplateSpec->getPointOfInstantiation(),
6752
0
           diag::note_template_class_instantiation_was_here)
6753
0
        << BaseTemplateSpec;
6754
0
  }
6755
0
}
6756
6757
/// Determine the kind of defaulting that would be done for a given function.
6758
///
6759
/// If the function is both a default constructor and a copy / move constructor
6760
/// (due to having a default argument for the first parameter), this picks
6761
/// CXXDefaultConstructor.
6762
///
6763
/// FIXME: Check that case is properly handled by all callers.
6764
Sema::DefaultedFunctionKind
6765
0
Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6766
0
  if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6767
0
    if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6768
0
      if (Ctor->isDefaultConstructor())
6769
0
        return Sema::CXXDefaultConstructor;
6770
6771
0
      if (Ctor->isCopyConstructor())
6772
0
        return Sema::CXXCopyConstructor;
6773
6774
0
      if (Ctor->isMoveConstructor())
6775
0
        return Sema::CXXMoveConstructor;
6776
0
    }
6777
6778
0
    if (MD->isCopyAssignmentOperator())
6779
0
      return Sema::CXXCopyAssignment;
6780
6781
0
    if (MD->isMoveAssignmentOperator())
6782
0
      return Sema::CXXMoveAssignment;
6783
6784
0
    if (isa<CXXDestructorDecl>(FD))
6785
0
      return Sema::CXXDestructor;
6786
0
  }
6787
6788
0
  switch (FD->getDeclName().getCXXOverloadedOperator()) {
6789
0
  case OO_EqualEqual:
6790
0
    return DefaultedComparisonKind::Equal;
6791
6792
0
  case OO_ExclaimEqual:
6793
0
    return DefaultedComparisonKind::NotEqual;
6794
6795
0
  case OO_Spaceship:
6796
    // No point allowing this if <=> doesn't exist in the current language mode.
6797
0
    if (!getLangOpts().CPlusPlus20)
6798
0
      break;
6799
0
    return DefaultedComparisonKind::ThreeWay;
6800
6801
0
  case OO_Less:
6802
0
  case OO_LessEqual:
6803
0
  case OO_Greater:
6804
0
  case OO_GreaterEqual:
6805
    // No point allowing this if <=> doesn't exist in the current language mode.
6806
0
    if (!getLangOpts().CPlusPlus20)
6807
0
      break;
6808
0
    return DefaultedComparisonKind::Relational;
6809
6810
0
  default:
6811
0
    break;
6812
0
  }
6813
6814
  // Not defaultable.
6815
0
  return DefaultedFunctionKind();
6816
0
}
6817
6818
static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6819
0
                                    SourceLocation DefaultLoc) {
6820
0
  Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6821
0
  if (DFK.isComparison())
6822
0
    return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6823
6824
0
  switch (DFK.asSpecialMember()) {
6825
0
  case Sema::CXXDefaultConstructor:
6826
0
    S.DefineImplicitDefaultConstructor(DefaultLoc,
6827
0
                                       cast<CXXConstructorDecl>(FD));
6828
0
    break;
6829
0
  case Sema::CXXCopyConstructor:
6830
0
    S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6831
0
    break;
6832
0
  case Sema::CXXCopyAssignment:
6833
0
    S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6834
0
    break;
6835
0
  case Sema::CXXDestructor:
6836
0
    S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6837
0
    break;
6838
0
  case Sema::CXXMoveConstructor:
6839
0
    S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6840
0
    break;
6841
0
  case Sema::CXXMoveAssignment:
6842
0
    S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6843
0
    break;
6844
0
  case Sema::CXXInvalid:
6845
0
    llvm_unreachable("Invalid special member.");
6846
0
  }
6847
0
}
6848
6849
/// Determine whether a type is permitted to be passed or returned in
6850
/// registers, per C++ [class.temporary]p3.
6851
static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6852
0
                               TargetInfo::CallingConvKind CCK) {
6853
0
  if (D->isDependentType() || D->isInvalidDecl())
6854
0
    return false;
6855
6856
  // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6857
  // The PS4 platform ABI follows the behavior of Clang 3.2.
6858
0
  if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6859
0
    return !D->hasNonTrivialDestructorForCall() &&
6860
0
           !D->hasNonTrivialCopyConstructorForCall();
6861
6862
0
  if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6863
0
    bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6864
0
    bool DtorIsTrivialForCall = false;
6865
6866
    // If a class has at least one eligible, trivial copy constructor, it
6867
    // is passed according to the C ABI. Otherwise, it is passed indirectly.
6868
    //
6869
    // Note: This permits classes with non-trivial copy or move ctors to be
6870
    // passed in registers, so long as they *also* have a trivial copy ctor,
6871
    // which is non-conforming.
6872
0
    if (D->needsImplicitCopyConstructor()) {
6873
0
      if (!D->defaultedCopyConstructorIsDeleted()) {
6874
0
        if (D->hasTrivialCopyConstructor())
6875
0
          CopyCtorIsTrivial = true;
6876
0
        if (D->hasTrivialCopyConstructorForCall())
6877
0
          CopyCtorIsTrivialForCall = true;
6878
0
      }
6879
0
    } else {
6880
0
      for (const CXXConstructorDecl *CD : D->ctors()) {
6881
0
        if (CD->isCopyConstructor() && !CD->isDeleted() &&
6882
0
            !CD->isIneligibleOrNotSelected()) {
6883
0
          if (CD->isTrivial())
6884
0
            CopyCtorIsTrivial = true;
6885
0
          if (CD->isTrivialForCall())
6886
0
            CopyCtorIsTrivialForCall = true;
6887
0
        }
6888
0
      }
6889
0
    }
6890
6891
0
    if (D->needsImplicitDestructor()) {
6892
0
      if (!D->defaultedDestructorIsDeleted() &&
6893
0
          D->hasTrivialDestructorForCall())
6894
0
        DtorIsTrivialForCall = true;
6895
0
    } else if (const auto *DD = D->getDestructor()) {
6896
0
      if (!DD->isDeleted() && DD->isTrivialForCall())
6897
0
        DtorIsTrivialForCall = true;
6898
0
    }
6899
6900
    // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6901
0
    if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6902
0
      return true;
6903
6904
    // If a class has a destructor, we'd really like to pass it indirectly
6905
    // because it allows us to elide copies.  Unfortunately, MSVC makes that
6906
    // impossible for small types, which it will pass in a single register or
6907
    // stack slot. Most objects with dtors are large-ish, so handle that early.
6908
    // We can't call out all large objects as being indirect because there are
6909
    // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6910
    // how we pass large POD types.
6911
6912
    // Note: This permits small classes with nontrivial destructors to be
6913
    // passed in registers, which is non-conforming.
6914
0
    bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6915
0
    uint64_t TypeSize = isAArch64 ? 128 : 64;
6916
6917
0
    if (CopyCtorIsTrivial &&
6918
0
        S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6919
0
      return true;
6920
0
    return false;
6921
0
  }
6922
6923
  // Per C++ [class.temporary]p3, the relevant condition is:
6924
  //   each copy constructor, move constructor, and destructor of X is
6925
  //   either trivial or deleted, and X has at least one non-deleted copy
6926
  //   or move constructor
6927
0
  bool HasNonDeletedCopyOrMove = false;
6928
6929
0
  if (D->needsImplicitCopyConstructor() &&
6930
0
      !D->defaultedCopyConstructorIsDeleted()) {
6931
0
    if (!D->hasTrivialCopyConstructorForCall())
6932
0
      return false;
6933
0
    HasNonDeletedCopyOrMove = true;
6934
0
  }
6935
6936
0
  if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6937
0
      !D->defaultedMoveConstructorIsDeleted()) {
6938
0
    if (!D->hasTrivialMoveConstructorForCall())
6939
0
      return false;
6940
0
    HasNonDeletedCopyOrMove = true;
6941
0
  }
6942
6943
0
  if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6944
0
      !D->hasTrivialDestructorForCall())
6945
0
    return false;
6946
6947
0
  for (const CXXMethodDecl *MD : D->methods()) {
6948
0
    if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6949
0
      continue;
6950
6951
0
    auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6952
0
    if (CD && CD->isCopyOrMoveConstructor())
6953
0
      HasNonDeletedCopyOrMove = true;
6954
0
    else if (!isa<CXXDestructorDecl>(MD))
6955
0
      continue;
6956
6957
0
    if (!MD->isTrivialForCall())
6958
0
      return false;
6959
0
  }
6960
6961
0
  return HasNonDeletedCopyOrMove;
6962
0
}
6963
6964
/// Report an error regarding overriding, along with any relevant
6965
/// overridden methods.
6966
///
6967
/// \param DiagID the primary error to report.
6968
/// \param MD the overriding method.
6969
static bool
6970
ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6971
0
                llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6972
0
  bool IssuedDiagnostic = false;
6973
0
  for (const CXXMethodDecl *O : MD->overridden_methods()) {
6974
0
    if (Report(O)) {
6975
0
      if (!IssuedDiagnostic) {
6976
0
        S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6977
0
        IssuedDiagnostic = true;
6978
0
      }
6979
0
      S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6980
0
    }
6981
0
  }
6982
0
  return IssuedDiagnostic;
6983
0
}
6984
6985
/// Perform semantic checks on a class definition that has been
6986
/// completing, introducing implicitly-declared members, checking for
6987
/// abstract types, etc.
6988
///
6989
/// \param S The scope in which the class was parsed. Null if we didn't just
6990
///        parse a class definition.
6991
/// \param Record The completed class.
6992
0
void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6993
0
  if (!Record)
6994
0
    return;
6995
6996
0
  if (Record->isAbstract() && !Record->isInvalidDecl()) {
6997
0
    AbstractUsageInfo Info(*this, Record);
6998
0
    CheckAbstractClassUsage(Info, Record);
6999
0
  }
7000
7001
  // If this is not an aggregate type and has no user-declared constructor,
7002
  // complain about any non-static data members of reference or const scalar
7003
  // type, since they will never get initializers.
7004
0
  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7005
0
      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7006
0
      !Record->isLambda()) {
7007
0
    bool Complained = false;
7008
0
    for (const auto *F : Record->fields()) {
7009
0
      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
7010
0
        continue;
7011
7012
0
      if (F->getType()->isReferenceType() ||
7013
0
          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7014
0
        if (!Complained) {
7015
0
          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
7016
0
              << llvm::to_underlying(Record->getTagKind()) << Record;
7017
0
          Complained = true;
7018
0
        }
7019
7020
0
        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
7021
0
          << F->getType()->isReferenceType()
7022
0
          << F->getDeclName();
7023
0
      }
7024
0
    }
7025
0
  }
7026
7027
0
  if (Record->getIdentifier()) {
7028
    // C++ [class.mem]p13:
7029
    //   If T is the name of a class, then each of the following shall have a
7030
    //   name different from T:
7031
    //     - every member of every anonymous union that is a member of class T.
7032
    //
7033
    // C++ [class.mem]p14:
7034
    //   In addition, if class T has a user-declared constructor (12.1), every
7035
    //   non-static data member of class T shall have a name different from T.
7036
0
    DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
7037
0
    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7038
0
         ++I) {
7039
0
      NamedDecl *D = (*I)->getUnderlyingDecl();
7040
0
      if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
7041
0
           Record->hasUserDeclaredConstructor()) ||
7042
0
          isa<IndirectFieldDecl>(D)) {
7043
0
        Diag((*I)->getLocation(), diag::err_member_name_of_class)
7044
0
          << D->getDeclName();
7045
0
        break;
7046
0
      }
7047
0
    }
7048
0
  }
7049
7050
  // Warn if the class has virtual methods but non-virtual public destructor.
7051
0
  if (Record->isPolymorphic() && !Record->isDependentType()) {
7052
0
    CXXDestructorDecl *dtor = Record->getDestructor();
7053
0
    if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7054
0
        !Record->hasAttr<FinalAttr>())
7055
0
      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
7056
0
           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
7057
0
  }
7058
7059
0
  if (Record->isAbstract()) {
7060
0
    if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7061
0
      Diag(Record->getLocation(), diag::warn_abstract_final_class)
7062
0
        << FA->isSpelledAsSealed();
7063
0
      DiagnoseAbstractType(Record);
7064
0
    }
7065
0
  }
7066
7067
  // Warn if the class has a final destructor but is not itself marked final.
7068
0
  if (!Record->hasAttr<FinalAttr>()) {
7069
0
    if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7070
0
      if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7071
0
        Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
7072
0
            << FA->isSpelledAsSealed()
7073
0
            << FixItHint::CreateInsertion(
7074
0
                   getLocForEndOfToken(Record->getLocation()),
7075
0
                   (FA->isSpelledAsSealed() ? " sealed" : " final"));
7076
0
        Diag(Record->getLocation(),
7077
0
             diag::note_final_dtor_non_final_class_silence)
7078
0
            << Context.getRecordType(Record) << FA->isSpelledAsSealed();
7079
0
      }
7080
0
    }
7081
0
  }
7082
7083
  // See if trivial_abi has to be dropped.
7084
0
  if (Record->hasAttr<TrivialABIAttr>())
7085
0
    checkIllFormedTrivialABIStruct(*Record);
7086
7087
  // Set HasTrivialSpecialMemberForCall if the record has attribute
7088
  // "trivial_abi".
7089
0
  bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7090
7091
0
  if (HasTrivialABI)
7092
0
    Record->setHasTrivialSpecialMemberForCall();
7093
7094
  // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7095
  // We check these last because they can depend on the properties of the
7096
  // primary comparison functions (==, <=>).
7097
0
  llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7098
7099
  // Perform checks that can't be done until we know all the properties of a
7100
  // member function (whether it's defaulted, deleted, virtual, overriding,
7101
  // ...).
7102
0
  auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7103
    // A static function cannot override anything.
7104
0
    if (MD->getStorageClass() == SC_Static) {
7105
0
      if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
7106
0
                          [](const CXXMethodDecl *) { return true; }))
7107
0
        return;
7108
0
    }
7109
7110
    // A deleted function cannot override a non-deleted function and vice
7111
    // versa.
7112
0
    if (ReportOverrides(*this,
7113
0
                        MD->isDeleted() ? diag::err_deleted_override
7114
0
                                        : diag::err_non_deleted_override,
7115
0
                        MD, [&](const CXXMethodDecl *V) {
7116
0
                          return MD->isDeleted() != V->isDeleted();
7117
0
                        })) {
7118
0
      if (MD->isDefaulted() && MD->isDeleted())
7119
        // Explain why this defaulted function was deleted.
7120
0
        DiagnoseDeletedDefaultedFunction(MD);
7121
0
      return;
7122
0
    }
7123
7124
    // A consteval function cannot override a non-consteval function and vice
7125
    // versa.
7126
0
    if (ReportOverrides(*this,
7127
0
                        MD->isConsteval() ? diag::err_consteval_override
7128
0
                                          : diag::err_non_consteval_override,
7129
0
                        MD, [&](const CXXMethodDecl *V) {
7130
0
                          return MD->isConsteval() != V->isConsteval();
7131
0
                        })) {
7132
0
      if (MD->isDefaulted() && MD->isDeleted())
7133
        // Explain why this defaulted function was deleted.
7134
0
        DiagnoseDeletedDefaultedFunction(MD);
7135
0
      return;
7136
0
    }
7137
0
  };
7138
7139
0
  auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7140
0
    if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7141
0
      return false;
7142
7143
0
    DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
7144
0
    if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7145
0
        DFK.asComparison() == DefaultedComparisonKind::Relational) {
7146
0
      DefaultedSecondaryComparisons.push_back(FD);
7147
0
      return true;
7148
0
    }
7149
7150
0
    CheckExplicitlyDefaultedFunction(S, FD);
7151
0
    return false;
7152
0
  };
7153
7154
0
  auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7155
    // Check whether the explicitly-defaulted members are valid.
7156
0
    bool Incomplete = CheckForDefaultedFunction(M);
7157
7158
    // Skip the rest of the checks for a member of a dependent class.
7159
0
    if (Record->isDependentType())
7160
0
      return;
7161
7162
    // For an explicitly defaulted or deleted special member, we defer
7163
    // determining triviality until the class is complete. That time is now!
7164
0
    CXXSpecialMember CSM = getSpecialMember(M);
7165
0
    if (!M->isImplicit() && !M->isUserProvided()) {
7166
0
      if (CSM != CXXInvalid) {
7167
0
        M->setTrivial(SpecialMemberIsTrivial(M, CSM));
7168
        // Inform the class that we've finished declaring this member.
7169
0
        Record->finishedDefaultedOrDeletedMember(M);
7170
0
        M->setTrivialForCall(
7171
0
            HasTrivialABI ||
7172
0
            SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
7173
0
        Record->setTrivialForCallFlags(M);
7174
0
      }
7175
0
    }
7176
7177
    // Set triviality for the purpose of calls if this is a user-provided
7178
    // copy/move constructor or destructor.
7179
0
    if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
7180
0
         CSM == CXXDestructor) && M->isUserProvided()) {
7181
0
      M->setTrivialForCall(HasTrivialABI);
7182
0
      Record->setTrivialForCallFlags(M);
7183
0
    }
7184
7185
0
    if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7186
0
        M->hasAttr<DLLExportAttr>()) {
7187
0
      if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
7188
0
          M->isTrivial() &&
7189
0
          (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
7190
0
           CSM == CXXDestructor))
7191
0
        M->dropAttr<DLLExportAttr>();
7192
7193
0
      if (M->hasAttr<DLLExportAttr>()) {
7194
        // Define after any fields with in-class initializers have been parsed.
7195
0
        DelayedDllExportMemberFunctions.push_back(M);
7196
0
      }
7197
0
    }
7198
7199
    // Define defaulted constexpr virtual functions that override a base class
7200
    // function right away.
7201
    // FIXME: We can defer doing this until the vtable is marked as used.
7202
0
    if (CSM != CXXInvalid && !M->isDeleted() && M->isDefaulted() &&
7203
0
        M->isConstexpr() && M->size_overridden_methods())
7204
0
      DefineDefaultedFunction(*this, M, M->getLocation());
7205
7206
0
    if (!Incomplete)
7207
0
      CheckCompletedMemberFunction(M);
7208
0
  };
7209
7210
  // Check the destructor before any other member function. We need to
7211
  // determine whether it's trivial in order to determine whether the claas
7212
  // type is a literal type, which is a prerequisite for determining whether
7213
  // other special member functions are valid and whether they're implicitly
7214
  // 'constexpr'.
7215
0
  if (CXXDestructorDecl *Dtor = Record->getDestructor())
7216
0
    CompleteMemberFunction(Dtor);
7217
7218
0
  bool HasMethodWithOverrideControl = false,
7219
0
       HasOverridingMethodWithoutOverrideControl = false;
7220
0
  for (auto *D : Record->decls()) {
7221
0
    if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7222
      // FIXME: We could do this check for dependent types with non-dependent
7223
      // bases.
7224
0
      if (!Record->isDependentType()) {
7225
        // See if a method overloads virtual methods in a base
7226
        // class without overriding any.
7227
0
        if (!M->isStatic())
7228
0
          DiagnoseHiddenVirtualMethods(M);
7229
0
        if (M->hasAttr<OverrideAttr>())
7230
0
          HasMethodWithOverrideControl = true;
7231
0
        else if (M->size_overridden_methods() > 0)
7232
0
          HasOverridingMethodWithoutOverrideControl = true;
7233
0
      }
7234
7235
0
      if (!isa<CXXDestructorDecl>(M))
7236
0
        CompleteMemberFunction(M);
7237
0
    } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7238
0
      CheckForDefaultedFunction(
7239
0
          dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7240
0
    }
7241
0
  }
7242
7243
0
  if (HasOverridingMethodWithoutOverrideControl) {
7244
0
    bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7245
0
    for (auto *M : Record->methods())
7246
0
      DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7247
0
  }
7248
7249
  // Check the defaulted secondary comparisons after any other member functions.
7250
0
  for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7251
0
    CheckExplicitlyDefaultedFunction(S, FD);
7252
7253
    // If this is a member function, we deferred checking it until now.
7254
0
    if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7255
0
      CheckCompletedMemberFunction(MD);
7256
0
  }
7257
7258
  // ms_struct is a request to use the same ABI rules as MSVC.  Check
7259
  // whether this class uses any C++ features that are implemented
7260
  // completely differently in MSVC, and if so, emit a diagnostic.
7261
  // That diagnostic defaults to an error, but we allow projects to
7262
  // map it down to a warning (or ignore it).  It's a fairly common
7263
  // practice among users of the ms_struct pragma to mass-annotate
7264
  // headers, sweeping up a bunch of types that the project doesn't
7265
  // really rely on MSVC-compatible layout for.  We must therefore
7266
  // support "ms_struct except for C++ stuff" as a secondary ABI.
7267
  // Don't emit this diagnostic if the feature was enabled as a
7268
  // language option (as opposed to via a pragma or attribute), as
7269
  // the option -mms-bitfields otherwise essentially makes it impossible
7270
  // to build C++ code, unless this diagnostic is turned off.
7271
0
  if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7272
0
      (Record->isPolymorphic() || Record->getNumBases())) {
7273
0
    Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7274
0
  }
7275
7276
0
  checkClassLevelDLLAttribute(Record);
7277
0
  checkClassLevelCodeSegAttribute(Record);
7278
7279
0
  bool ClangABICompat4 =
7280
0
      Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7281
0
  TargetInfo::CallingConvKind CCK =
7282
0
      Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7283
0
  bool CanPass = canPassInRegisters(*this, Record, CCK);
7284
7285
  // Do not change ArgPassingRestrictions if it has already been set to
7286
  // ArgPassingKind::CanNeverPassInRegs.
7287
0
  if (Record->getArgPassingRestrictions() !=
7288
0
      RecordArgPassingKind::CanNeverPassInRegs)
7289
0
    Record->setArgPassingRestrictions(
7290
0
        CanPass ? RecordArgPassingKind::CanPassInRegs
7291
0
                : RecordArgPassingKind::CannotPassInRegs);
7292
7293
  // If canPassInRegisters returns true despite the record having a non-trivial
7294
  // destructor, the record is destructed in the callee. This happens only when
7295
  // the record or one of its subobjects has a field annotated with trivial_abi
7296
  // or a field qualified with ObjC __strong/__weak.
7297
0
  if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7298
0
    Record->setParamDestroyedInCallee(true);
7299
0
  else if (Record->hasNonTrivialDestructor())
7300
0
    Record->setParamDestroyedInCallee(CanPass);
7301
7302
0
  if (getLangOpts().ForceEmitVTables) {
7303
    // If we want to emit all the vtables, we need to mark it as used.  This
7304
    // is especially required for cases like vtable assumption loads.
7305
0
    MarkVTableUsed(Record->getInnerLocStart(), Record);
7306
0
  }
7307
7308
0
  if (getLangOpts().CUDA) {
7309
0
    if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7310
0
      checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7311
0
    else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7312
0
      checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7313
0
  }
7314
0
}
7315
7316
/// Look up the special member function that would be called by a special
7317
/// member function for a subobject of class type.
7318
///
7319
/// \param Class The class type of the subobject.
7320
/// \param CSM The kind of special member function.
7321
/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7322
/// \param ConstRHS True if this is a copy operation with a const object
7323
///        on its RHS, that is, if the argument to the outer special member
7324
///        function is 'const' and this is not a field marked 'mutable'.
7325
static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7326
    Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7327
0
    unsigned FieldQuals, bool ConstRHS) {
7328
0
  unsigned LHSQuals = 0;
7329
0
  if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7330
0
    LHSQuals = FieldQuals;
7331
7332
0
  unsigned RHSQuals = FieldQuals;
7333
0
  if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7334
0
    RHSQuals = 0;
7335
0
  else if (ConstRHS)
7336
0
    RHSQuals |= Qualifiers::Const;
7337
7338
0
  return S.LookupSpecialMember(Class, CSM,
7339
0
                               RHSQuals & Qualifiers::Const,
7340
0
                               RHSQuals & Qualifiers::Volatile,
7341
0
                               false,
7342
0
                               LHSQuals & Qualifiers::Const,
7343
0
                               LHSQuals & Qualifiers::Volatile);
7344
0
}
7345
7346
class Sema::InheritedConstructorInfo {
7347
  Sema &S;
7348
  SourceLocation UseLoc;
7349
7350
  /// A mapping from the base classes through which the constructor was
7351
  /// inherited to the using shadow declaration in that base class (or a null
7352
  /// pointer if the constructor was declared in that base class).
7353
  llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7354
      InheritedFromBases;
7355
7356
public:
7357
  InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7358
                           ConstructorUsingShadowDecl *Shadow)
7359
0
      : S(S), UseLoc(UseLoc) {
7360
0
    bool DiagnosedMultipleConstructedBases = false;
7361
0
    CXXRecordDecl *ConstructedBase = nullptr;
7362
0
    BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7363
7364
    // Find the set of such base class subobjects and check that there's a
7365
    // unique constructed subobject.
7366
0
    for (auto *D : Shadow->redecls()) {
7367
0
      auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7368
0
      auto *DNominatedBase = DShadow->getNominatedBaseClass();
7369
0
      auto *DConstructedBase = DShadow->getConstructedBaseClass();
7370
7371
0
      InheritedFromBases.insert(
7372
0
          std::make_pair(DNominatedBase->getCanonicalDecl(),
7373
0
                         DShadow->getNominatedBaseClassShadowDecl()));
7374
0
      if (DShadow->constructsVirtualBase())
7375
0
        InheritedFromBases.insert(
7376
0
            std::make_pair(DConstructedBase->getCanonicalDecl(),
7377
0
                           DShadow->getConstructedBaseClassShadowDecl()));
7378
0
      else
7379
0
        assert(DNominatedBase == DConstructedBase);
7380
7381
      // [class.inhctor.init]p2:
7382
      //   If the constructor was inherited from multiple base class subobjects
7383
      //   of type B, the program is ill-formed.
7384
0
      if (!ConstructedBase) {
7385
0
        ConstructedBase = DConstructedBase;
7386
0
        ConstructedBaseIntroducer = D->getIntroducer();
7387
0
      } else if (ConstructedBase != DConstructedBase &&
7388
0
                 !Shadow->isInvalidDecl()) {
7389
0
        if (!DiagnosedMultipleConstructedBases) {
7390
0
          S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7391
0
              << Shadow->getTargetDecl();
7392
0
          S.Diag(ConstructedBaseIntroducer->getLocation(),
7393
0
                 diag::note_ambiguous_inherited_constructor_using)
7394
0
              << ConstructedBase;
7395
0
          DiagnosedMultipleConstructedBases = true;
7396
0
        }
7397
0
        S.Diag(D->getIntroducer()->getLocation(),
7398
0
               diag::note_ambiguous_inherited_constructor_using)
7399
0
            << DConstructedBase;
7400
0
      }
7401
0
    }
7402
7403
0
    if (DiagnosedMultipleConstructedBases)
7404
0
      Shadow->setInvalidDecl();
7405
0
  }
7406
7407
  /// Find the constructor to use for inherited construction of a base class,
7408
  /// and whether that base class constructor inherits the constructor from a
7409
  /// virtual base class (in which case it won't actually invoke it).
7410
  std::pair<CXXConstructorDecl *, bool>
7411
0
  findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7412
0
    auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7413
0
    if (It == InheritedFromBases.end())
7414
0
      return std::make_pair(nullptr, false);
7415
7416
    // This is an intermediary class.
7417
0
    if (It->second)
7418
0
      return std::make_pair(
7419
0
          S.findInheritingConstructor(UseLoc, Ctor, It->second),
7420
0
          It->second->constructsVirtualBase());
7421
7422
    // This is the base class from which the constructor was inherited.
7423
0
    return std::make_pair(Ctor, false);
7424
0
  }
7425
};
7426
7427
/// Is the special member function which would be selected to perform the
7428
/// specified operation on the specified class type a constexpr constructor?
7429
static bool
7430
specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7431
                         Sema::CXXSpecialMember CSM, unsigned Quals,
7432
                         bool ConstRHS,
7433
                         CXXConstructorDecl *InheritedCtor = nullptr,
7434
0
                         Sema::InheritedConstructorInfo *Inherited = nullptr) {
7435
  // Suppress duplicate constraint checking here, in case a constraint check
7436
  // caused us to decide to do this.  Any truely recursive checks will get
7437
  // caught during these checks anyway.
7438
0
  Sema::SatisfactionStackResetRAII SSRAII{S};
7439
7440
  // If we're inheriting a constructor, see if we need to call it for this base
7441
  // class.
7442
0
  if (InheritedCtor) {
7443
0
    assert(CSM == Sema::CXXDefaultConstructor);
7444
0
    auto BaseCtor =
7445
0
        Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7446
0
    if (BaseCtor)
7447
0
      return BaseCtor->isConstexpr();
7448
0
  }
7449
7450
0
  if (CSM == Sema::CXXDefaultConstructor)
7451
0
    return ClassDecl->hasConstexprDefaultConstructor();
7452
0
  if (CSM == Sema::CXXDestructor)
7453
0
    return ClassDecl->hasConstexprDestructor();
7454
7455
0
  Sema::SpecialMemberOverloadResult SMOR =
7456
0
      lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7457
0
  if (!SMOR.getMethod())
7458
    // A constructor we wouldn't select can't be "involved in initializing"
7459
    // anything.
7460
0
    return true;
7461
0
  return SMOR.getMethod()->isConstexpr();
7462
0
}
7463
7464
/// Determine whether the specified special member function would be constexpr
7465
/// if it were implicitly defined.
7466
static bool defaultedSpecialMemberIsConstexpr(
7467
    Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7468
    bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7469
0
    Sema::InheritedConstructorInfo *Inherited = nullptr) {
7470
0
  if (!S.getLangOpts().CPlusPlus11)
7471
0
    return false;
7472
7473
  // C++11 [dcl.constexpr]p4:
7474
  // In the definition of a constexpr constructor [...]
7475
0
  bool Ctor = true;
7476
0
  switch (CSM) {
7477
0
  case Sema::CXXDefaultConstructor:
7478
0
    if (Inherited)
7479
0
      break;
7480
    // Since default constructor lookup is essentially trivial (and cannot
7481
    // involve, for instance, template instantiation), we compute whether a
7482
    // defaulted default constructor is constexpr directly within CXXRecordDecl.
7483
    //
7484
    // This is important for performance; we need to know whether the default
7485
    // constructor is constexpr to determine whether the type is a literal type.
7486
0
    return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7487
7488
0
  case Sema::CXXCopyConstructor:
7489
0
  case Sema::CXXMoveConstructor:
7490
    // For copy or move constructors, we need to perform overload resolution.
7491
0
    break;
7492
7493
0
  case Sema::CXXCopyAssignment:
7494
0
  case Sema::CXXMoveAssignment:
7495
0
    if (!S.getLangOpts().CPlusPlus14)
7496
0
      return false;
7497
    // In C++1y, we need to perform overload resolution.
7498
0
    Ctor = false;
7499
0
    break;
7500
7501
0
  case Sema::CXXDestructor:
7502
0
    return ClassDecl->defaultedDestructorIsConstexpr();
7503
7504
0
  case Sema::CXXInvalid:
7505
0
    return false;
7506
0
  }
7507
7508
  //   -- if the class is a non-empty union, or for each non-empty anonymous
7509
  //      union member of a non-union class, exactly one non-static data member
7510
  //      shall be initialized; [DR1359]
7511
  //
7512
  // If we squint, this is guaranteed, since exactly one non-static data member
7513
  // will be initialized (if the constructor isn't deleted), we just don't know
7514
  // which one.
7515
0
  if (Ctor && ClassDecl->isUnion())
7516
0
    return CSM == Sema::CXXDefaultConstructor
7517
0
               ? ClassDecl->hasInClassInitializer() ||
7518
0
                     !ClassDecl->hasVariantMembers()
7519
0
               : true;
7520
7521
  //   -- the class shall not have any virtual base classes;
7522
0
  if (Ctor && ClassDecl->getNumVBases())
7523
0
    return false;
7524
7525
  // C++1y [class.copy]p26:
7526
  //   -- [the class] is a literal type, and
7527
0
  if (!Ctor && !ClassDecl->isLiteral())
7528
0
    return false;
7529
7530
  //   -- every constructor involved in initializing [...] base class
7531
  //      sub-objects shall be a constexpr constructor;
7532
  //   -- the assignment operator selected to copy/move each direct base
7533
  //      class is a constexpr function, and
7534
0
  for (const auto &B : ClassDecl->bases()) {
7535
0
    const RecordType *BaseType = B.getType()->getAs<RecordType>();
7536
0
    if (!BaseType)
7537
0
      continue;
7538
0
    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7539
0
    if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7540
0
                                  InheritedCtor, Inherited))
7541
0
      return false;
7542
0
  }
7543
7544
  //   -- every constructor involved in initializing non-static data members
7545
  //      [...] shall be a constexpr constructor;
7546
  //   -- every non-static data member and base class sub-object shall be
7547
  //      initialized
7548
  //   -- for each non-static data member of X that is of class type (or array
7549
  //      thereof), the assignment operator selected to copy/move that member is
7550
  //      a constexpr function
7551
0
  for (const auto *F : ClassDecl->fields()) {
7552
0
    if (F->isInvalidDecl())
7553
0
      continue;
7554
0
    if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7555
0
      continue;
7556
0
    QualType BaseType = S.Context.getBaseElementType(F->getType());
7557
0
    if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7558
0
      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7559
0
      if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7560
0
                                    BaseType.getCVRQualifiers(),
7561
0
                                    ConstArg && !F->isMutable()))
7562
0
        return false;
7563
0
    } else if (CSM == Sema::CXXDefaultConstructor) {
7564
0
      return false;
7565
0
    }
7566
0
  }
7567
7568
  // All OK, it's constexpr!
7569
0
  return true;
7570
0
}
7571
7572
namespace {
7573
/// RAII object to register a defaulted function as having its exception
7574
/// specification computed.
7575
struct ComputingExceptionSpec {
7576
  Sema &S;
7577
7578
  ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7579
0
      : S(S) {
7580
0
    Sema::CodeSynthesisContext Ctx;
7581
0
    Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7582
0
    Ctx.PointOfInstantiation = Loc;
7583
0
    Ctx.Entity = FD;
7584
0
    S.pushCodeSynthesisContext(Ctx);
7585
0
  }
7586
0
  ~ComputingExceptionSpec() {
7587
0
    S.popCodeSynthesisContext();
7588
0
  }
7589
};
7590
}
7591
7592
static Sema::ImplicitExceptionSpecification
7593
ComputeDefaultedSpecialMemberExceptionSpec(
7594
    Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7595
    Sema::InheritedConstructorInfo *ICI);
7596
7597
static Sema::ImplicitExceptionSpecification
7598
ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7599
                                        FunctionDecl *FD,
7600
                                        Sema::DefaultedComparisonKind DCK);
7601
7602
static Sema::ImplicitExceptionSpecification
7603
0
computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7604
0
  auto DFK = S.getDefaultedFunctionKind(FD);
7605
0
  if (DFK.isSpecialMember())
7606
0
    return ComputeDefaultedSpecialMemberExceptionSpec(
7607
0
        S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7608
0
  if (DFK.isComparison())
7609
0
    return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7610
0
                                                   DFK.asComparison());
7611
7612
0
  auto *CD = cast<CXXConstructorDecl>(FD);
7613
0
  assert(CD->getInheritedConstructor() &&
7614
0
         "only defaulted functions and inherited constructors have implicit "
7615
0
         "exception specs");
7616
0
  Sema::InheritedConstructorInfo ICI(
7617
0
      S, Loc, CD->getInheritedConstructor().getShadowDecl());
7618
0
  return ComputeDefaultedSpecialMemberExceptionSpec(
7619
0
      S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7620
0
}
7621
7622
static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7623
0
                                                            CXXMethodDecl *MD) {
7624
0
  FunctionProtoType::ExtProtoInfo EPI;
7625
7626
  // Build an exception specification pointing back at this member.
7627
0
  EPI.ExceptionSpec.Type = EST_Unevaluated;
7628
0
  EPI.ExceptionSpec.SourceDecl = MD;
7629
7630
  // Set the calling convention to the default for C++ instance methods.
7631
0
  EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7632
0
      S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7633
0
                                            /*IsCXXMethod=*/true));
7634
0
  return EPI;
7635
0
}
7636
7637
0
void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7638
0
  const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7639
0
  if (FPT->getExceptionSpecType() != EST_Unevaluated)
7640
0
    return;
7641
7642
  // Evaluate the exception specification.
7643
0
  auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7644
0
  auto ESI = IES.getExceptionSpec();
7645
7646
  // Update the type of the special member to use it.
7647
0
  UpdateExceptionSpec(FD, ESI);
7648
0
}
7649
7650
0
void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7651
0
  assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7652
7653
0
  DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7654
0
  if (!DefKind) {
7655
0
    assert(FD->getDeclContext()->isDependentContext());
7656
0
    return;
7657
0
  }
7658
7659
0
  if (DefKind.isComparison())
7660
0
    UnusedPrivateFields.clear();
7661
7662
0
  if (DefKind.isSpecialMember()
7663
0
          ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7664
0
                                                  DefKind.asSpecialMember(),
7665
0
                                                  FD->getDefaultLoc())
7666
0
          : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7667
0
    FD->setInvalidDecl();
7668
0
}
7669
7670
bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7671
                                                 CXXSpecialMember CSM,
7672
0
                                                 SourceLocation DefaultLoc) {
7673
0
  CXXRecordDecl *RD = MD->getParent();
7674
7675
0
  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7676
0
         "not an explicitly-defaulted special member");
7677
7678
  // Defer all checking for special members of a dependent type.
7679
0
  if (RD->isDependentType())
7680
0
    return false;
7681
7682
  // Whether this was the first-declared instance of the constructor.
7683
  // This affects whether we implicitly add an exception spec and constexpr.
7684
0
  bool First = MD == MD->getCanonicalDecl();
7685
7686
0
  bool HadError = false;
7687
7688
  // C++11 [dcl.fct.def.default]p1:
7689
  //   A function that is explicitly defaulted shall
7690
  //     -- be a special member function [...] (checked elsewhere),
7691
  //     -- have the same type (except for ref-qualifiers, and except that a
7692
  //        copy operation can take a non-const reference) as an implicit
7693
  //        declaration, and
7694
  //     -- not have default arguments.
7695
  // C++2a changes the second bullet to instead delete the function if it's
7696
  // defaulted on its first declaration, unless it's "an assignment operator,
7697
  // and its return type differs or its parameter type is not a reference".
7698
0
  bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7699
0
  bool ShouldDeleteForTypeMismatch = false;
7700
0
  unsigned ExpectedParams = 1;
7701
0
  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7702
0
    ExpectedParams = 0;
7703
0
  if (MD->getNumExplicitParams() != ExpectedParams) {
7704
    // This checks for default arguments: a copy or move constructor with a
7705
    // default argument is classified as a default constructor, and assignment
7706
    // operations and destructors can't have default arguments.
7707
0
    Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7708
0
      << CSM << MD->getSourceRange();
7709
0
    HadError = true;
7710
0
  } else if (MD->isVariadic()) {
7711
0
    if (DeleteOnTypeMismatch)
7712
0
      ShouldDeleteForTypeMismatch = true;
7713
0
    else {
7714
0
      Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7715
0
        << CSM << MD->getSourceRange();
7716
0
      HadError = true;
7717
0
    }
7718
0
  }
7719
7720
0
  const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7721
7722
0
  bool CanHaveConstParam = false;
7723
0
  if (CSM == CXXCopyConstructor)
7724
0
    CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7725
0
  else if (CSM == CXXCopyAssignment)
7726
0
    CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7727
7728
0
  QualType ReturnType = Context.VoidTy;
7729
0
  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7730
    // Check for return type matching.
7731
0
    ReturnType = Type->getReturnType();
7732
0
    QualType ThisType = MD->getFunctionObjectParameterType();
7733
7734
0
    QualType DeclType = Context.getTypeDeclType(RD);
7735
0
    DeclType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
7736
0
                                         DeclType, nullptr);
7737
0
    DeclType = Context.getAddrSpaceQualType(
7738
0
        DeclType, ThisType.getQualifiers().getAddressSpace());
7739
0
    QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7740
7741
0
    if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7742
0
      Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7743
0
        << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7744
0
      HadError = true;
7745
0
    }
7746
7747
    // A defaulted special member cannot have cv-qualifiers.
7748
0
    if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7749
0
      if (DeleteOnTypeMismatch)
7750
0
        ShouldDeleteForTypeMismatch = true;
7751
0
      else {
7752
0
        Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7753
0
          << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7754
0
        HadError = true;
7755
0
      }
7756
0
    }
7757
    // [C++23][dcl.fct.def.default]/p2.2
7758
    // if F2 has an implicit object parameter of type “reference to C”,
7759
    // F1 may be an explicit object member function whose explicit object
7760
    // parameter is of (possibly different) type “reference to C”,
7761
    // in which case the type of F1 would differ from the type of F2
7762
    // in that the type of F1 has an additional parameter;
7763
0
    if (!Context.hasSameType(
7764
0
            ThisType.getNonReferenceType().getUnqualifiedType(),
7765
0
            Context.getRecordType(RD))) {
7766
0
      if (DeleteOnTypeMismatch)
7767
0
        ShouldDeleteForTypeMismatch = true;
7768
0
      else {
7769
0
        Diag(MD->getLocation(),
7770
0
             diag::err_defaulted_special_member_explicit_object_mismatch)
7771
0
            << (CSM == CXXMoveAssignment) << RD << MD->getSourceRange();
7772
0
        HadError = true;
7773
0
      }
7774
0
    }
7775
0
  }
7776
7777
  // Check for parameter type matching.
7778
0
  QualType ArgType =
7779
0
      ExpectedParams
7780
0
          ? Type->getParamType(MD->isExplicitObjectMemberFunction() ? 1 : 0)
7781
0
          : QualType();
7782
0
  bool HasConstParam = false;
7783
0
  if (ExpectedParams && ArgType->isReferenceType()) {
7784
    // Argument must be reference to possibly-const T.
7785
0
    QualType ReferentType = ArgType->getPointeeType();
7786
0
    HasConstParam = ReferentType.isConstQualified();
7787
7788
0
    if (ReferentType.isVolatileQualified()) {
7789
0
      if (DeleteOnTypeMismatch)
7790
0
        ShouldDeleteForTypeMismatch = true;
7791
0
      else {
7792
0
        Diag(MD->getLocation(),
7793
0
             diag::err_defaulted_special_member_volatile_param) << CSM;
7794
0
        HadError = true;
7795
0
      }
7796
0
    }
7797
7798
0
    if (HasConstParam && !CanHaveConstParam) {
7799
0
      if (DeleteOnTypeMismatch)
7800
0
        ShouldDeleteForTypeMismatch = true;
7801
0
      else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7802
0
        Diag(MD->getLocation(),
7803
0
             diag::err_defaulted_special_member_copy_const_param)
7804
0
          << (CSM == CXXCopyAssignment);
7805
        // FIXME: Explain why this special member can't be const.
7806
0
        HadError = true;
7807
0
      } else {
7808
0
        Diag(MD->getLocation(),
7809
0
             diag::err_defaulted_special_member_move_const_param)
7810
0
          << (CSM == CXXMoveAssignment);
7811
0
        HadError = true;
7812
0
      }
7813
0
    }
7814
0
  } else if (ExpectedParams) {
7815
    // A copy assignment operator can take its argument by value, but a
7816
    // defaulted one cannot.
7817
0
    assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7818
0
    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7819
0
    HadError = true;
7820
0
  }
7821
7822
  // C++11 [dcl.fct.def.default]p2:
7823
  //   An explicitly-defaulted function may be declared constexpr only if it
7824
  //   would have been implicitly declared as constexpr,
7825
  // Do not apply this rule to members of class templates, since core issue 1358
7826
  // makes such functions always instantiate to constexpr functions. For
7827
  // functions which cannot be constexpr (for non-constructors in C++11 and for
7828
  // destructors in C++14 and C++17), this is checked elsewhere.
7829
  //
7830
  // FIXME: This should not apply if the member is deleted.
7831
0
  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7832
0
                                                     HasConstParam);
7833
7834
  // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7835
  //   If the instantiated template specialization of a constexpr function
7836
  //   template or member function of a class template would fail to satisfy
7837
  //   the requirements for a constexpr function or constexpr constructor, that
7838
  //   specialization is still a constexpr function or constexpr constructor,
7839
  //   even though a call to such a function cannot appear in a constant
7840
  //   expression.
7841
0
  if (MD->isTemplateInstantiation() && MD->isConstexpr())
7842
0
    Constexpr = true;
7843
7844
0
  if ((getLangOpts().CPlusPlus20 ||
7845
0
       (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7846
0
                                  : isa<CXXConstructorDecl>(MD))) &&
7847
0
      MD->isConstexpr() && !Constexpr &&
7848
0
      MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7849
0
        if (!MD->isConsteval() && RD->getNumVBases()) {
7850
0
          Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr_with_vb)
7851
0
              << CSM;
7852
0
          for (const auto &I : RD->vbases())
7853
0
            Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here);
7854
0
        } else {
7855
0
          Diag(MD->getBeginLoc(), MD->isConsteval()
7856
0
                                      ? diag::err_incorrect_defaulted_consteval
7857
0
                                      : diag::err_incorrect_defaulted_constexpr)
7858
0
              << CSM;
7859
0
        }
7860
    // FIXME: Explain why the special member can't be constexpr.
7861
0
    HadError = true;
7862
0
  }
7863
7864
0
  if (First) {
7865
    // C++2a [dcl.fct.def.default]p3:
7866
    //   If a function is explicitly defaulted on its first declaration, it is
7867
    //   implicitly considered to be constexpr if the implicit declaration
7868
    //   would be.
7869
0
    MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7870
0
                                          ? ConstexprSpecKind::Consteval
7871
0
                                          : ConstexprSpecKind::Constexpr)
7872
0
                                   : ConstexprSpecKind::Unspecified);
7873
7874
0
    if (!Type->hasExceptionSpec()) {
7875
      // C++2a [except.spec]p3:
7876
      //   If a declaration of a function does not have a noexcept-specifier
7877
      //   [and] is defaulted on its first declaration, [...] the exception
7878
      //   specification is as specified below
7879
0
      FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7880
0
      EPI.ExceptionSpec.Type = EST_Unevaluated;
7881
0
      EPI.ExceptionSpec.SourceDecl = MD;
7882
0
      MD->setType(
7883
0
          Context.getFunctionType(ReturnType, Type->getParamTypes(), EPI));
7884
0
    }
7885
0
  }
7886
7887
0
  if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7888
0
    if (First) {
7889
0
      SetDeclDeleted(MD, MD->getLocation());
7890
0
      if (!inTemplateInstantiation() && !HadError) {
7891
0
        Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7892
0
        if (ShouldDeleteForTypeMismatch) {
7893
0
          Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7894
0
        } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7895
0
                                             /*Diagnose*/ true) &&
7896
0
                   DefaultLoc.isValid()) {
7897
0
          Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7898
0
              << FixItHint::CreateReplacement(DefaultLoc, "delete");
7899
0
        }
7900
0
      }
7901
0
      if (ShouldDeleteForTypeMismatch && !HadError) {
7902
0
        Diag(MD->getLocation(),
7903
0
             diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7904
0
      }
7905
0
    } else {
7906
      // C++11 [dcl.fct.def.default]p4:
7907
      //   [For a] user-provided explicitly-defaulted function [...] if such a
7908
      //   function is implicitly defined as deleted, the program is ill-formed.
7909
0
      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7910
0
      assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7911
0
      ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7912
0
      HadError = true;
7913
0
    }
7914
0
  }
7915
7916
0
  return HadError;
7917
0
}
7918
7919
namespace {
7920
/// Helper class for building and checking a defaulted comparison.
7921
///
7922
/// Defaulted functions are built in two phases:
7923
///
7924
///  * First, the set of operations that the function will perform are
7925
///    identified, and some of them are checked. If any of the checked
7926
///    operations is invalid in certain ways, the comparison function is
7927
///    defined as deleted and no body is built.
7928
///  * Then, if the function is not defined as deleted, the body is built.
7929
///
7930
/// This is accomplished by performing two visitation steps over the eventual
7931
/// body of the function.
7932
template<typename Derived, typename ResultList, typename Result,
7933
         typename Subobject>
7934
class DefaultedComparisonVisitor {
7935
public:
7936
  using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7937
7938
  DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7939
                             DefaultedComparisonKind DCK)
7940
0
      : S(S), RD(RD), FD(FD), DCK(DCK) {
7941
0
    if (auto *Info = FD->getDefaultedFunctionInfo()) {
7942
      // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7943
      // UnresolvedSet to avoid this copy.
7944
0
      Fns.assign(Info->getUnqualifiedLookups().begin(),
7945
0
                 Info->getUnqualifiedLookups().end());
7946
0
    }
7947
0
  }
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::DefaultedComparisonVisitor<(anonymous namespace)::DefaultedComparisonAnalyzer, (anonymous namespace)::DefaultedComparisonInfo, (anonymous namespace)::DefaultedComparisonInfo, (anonymous namespace)::DefaultedComparisonSubobject>::DefaultedComparisonVisitor(clang::Sema&, clang::CXXRecordDecl*, clang::FunctionDecl*, clang::Sema::DefaultedComparisonKind)
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::DefaultedComparisonVisitor<(anonymous namespace)::DefaultedComparisonSynthesizer, (anonymous namespace)::StmtListResult, clang::ActionResult<clang::Stmt*, true>, std::__1::pair<clang::ActionResult<clang::Expr*, true>, clang::ActionResult<clang::Expr*, true> > >::DefaultedComparisonVisitor(clang::Sema&, clang::CXXRecordDecl*, clang::FunctionDecl*, clang::Sema::DefaultedComparisonKind)
7948
7949
0
  ResultList visit() {
7950
    // The type of an lvalue naming a parameter of this function.
7951
0
    QualType ParamLvalType =
7952
0
        FD->getParamDecl(0)->getType().getNonReferenceType();
7953
7954
0
    ResultList Results;
7955
7956
0
    switch (DCK) {
7957
0
    case DefaultedComparisonKind::None:
7958
0
      llvm_unreachable("not a defaulted comparison");
7959
7960
0
    case DefaultedComparisonKind::Equal:
7961
0
    case DefaultedComparisonKind::ThreeWay:
7962
0
      getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7963
0
      return Results;
7964
7965
0
    case DefaultedComparisonKind::NotEqual:
7966
0
    case DefaultedComparisonKind::Relational:
7967
0
      Results.add(getDerived().visitExpandedSubobject(
7968
0
          ParamLvalType, getDerived().getCompleteObject()));
7969
0
      return Results;
7970
0
    }
7971
0
    llvm_unreachable("");
7972
0
  }
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::DefaultedComparisonVisitor<(anonymous namespace)::DefaultedComparisonAnalyzer, (anonymous namespace)::DefaultedComparisonInfo, (anonymous namespace)::DefaultedComparisonInfo, (anonymous namespace)::DefaultedComparisonSubobject>::visit()
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::DefaultedComparisonVisitor<(anonymous namespace)::DefaultedComparisonSynthesizer, (anonymous namespace)::StmtListResult, clang::ActionResult<clang::Stmt*, true>, std::__1::pair<clang::ActionResult<clang::Expr*, true>, clang::ActionResult<clang::Expr*, true> > >::visit()
7973
7974
protected:
7975
0
  Derived &getDerived() { return static_cast<Derived&>(*this); }
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::DefaultedComparisonVisitor<(anonymous namespace)::DefaultedComparisonAnalyzer, (anonymous namespace)::DefaultedComparisonInfo, (anonymous namespace)::DefaultedComparisonInfo, (anonymous namespace)::DefaultedComparisonSubobject>::getDerived()
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::DefaultedComparisonVisitor<(anonymous namespace)::DefaultedComparisonSynthesizer, (anonymous namespace)::StmtListResult, clang::ActionResult<clang::Stmt*, true>, std::__1::pair<clang::ActionResult<clang::Expr*, true>, clang::ActionResult<clang::Expr*, true> > >::getDerived()
7976
7977
  /// Visit the expanded list of subobjects of the given type, as specified in
7978
  /// C++2a [class.compare.default].
7979
  ///
7980
  /// \return \c true if the ResultList object said we're done, \c false if not.
7981
  bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7982
0
                       Qualifiers Quals) {
7983
    // C++2a [class.compare.default]p4:
7984
    //   The direct base class subobjects of C
7985
0
    for (CXXBaseSpecifier &Base : Record->bases())
7986
0
      if (Results.add(getDerived().visitSubobject(
7987
0
              S.Context.getQualifiedType(Base.getType(), Quals),
7988
0
              getDerived().getBase(&Base))))
7989
0
        return true;
7990
7991
    //   followed by the non-static data members of C
7992
0
    for (FieldDecl *Field : Record->fields()) {
7993
      // C++23 [class.bit]p2:
7994
      //   Unnamed bit-fields are not members ...
7995
0
      if (Field->isUnnamedBitfield())
7996
0
        continue;
7997
      // Recursively expand anonymous structs.
7998
0
      if (Field->isAnonymousStructOrUnion()) {
7999
0
        if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
8000
0
                            Quals))
8001
0
          return true;
8002
0
        continue;
8003
0
      }
8004
8005
      // Figure out the type of an lvalue denoting this field.
8006
0
      Qualifiers FieldQuals = Quals;
8007
0
      if (Field->isMutable())
8008
0
        FieldQuals.removeConst();
8009
0
      QualType FieldType =
8010
0
          S.Context.getQualifiedType(Field->getType(), FieldQuals);
8011
8012
0
      if (Results.add(getDerived().visitSubobject(
8013
0
              FieldType, getDerived().getField(Field))))
8014
0
        return true;
8015
0
    }
8016
8017
    //   form a list of subobjects.
8018
0
    return false;
8019
0
  }
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::DefaultedComparisonVisitor<(anonymous namespace)::DefaultedComparisonAnalyzer, (anonymous namespace)::DefaultedComparisonInfo, (anonymous namespace)::DefaultedComparisonInfo, (anonymous namespace)::DefaultedComparisonSubobject>::visitSubobjects((anonymous namespace)::DefaultedComparisonInfo&, clang::CXXRecordDecl*, clang::Qualifiers)
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::DefaultedComparisonVisitor<(anonymous namespace)::DefaultedComparisonSynthesizer, (anonymous namespace)::StmtListResult, clang::ActionResult<clang::Stmt*, true>, std::__1::pair<clang::ActionResult<clang::Expr*, true>, clang::ActionResult<clang::Expr*, true> > >::visitSubobjects((anonymous namespace)::StmtListResult&, clang::CXXRecordDecl*, clang::Qualifiers)
8020
8021
0
  Result visitSubobject(QualType Type, Subobject Subobj) {
8022
    //   In that list, any subobject of array type is recursively expanded
8023
0
    const ArrayType *AT = S.Context.getAsArrayType(Type);
8024
0
    if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
8025
0
      return getDerived().visitSubobjectArray(CAT->getElementType(),
8026
0
                                              CAT->getSize(), Subobj);
8027
0
    return getDerived().visitExpandedSubobject(Type, Subobj);
8028
0
  }
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::DefaultedComparisonVisitor<(anonymous namespace)::DefaultedComparisonAnalyzer, (anonymous namespace)::DefaultedComparisonInfo, (anonymous namespace)::DefaultedComparisonInfo, (anonymous namespace)::DefaultedComparisonSubobject>::visitSubobject(clang::QualType, (anonymous namespace)::DefaultedComparisonSubobject)
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::DefaultedComparisonVisitor<(anonymous namespace)::DefaultedComparisonSynthesizer, (anonymous namespace)::StmtListResult, clang::ActionResult<clang::Stmt*, true>, std::__1::pair<clang::ActionResult<clang::Expr*, true>, clang::ActionResult<clang::Expr*, true> > >::visitSubobject(clang::QualType, std::__1::pair<clang::ActionResult<clang::Expr*, true>, clang::ActionResult<clang::Expr*, true> >)
8029
8030
  Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8031
0
                             Subobject Subobj) {
8032
0
    return getDerived().visitSubobject(Type, Subobj);
8033
0
  }
8034
8035
protected:
8036
  Sema &S;
8037
  CXXRecordDecl *RD;
8038
  FunctionDecl *FD;
8039
  DefaultedComparisonKind DCK;
8040
  UnresolvedSet<16> Fns;
8041
};
8042
8043
/// Information about a defaulted comparison, as determined by
8044
/// DefaultedComparisonAnalyzer.
8045
struct DefaultedComparisonInfo {
8046
  bool Deleted = false;
8047
  bool Constexpr = true;
8048
  ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8049
8050
0
  static DefaultedComparisonInfo deleted() {
8051
0
    DefaultedComparisonInfo Deleted;
8052
0
    Deleted.Deleted = true;
8053
0
    return Deleted;
8054
0
  }
8055
8056
0
  bool add(const DefaultedComparisonInfo &R) {
8057
0
    Deleted |= R.Deleted;
8058
0
    Constexpr &= R.Constexpr;
8059
0
    Category = commonComparisonType(Category, R.Category);
8060
0
    return Deleted;
8061
0
  }
8062
};
8063
8064
/// An element in the expanded list of subobjects of a defaulted comparison, as
8065
/// specified in C++2a [class.compare.default]p4.
8066
struct DefaultedComparisonSubobject {
8067
  enum { CompleteObject, Member, Base } Kind;
8068
  NamedDecl *Decl;
8069
  SourceLocation Loc;
8070
};
8071
8072
/// A visitor over the notional body of a defaulted comparison that determines
8073
/// whether that body would be deleted or constexpr.
8074
class DefaultedComparisonAnalyzer
8075
    : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8076
                                        DefaultedComparisonInfo,
8077
                                        DefaultedComparisonInfo,
8078
                                        DefaultedComparisonSubobject> {
8079
public:
8080
  enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8081
8082
private:
8083
  DiagnosticKind Diagnose;
8084
8085
public:
8086
  using Base = DefaultedComparisonVisitor;
8087
  using Result = DefaultedComparisonInfo;
8088
  using Subobject = DefaultedComparisonSubobject;
8089
8090
  friend Base;
8091
8092
  DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8093
                              DefaultedComparisonKind DCK,
8094
                              DiagnosticKind Diagnose = NoDiagnostics)
8095
0
      : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8096
8097
0
  Result visit() {
8098
0
    if ((DCK == DefaultedComparisonKind::Equal ||
8099
0
         DCK == DefaultedComparisonKind::ThreeWay) &&
8100
0
        RD->hasVariantMembers()) {
8101
      // C++2a [class.compare.default]p2 [P2002R0]:
8102
      //   A defaulted comparison operator function for class C is defined as
8103
      //   deleted if [...] C has variant members.
8104
0
      if (Diagnose == ExplainDeleted) {
8105
0
        S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
8106
0
          << FD << RD->isUnion() << RD;
8107
0
      }
8108
0
      return Result::deleted();
8109
0
    }
8110
8111
0
    return Base::visit();
8112
0
  }
8113
8114
private:
8115
0
  Subobject getCompleteObject() {
8116
0
    return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
8117
0
  }
8118
8119
0
  Subobject getBase(CXXBaseSpecifier *Base) {
8120
0
    return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
8121
0
                     Base->getBaseTypeLoc()};
8122
0
  }
8123
8124
0
  Subobject getField(FieldDecl *Field) {
8125
0
    return Subobject{Subobject::Member, Field, Field->getLocation()};
8126
0
  }
8127
8128
0
  Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8129
    // C++2a [class.compare.default]p2 [P2002R0]:
8130
    //   A defaulted <=> or == operator function for class C is defined as
8131
    //   deleted if any non-static data member of C is of reference type
8132
0
    if (Type->isReferenceType()) {
8133
0
      if (Diagnose == ExplainDeleted) {
8134
0
        S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
8135
0
            << FD << RD;
8136
0
      }
8137
0
      return Result::deleted();
8138
0
    }
8139
8140
    // [...] Let xi be an lvalue denoting the ith element [...]
8141
0
    OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8142
0
    Expr *Args[] = {&Xi, &Xi};
8143
8144
    // All operators start by trying to apply that same operator recursively.
8145
0
    OverloadedOperatorKind OO = FD->getOverloadedOperator();
8146
0
    assert(OO != OO_None && "not an overloaded operator!");
8147
0
    return visitBinaryOperator(OO, Args, Subobj);
8148
0
  }
8149
8150
  Result
8151
  visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8152
                      Subobject Subobj,
8153
0
                      OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8154
    // Note that there is no need to consider rewritten candidates here if
8155
    // we've already found there is no viable 'operator<=>' candidate (and are
8156
    // considering synthesizing a '<=>' from '==' and '<').
8157
0
    OverloadCandidateSet CandidateSet(
8158
0
        FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8159
0
        OverloadCandidateSet::OperatorRewriteInfo(
8160
0
            OO, FD->getLocation(),
8161
0
            /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8162
8163
    /// C++2a [class.compare.default]p1 [P2002R0]:
8164
    ///   [...] the defaulted function itself is never a candidate for overload
8165
    ///   resolution [...]
8166
0
    CandidateSet.exclude(FD);
8167
8168
0
    if (Args[0]->getType()->isOverloadableType())
8169
0
      S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
8170
0
    else
8171
      // FIXME: We determine whether this is a valid expression by checking to
8172
      // see if there's a viable builtin operator candidate for it. That isn't
8173
      // really what the rules ask us to do, but should give the right results.
8174
0
      S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
8175
8176
0
    Result R;
8177
8178
0
    OverloadCandidateSet::iterator Best;
8179
0
    switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
8180
0
    case OR_Success: {
8181
      // C++2a [class.compare.secondary]p2 [P2002R0]:
8182
      //   The operator function [...] is defined as deleted if [...] the
8183
      //   candidate selected by overload resolution is not a rewritten
8184
      //   candidate.
8185
0
      if ((DCK == DefaultedComparisonKind::NotEqual ||
8186
0
           DCK == DefaultedComparisonKind::Relational) &&
8187
0
          !Best->RewriteKind) {
8188
0
        if (Diagnose == ExplainDeleted) {
8189
0
          if (Best->Function) {
8190
0
            S.Diag(Best->Function->getLocation(),
8191
0
                   diag::note_defaulted_comparison_not_rewritten_callee)
8192
0
                << FD;
8193
0
          } else {
8194
0
            assert(Best->Conversions.size() == 2 &&
8195
0
                   Best->Conversions[0].isUserDefined() &&
8196
0
                   "non-user-defined conversion from class to built-in "
8197
0
                   "comparison");
8198
0
            S.Diag(Best->Conversions[0]
8199
0
                       .UserDefined.FoundConversionFunction.getDecl()
8200
0
                       ->getLocation(),
8201
0
                   diag::note_defaulted_comparison_not_rewritten_conversion)
8202
0
                << FD;
8203
0
          }
8204
0
        }
8205
0
        return Result::deleted();
8206
0
      }
8207
8208
      // Throughout C++2a [class.compare]: if overload resolution does not
8209
      // result in a usable function, the candidate function is defined as
8210
      // deleted. This requires that we selected an accessible function.
8211
      //
8212
      // Note that this only considers the access of the function when named
8213
      // within the type of the subobject, and not the access path for any
8214
      // derived-to-base conversion.
8215
0
      CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8216
0
      if (ArgClass && Best->FoundDecl.getDecl() &&
8217
0
          Best->FoundDecl.getDecl()->isCXXClassMember()) {
8218
0
        QualType ObjectType = Subobj.Kind == Subobject::Member
8219
0
                                  ? Args[0]->getType()
8220
0
                                  : S.Context.getRecordType(RD);
8221
0
        if (!S.isMemberAccessibleForDeletion(
8222
0
                ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
8223
0
                Diagnose == ExplainDeleted
8224
0
                    ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
8225
0
                          << FD << Subobj.Kind << Subobj.Decl
8226
0
                    : S.PDiag()))
8227
0
          return Result::deleted();
8228
0
      }
8229
8230
0
      bool NeedsDeducing =
8231
0
          OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8232
8233
0
      if (FunctionDecl *BestFD = Best->Function) {
8234
        // C++2a [class.compare.default]p3 [P2002R0]:
8235
        //   A defaulted comparison function is constexpr-compatible if
8236
        //   [...] no overlod resolution performed [...] results in a
8237
        //   non-constexpr function.
8238
0
        assert(!BestFD->isDeleted() && "wrong overload resolution result");
8239
        // If it's not constexpr, explain why not.
8240
0
        if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8241
0
          if (Subobj.Kind != Subobject::CompleteObject)
8242
0
            S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8243
0
              << Subobj.Kind << Subobj.Decl;
8244
0
          S.Diag(BestFD->getLocation(),
8245
0
                 diag::note_defaulted_comparison_not_constexpr_here);
8246
          // Bail out after explaining; we don't want any more notes.
8247
0
          return Result::deleted();
8248
0
        }
8249
0
        R.Constexpr &= BestFD->isConstexpr();
8250
8251
0
        if (NeedsDeducing) {
8252
          // If any callee has an undeduced return type, deduce it now.
8253
          // FIXME: It's not clear how a failure here should be handled. For
8254
          // now, we produce an eager diagnostic, because that is forward
8255
          // compatible with most (all?) other reasonable options.
8256
0
          if (BestFD->getReturnType()->isUndeducedType() &&
8257
0
              S.DeduceReturnType(BestFD, FD->getLocation(),
8258
0
                                 /*Diagnose=*/false)) {
8259
            // Don't produce a duplicate error when asked to explain why the
8260
            // comparison is deleted: we diagnosed that when initially checking
8261
            // the defaulted operator.
8262
0
            if (Diagnose == NoDiagnostics) {
8263
0
              S.Diag(
8264
0
                  FD->getLocation(),
8265
0
                  diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8266
0
                  << Subobj.Kind << Subobj.Decl;
8267
0
              S.Diag(
8268
0
                  Subobj.Loc,
8269
0
                  diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8270
0
                  << Subobj.Kind << Subobj.Decl;
8271
0
              S.Diag(BestFD->getLocation(),
8272
0
                     diag::note_defaulted_comparison_cannot_deduce_callee)
8273
0
                  << Subobj.Kind << Subobj.Decl;
8274
0
            }
8275
0
            return Result::deleted();
8276
0
          }
8277
0
          auto *Info = S.Context.CompCategories.lookupInfoForType(
8278
0
              BestFD->getCallResultType());
8279
0
          if (!Info) {
8280
0
            if (Diagnose == ExplainDeleted) {
8281
0
              S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8282
0
                  << Subobj.Kind << Subobj.Decl
8283
0
                  << BestFD->getCallResultType().withoutLocalFastQualifiers();
8284
0
              S.Diag(BestFD->getLocation(),
8285
0
                     diag::note_defaulted_comparison_cannot_deduce_callee)
8286
0
                  << Subobj.Kind << Subobj.Decl;
8287
0
            }
8288
0
            return Result::deleted();
8289
0
          }
8290
0
          R.Category = Info->Kind;
8291
0
        }
8292
0
      } else {
8293
0
        QualType T = Best->BuiltinParamTypes[0];
8294
0
        assert(T == Best->BuiltinParamTypes[1] &&
8295
0
               "builtin comparison for different types?");
8296
0
        assert(Best->BuiltinParamTypes[2].isNull() &&
8297
0
               "invalid builtin comparison");
8298
8299
0
        if (NeedsDeducing) {
8300
0
          std::optional<ComparisonCategoryType> Cat =
8301
0
              getComparisonCategoryForBuiltinCmp(T);
8302
0
          assert(Cat && "no category for builtin comparison?");
8303
0
          R.Category = *Cat;
8304
0
        }
8305
0
      }
8306
8307
      // Note that we might be rewriting to a different operator. That call is
8308
      // not considered until we come to actually build the comparison function.
8309
0
      break;
8310
0
    }
8311
8312
0
    case OR_Ambiguous:
8313
0
      if (Diagnose == ExplainDeleted) {
8314
0
        unsigned Kind = 0;
8315
0
        if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8316
0
          Kind = OO == OO_EqualEqual ? 1 : 2;
8317
0
        CandidateSet.NoteCandidates(
8318
0
            PartialDiagnosticAt(
8319
0
                Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8320
0
                                << FD << Kind << Subobj.Kind << Subobj.Decl),
8321
0
            S, OCD_AmbiguousCandidates, Args);
8322
0
      }
8323
0
      R = Result::deleted();
8324
0
      break;
8325
8326
0
    case OR_Deleted:
8327
0
      if (Diagnose == ExplainDeleted) {
8328
0
        if ((DCK == DefaultedComparisonKind::NotEqual ||
8329
0
             DCK == DefaultedComparisonKind::Relational) &&
8330
0
            !Best->RewriteKind) {
8331
0
          S.Diag(Best->Function->getLocation(),
8332
0
                 diag::note_defaulted_comparison_not_rewritten_callee)
8333
0
              << FD;
8334
0
        } else {
8335
0
          S.Diag(Subobj.Loc,
8336
0
                 diag::note_defaulted_comparison_calls_deleted)
8337
0
              << FD << Subobj.Kind << Subobj.Decl;
8338
0
          S.NoteDeletedFunction(Best->Function);
8339
0
        }
8340
0
      }
8341
0
      R = Result::deleted();
8342
0
      break;
8343
8344
0
    case OR_No_Viable_Function:
8345
      // If there's no usable candidate, we're done unless we can rewrite a
8346
      // '<=>' in terms of '==' and '<'.
8347
0
      if (OO == OO_Spaceship &&
8348
0
          S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
8349
        // For any kind of comparison category return type, we need a usable
8350
        // '==' and a usable '<'.
8351
0
        if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8352
0
                                       &CandidateSet)))
8353
0
          R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8354
0
        break;
8355
0
      }
8356
8357
0
      if (Diagnose == ExplainDeleted) {
8358
0
        S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8359
0
            << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8360
0
            << Subobj.Kind << Subobj.Decl;
8361
8362
        // For a three-way comparison, list both the candidates for the
8363
        // original operator and the candidates for the synthesized operator.
8364
0
        if (SpaceshipCandidates) {
8365
0
          SpaceshipCandidates->NoteCandidates(
8366
0
              S, Args,
8367
0
              SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8368
0
                                                      Args, FD->getLocation()));
8369
0
          S.Diag(Subobj.Loc,
8370
0
                 diag::note_defaulted_comparison_no_viable_function_synthesized)
8371
0
              << (OO == OO_EqualEqual ? 0 : 1);
8372
0
        }
8373
8374
0
        CandidateSet.NoteCandidates(
8375
0
            S, Args,
8376
0
            CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8377
0
                                            FD->getLocation()));
8378
0
      }
8379
0
      R = Result::deleted();
8380
0
      break;
8381
0
    }
8382
8383
0
    return R;
8384
0
  }
8385
};
8386
8387
/// A list of statements.
8388
struct StmtListResult {
8389
  bool IsInvalid = false;
8390
  llvm::SmallVector<Stmt*, 16> Stmts;
8391
8392
0
  bool add(const StmtResult &S) {
8393
0
    IsInvalid |= S.isInvalid();
8394
0
    if (IsInvalid)
8395
0
      return true;
8396
0
    Stmts.push_back(S.get());
8397
0
    return false;
8398
0
  }
8399
};
8400
8401
/// A visitor over the notional body of a defaulted comparison that synthesizes
8402
/// the actual body.
8403
class DefaultedComparisonSynthesizer
8404
    : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8405
                                        StmtListResult, StmtResult,
8406
                                        std::pair<ExprResult, ExprResult>> {
8407
  SourceLocation Loc;
8408
  unsigned ArrayDepth = 0;
8409
8410
public:
8411
  using Base = DefaultedComparisonVisitor;
8412
  using ExprPair = std::pair<ExprResult, ExprResult>;
8413
8414
  friend Base;
8415
8416
  DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8417
                                 DefaultedComparisonKind DCK,
8418
                                 SourceLocation BodyLoc)
8419
0
      : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8420
8421
  /// Build a suitable function body for this defaulted comparison operator.
8422
0
  StmtResult build() {
8423
0
    Sema::CompoundScopeRAII CompoundScope(S);
8424
8425
0
    StmtListResult Stmts = visit();
8426
0
    if (Stmts.IsInvalid)
8427
0
      return StmtError();
8428
8429
0
    ExprResult RetVal;
8430
0
    switch (DCK) {
8431
0
    case DefaultedComparisonKind::None:
8432
0
      llvm_unreachable("not a defaulted comparison");
8433
8434
0
    case DefaultedComparisonKind::Equal: {
8435
      // C++2a [class.eq]p3:
8436
      //   [...] compar[e] the corresponding elements [...] until the first
8437
      //   index i where xi == yi yields [...] false. If no such index exists,
8438
      //   V is true. Otherwise, V is false.
8439
      //
8440
      // Join the comparisons with '&&'s and return the result. Use a right
8441
      // fold (traversing the conditions right-to-left), because that
8442
      // short-circuits more naturally.
8443
0
      auto OldStmts = std::move(Stmts.Stmts);
8444
0
      Stmts.Stmts.clear();
8445
0
      ExprResult CmpSoFar;
8446
      // Finish a particular comparison chain.
8447
0
      auto FinishCmp = [&] {
8448
0
        if (Expr *Prior = CmpSoFar.get()) {
8449
          // Convert the last expression to 'return ...;'
8450
0
          if (RetVal.isUnset() && Stmts.Stmts.empty())
8451
0
            RetVal = CmpSoFar;
8452
          // Convert any prior comparison to 'if (!(...)) return false;'
8453
0
          else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8454
0
            return true;
8455
0
          CmpSoFar = ExprResult();
8456
0
        }
8457
0
        return false;
8458
0
      };
8459
0
      for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8460
0
        Expr *E = dyn_cast<Expr>(EAsStmt);
8461
0
        if (!E) {
8462
          // Found an array comparison.
8463
0
          if (FinishCmp() || Stmts.add(EAsStmt))
8464
0
            return StmtError();
8465
0
          continue;
8466
0
        }
8467
8468
0
        if (CmpSoFar.isUnset()) {
8469
0
          CmpSoFar = E;
8470
0
          continue;
8471
0
        }
8472
0
        CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8473
0
        if (CmpSoFar.isInvalid())
8474
0
          return StmtError();
8475
0
      }
8476
0
      if (FinishCmp())
8477
0
        return StmtError();
8478
0
      std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8479
      //   If no such index exists, V is true.
8480
0
      if (RetVal.isUnset())
8481
0
        RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8482
0
      break;
8483
0
    }
8484
8485
0
    case DefaultedComparisonKind::ThreeWay: {
8486
      // Per C++2a [class.spaceship]p3, as a fallback add:
8487
      // return static_cast<R>(std::strong_ordering::equal);
8488
0
      QualType StrongOrdering = S.CheckComparisonCategoryType(
8489
0
          ComparisonCategoryType::StrongOrdering, Loc,
8490
0
          Sema::ComparisonCategoryUsage::DefaultedOperator);
8491
0
      if (StrongOrdering.isNull())
8492
0
        return StmtError();
8493
0
      VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8494
0
                             .getValueInfo(ComparisonCategoryResult::Equal)
8495
0
                             ->VD;
8496
0
      RetVal = getDecl(EqualVD);
8497
0
      if (RetVal.isInvalid())
8498
0
        return StmtError();
8499
0
      RetVal = buildStaticCastToR(RetVal.get());
8500
0
      break;
8501
0
    }
8502
8503
0
    case DefaultedComparisonKind::NotEqual:
8504
0
    case DefaultedComparisonKind::Relational:
8505
0
      RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8506
0
      break;
8507
0
    }
8508
8509
    // Build the final return statement.
8510
0
    if (RetVal.isInvalid())
8511
0
      return StmtError();
8512
0
    StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8513
0
    if (ReturnStmt.isInvalid())
8514
0
      return StmtError();
8515
0
    Stmts.Stmts.push_back(ReturnStmt.get());
8516
8517
0
    return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8518
0
  }
8519
8520
private:
8521
0
  ExprResult getDecl(ValueDecl *VD) {
8522
0
    return S.BuildDeclarationNameExpr(
8523
0
        CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8524
0
  }
8525
8526
0
  ExprResult getParam(unsigned I) {
8527
0
    ParmVarDecl *PD = FD->getParamDecl(I);
8528
0
    return getDecl(PD);
8529
0
  }
8530
8531
0
  ExprPair getCompleteObject() {
8532
0
    unsigned Param = 0;
8533
0
    ExprResult LHS;
8534
0
    if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
8535
0
        MD && MD->isImplicitObjectMemberFunction()) {
8536
      // LHS is '*this'.
8537
0
      LHS = S.ActOnCXXThis(Loc);
8538
0
      if (!LHS.isInvalid())
8539
0
        LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8540
0
    } else {
8541
0
      LHS = getParam(Param++);
8542
0
    }
8543
0
    ExprResult RHS = getParam(Param++);
8544
0
    assert(Param == FD->getNumParams());
8545
0
    return {LHS, RHS};
8546
0
  }
8547
8548
0
  ExprPair getBase(CXXBaseSpecifier *Base) {
8549
0
    ExprPair Obj = getCompleteObject();
8550
0
    if (Obj.first.isInvalid() || Obj.second.isInvalid())
8551
0
      return {ExprError(), ExprError()};
8552
0
    CXXCastPath Path = {Base};
8553
0
    return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8554
0
                                CK_DerivedToBase, VK_LValue, &Path),
8555
0
            S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8556
0
                                CK_DerivedToBase, VK_LValue, &Path)};
8557
0
  }
8558
8559
0
  ExprPair getField(FieldDecl *Field) {
8560
0
    ExprPair Obj = getCompleteObject();
8561
0
    if (Obj.first.isInvalid() || Obj.second.isInvalid())
8562
0
      return {ExprError(), ExprError()};
8563
8564
0
    DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8565
0
    DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8566
0
    return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8567
0
                                      CXXScopeSpec(), Field, Found, NameInfo),
8568
0
            S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8569
0
                                      CXXScopeSpec(), Field, Found, NameInfo)};
8570
0
  }
8571
8572
  // FIXME: When expanding a subobject, register a note in the code synthesis
8573
  // stack to say which subobject we're comparing.
8574
8575
0
  StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8576
0
    if (Cond.isInvalid())
8577
0
      return StmtError();
8578
8579
0
    ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8580
0
    if (NotCond.isInvalid())
8581
0
      return StmtError();
8582
8583
0
    ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8584
0
    assert(!False.isInvalid() && "should never fail");
8585
0
    StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8586
0
    if (ReturnFalse.isInvalid())
8587
0
      return StmtError();
8588
8589
0
    return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8590
0
                         S.ActOnCondition(nullptr, Loc, NotCond.get(),
8591
0
                                          Sema::ConditionKind::Boolean),
8592
0
                         Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8593
0
  }
8594
8595
  StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8596
0
                                 ExprPair Subobj) {
8597
0
    QualType SizeType = S.Context.getSizeType();
8598
0
    Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8599
8600
    // Build 'size_t i$n = 0'.
8601
0
    IdentifierInfo *IterationVarName = nullptr;
8602
0
    {
8603
0
      SmallString<8> Str;
8604
0
      llvm::raw_svector_ostream OS(Str);
8605
0
      OS << "i" << ArrayDepth;
8606
0
      IterationVarName = &S.Context.Idents.get(OS.str());
8607
0
    }
8608
0
    VarDecl *IterationVar = VarDecl::Create(
8609
0
        S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8610
0
        S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8611
0
    llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8612
0
    IterationVar->setInit(
8613
0
        IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8614
0
    Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8615
8616
0
    auto IterRef = [&] {
8617
0
      ExprResult Ref = S.BuildDeclarationNameExpr(
8618
0
          CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8619
0
          IterationVar);
8620
0
      assert(!Ref.isInvalid() && "can't reference our own variable?");
8621
0
      return Ref.get();
8622
0
    };
8623
8624
    // Build 'i$n != Size'.
8625
0
    ExprResult Cond = S.CreateBuiltinBinOp(
8626
0
        Loc, BO_NE, IterRef(),
8627
0
        IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8628
0
    assert(!Cond.isInvalid() && "should never fail");
8629
8630
    // Build '++i$n'.
8631
0
    ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8632
0
    assert(!Inc.isInvalid() && "should never fail");
8633
8634
    // Build 'a[i$n]' and 'b[i$n]'.
8635
0
    auto Index = [&](ExprResult E) {
8636
0
      if (E.isInvalid())
8637
0
        return ExprError();
8638
0
      return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8639
0
    };
8640
0
    Subobj.first = Index(Subobj.first);
8641
0
    Subobj.second = Index(Subobj.second);
8642
8643
    // Compare the array elements.
8644
0
    ++ArrayDepth;
8645
0
    StmtResult Substmt = visitSubobject(Type, Subobj);
8646
0
    --ArrayDepth;
8647
8648
0
    if (Substmt.isInvalid())
8649
0
      return StmtError();
8650
8651
    // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8652
    // For outer levels or for an 'operator<=>' we already have a suitable
8653
    // statement that returns as necessary.
8654
0
    if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8655
0
      assert(DCK == DefaultedComparisonKind::Equal &&
8656
0
             "should have non-expression statement");
8657
0
      Substmt = buildIfNotCondReturnFalse(ElemCmp);
8658
0
      if (Substmt.isInvalid())
8659
0
        return StmtError();
8660
0
    }
8661
8662
    // Build 'for (...) ...'
8663
0
    return S.ActOnForStmt(Loc, Loc, Init,
8664
0
                          S.ActOnCondition(nullptr, Loc, Cond.get(),
8665
0
                                           Sema::ConditionKind::Boolean),
8666
0
                          S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8667
0
                          Substmt.get());
8668
0
  }
8669
8670
0
  StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8671
0
    if (Obj.first.isInvalid() || Obj.second.isInvalid())
8672
0
      return StmtError();
8673
8674
0
    OverloadedOperatorKind OO = FD->getOverloadedOperator();
8675
0
    BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8676
0
    ExprResult Op;
8677
0
    if (Type->isOverloadableType())
8678
0
      Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8679
0
                                   Obj.second.get(), /*PerformADL=*/true,
8680
0
                                   /*AllowRewrittenCandidates=*/true, FD);
8681
0
    else
8682
0
      Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8683
0
    if (Op.isInvalid())
8684
0
      return StmtError();
8685
8686
0
    switch (DCK) {
8687
0
    case DefaultedComparisonKind::None:
8688
0
      llvm_unreachable("not a defaulted comparison");
8689
8690
0
    case DefaultedComparisonKind::Equal:
8691
      // Per C++2a [class.eq]p2, each comparison is individually contextually
8692
      // converted to bool.
8693
0
      Op = S.PerformContextuallyConvertToBool(Op.get());
8694
0
      if (Op.isInvalid())
8695
0
        return StmtError();
8696
0
      return Op.get();
8697
8698
0
    case DefaultedComparisonKind::ThreeWay: {
8699
      // Per C++2a [class.spaceship]p3, form:
8700
      //   if (R cmp = static_cast<R>(op); cmp != 0)
8701
      //     return cmp;
8702
0
      QualType R = FD->getReturnType();
8703
0
      Op = buildStaticCastToR(Op.get());
8704
0
      if (Op.isInvalid())
8705
0
        return StmtError();
8706
8707
      // R cmp = ...;
8708
0
      IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8709
0
      VarDecl *VD =
8710
0
          VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8711
0
                          S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8712
0
      S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8713
0
      Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8714
8715
      // cmp != 0
8716
0
      ExprResult VDRef = getDecl(VD);
8717
0
      if (VDRef.isInvalid())
8718
0
        return StmtError();
8719
0
      llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8720
0
      Expr *Zero =
8721
0
          IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8722
0
      ExprResult Comp;
8723
0
      if (VDRef.get()->getType()->isOverloadableType())
8724
0
        Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8725
0
                                       true, FD);
8726
0
      else
8727
0
        Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8728
0
      if (Comp.isInvalid())
8729
0
        return StmtError();
8730
0
      Sema::ConditionResult Cond = S.ActOnCondition(
8731
0
          nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8732
0
      if (Cond.isInvalid())
8733
0
        return StmtError();
8734
8735
      // return cmp;
8736
0
      VDRef = getDecl(VD);
8737
0
      if (VDRef.isInvalid())
8738
0
        return StmtError();
8739
0
      StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8740
0
      if (ReturnStmt.isInvalid())
8741
0
        return StmtError();
8742
8743
      // if (...)
8744
0
      return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8745
0
                           Loc, ReturnStmt.get(),
8746
0
                           /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8747
0
    }
8748
8749
0
    case DefaultedComparisonKind::NotEqual:
8750
0
    case DefaultedComparisonKind::Relational:
8751
      // C++2a [class.compare.secondary]p2:
8752
      //   Otherwise, the operator function yields x @ y.
8753
0
      return Op.get();
8754
0
    }
8755
0
    llvm_unreachable("");
8756
0
  }
8757
8758
  /// Build "static_cast<R>(E)".
8759
0
  ExprResult buildStaticCastToR(Expr *E) {
8760
0
    QualType R = FD->getReturnType();
8761
0
    assert(!R->isUndeducedType() && "type should have been deduced already");
8762
8763
    // Don't bother forming a no-op cast in the common case.
8764
0
    if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8765
0
      return E;
8766
0
    return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8767
0
                               S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8768
0
                               SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8769
0
  }
8770
};
8771
}
8772
8773
/// Perform the unqualified lookups that might be needed to form a defaulted
8774
/// comparison function for the given operator.
8775
static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8776
                                                  UnresolvedSetImpl &Operators,
8777
0
                                                  OverloadedOperatorKind Op) {
8778
0
  auto Lookup = [&](OverloadedOperatorKind OO) {
8779
0
    Self.LookupOverloadedOperatorName(OO, S, Operators);
8780
0
  };
8781
8782
  // Every defaulted operator looks up itself.
8783
0
  Lookup(Op);
8784
  // ... and the rewritten form of itself, if any.
8785
0
  if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8786
0
    Lookup(ExtraOp);
8787
8788
  // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8789
  // synthesize a three-way comparison from '<' and '=='. In a dependent
8790
  // context, we also need to look up '==' in case we implicitly declare a
8791
  // defaulted 'operator=='.
8792
0
  if (Op == OO_Spaceship) {
8793
0
    Lookup(OO_ExclaimEqual);
8794
0
    Lookup(OO_Less);
8795
0
    Lookup(OO_EqualEqual);
8796
0
  }
8797
0
}
8798
8799
bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8800
0
                                              DefaultedComparisonKind DCK) {
8801
0
  assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8802
8803
  // Perform any unqualified lookups we're going to need to default this
8804
  // function.
8805
0
  if (S) {
8806
0
    UnresolvedSet<32> Operators;
8807
0
    lookupOperatorsForDefaultedComparison(*this, S, Operators,
8808
0
                                          FD->getOverloadedOperator());
8809
0
    FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8810
0
        Context, Operators.pairs()));
8811
0
  }
8812
8813
  // C++2a [class.compare.default]p1:
8814
  //   A defaulted comparison operator function for some class C shall be a
8815
  //   non-template function declared in the member-specification of C that is
8816
  //    -- a non-static const non-volatile member of C having one parameter of
8817
  //       type const C& and either no ref-qualifier or the ref-qualifier &, or
8818
  //    -- a friend of C having two parameters of type const C& or two
8819
  //       parameters of type C.
8820
8821
0
  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8822
0
  bool IsMethod = isa<CXXMethodDecl>(FD);
8823
0
  if (IsMethod) {
8824
0
    auto *MD = cast<CXXMethodDecl>(FD);
8825
0
    assert(!MD->isStatic() && "comparison function cannot be a static member");
8826
8827
0
    if (MD->getRefQualifier() == RQ_RValue) {
8828
0
      Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator);
8829
8830
      // Remove the ref qualifier to recover.
8831
0
      const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8832
0
      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8833
0
      EPI.RefQualifier = RQ_None;
8834
0
      MD->setType(Context.getFunctionType(FPT->getReturnType(),
8835
0
                                          FPT->getParamTypes(), EPI));
8836
0
    }
8837
8838
    // If we're out-of-class, this is the class we're comparing.
8839
0
    if (!RD)
8840
0
      RD = MD->getParent();
8841
0
    QualType T = MD->getFunctionObjectParameterType();
8842
0
    if (!T.isConstQualified()) {
8843
0
      SourceLocation Loc, InsertLoc;
8844
0
      if (MD->isExplicitObjectMemberFunction()) {
8845
0
        Loc = MD->getParamDecl(0)->getBeginLoc();
8846
0
        InsertLoc = getLocForEndOfToken(
8847
0
            MD->getParamDecl(0)->getExplicitObjectParamThisLoc());
8848
0
      } else {
8849
0
        Loc = MD->getLocation();
8850
0
        if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8851
0
          InsertLoc = Loc.getRParenLoc();
8852
0
      }
8853
      // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8854
      // corresponding defaulted 'operator<=>' already.
8855
0
      if (!MD->isImplicit()) {
8856
0
        Diag(Loc, diag::err_defaulted_comparison_non_const)
8857
0
            << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8858
0
      }
8859
8860
      // Add the 'const' to the type to recover.
8861
0
      const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8862
0
      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8863
0
      EPI.TypeQuals.addConst();
8864
0
      MD->setType(Context.getFunctionType(FPT->getReturnType(),
8865
0
                                          FPT->getParamTypes(), EPI));
8866
0
    }
8867
8868
0
    if (MD->isVolatile()) {
8869
0
      Diag(MD->getLocation(), diag::err_volatile_comparison_operator);
8870
8871
      // Remove the 'volatile' from the type to recover.
8872
0
      const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8873
0
      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8874
0
      EPI.TypeQuals.removeVolatile();
8875
0
      MD->setType(Context.getFunctionType(FPT->getReturnType(),
8876
0
                                          FPT->getParamTypes(), EPI));
8877
0
    }
8878
0
  }
8879
8880
0
  if ((FD->getNumParams() -
8881
0
       (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
8882
0
      (IsMethod ? 1 : 2)) {
8883
    // Let's not worry about using a variadic template pack here -- who would do
8884
    // such a thing?
8885
0
    Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8886
0
        << int(IsMethod) << int(DCK);
8887
0
    return true;
8888
0
  }
8889
8890
0
  const ParmVarDecl *KnownParm = nullptr;
8891
0
  for (const ParmVarDecl *Param : FD->parameters()) {
8892
0
    if (Param->isExplicitObjectParameter())
8893
0
      continue;
8894
0
    QualType ParmTy = Param->getType();
8895
8896
0
    if (!KnownParm) {
8897
0
      auto CTy = ParmTy;
8898
      // Is it `T const &`?
8899
0
      bool Ok = !IsMethod;
8900
0
      QualType ExpectedTy;
8901
0
      if (RD)
8902
0
        ExpectedTy = Context.getRecordType(RD);
8903
0
      if (auto *Ref = CTy->getAs<ReferenceType>()) {
8904
0
        CTy = Ref->getPointeeType();
8905
0
        if (RD)
8906
0
          ExpectedTy.addConst();
8907
0
        Ok = true;
8908
0
      }
8909
8910
      // Is T a class?
8911
0
      if (!Ok) {
8912
0
      } else if (RD) {
8913
0
        if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8914
0
          Ok = false;
8915
0
      } else if (auto *CRD = CTy->getAsRecordDecl()) {
8916
0
        RD = cast<CXXRecordDecl>(CRD);
8917
0
      } else {
8918
0
        Ok = false;
8919
0
      }
8920
8921
0
      if (Ok) {
8922
0
        KnownParm = Param;
8923
0
      } else {
8924
        // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8925
        // corresponding defaulted 'operator<=>' already.
8926
0
        if (!FD->isImplicit()) {
8927
0
          if (RD) {
8928
0
            QualType PlainTy = Context.getRecordType(RD);
8929
0
            QualType RefTy =
8930
0
                Context.getLValueReferenceType(PlainTy.withConst());
8931
0
            Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8932
0
                << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8933
0
                << Param->getSourceRange();
8934
0
          } else {
8935
0
            assert(!IsMethod && "should know expected type for method");
8936
0
            Diag(FD->getLocation(),
8937
0
                 diag::err_defaulted_comparison_param_unknown)
8938
0
                << int(DCK) << ParmTy << Param->getSourceRange();
8939
0
          }
8940
0
        }
8941
0
        return true;
8942
0
      }
8943
0
    } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8944
0
      Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8945
0
          << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8946
0
          << ParmTy << Param->getSourceRange();
8947
0
      return true;
8948
0
    }
8949
0
  }
8950
8951
0
  assert(RD && "must have determined class");
8952
0
  if (IsMethod) {
8953
0
  } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8954
    // In-class, must be a friend decl.
8955
0
    assert(FD->getFriendObjectKind() && "expected a friend declaration");
8956
0
  } else {
8957
    // Out of class, require the defaulted comparison to be a friend (of a
8958
    // complete type).
8959
0
    if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8960
0
                            diag::err_defaulted_comparison_not_friend, int(DCK),
8961
0
                            int(1)))
8962
0
      return true;
8963
8964
0
    if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8965
0
          return FD->getCanonicalDecl() ==
8966
0
                 F->getFriendDecl()->getCanonicalDecl();
8967
0
        })) {
8968
0
      Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8969
0
          << int(DCK) << int(0) << RD;
8970
0
      Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8971
0
      return true;
8972
0
    }
8973
0
  }
8974
8975
  // C++2a [class.eq]p1, [class.rel]p1:
8976
  //   A [defaulted comparison other than <=>] shall have a declared return
8977
  //   type bool.
8978
0
  if (DCK != DefaultedComparisonKind::ThreeWay &&
8979
0
      !FD->getDeclaredReturnType()->isDependentType() &&
8980
0
      !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8981
0
    Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8982
0
        << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8983
0
        << FD->getReturnTypeSourceRange();
8984
0
    return true;
8985
0
  }
8986
  // C++2a [class.spaceship]p2 [P2002R0]:
8987
  //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8988
  //   R shall not contain a placeholder type.
8989
0
  if (QualType RT = FD->getDeclaredReturnType();
8990
0
      DCK == DefaultedComparisonKind::ThreeWay &&
8991
0
      RT->getContainedDeducedType() &&
8992
0
      (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
8993
0
       RT->getContainedAutoType()->isConstrained())) {
8994
0
    Diag(FD->getLocation(),
8995
0
         diag::err_defaulted_comparison_deduced_return_type_not_auto)
8996
0
        << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8997
0
        << FD->getReturnTypeSourceRange();
8998
0
    return true;
8999
0
  }
9000
9001
  // For a defaulted function in a dependent class, defer all remaining checks
9002
  // until instantiation.
9003
0
  if (RD->isDependentType())
9004
0
    return false;
9005
9006
  // Determine whether the function should be defined as deleted.
9007
0
  DefaultedComparisonInfo Info =
9008
0
      DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9009
9010
0
  bool First = FD == FD->getCanonicalDecl();
9011
9012
0
  if (!First) {
9013
0
    if (Info.Deleted) {
9014
      // C++11 [dcl.fct.def.default]p4:
9015
      //   [For a] user-provided explicitly-defaulted function [...] if such a
9016
      //   function is implicitly defined as deleted, the program is ill-formed.
9017
      //
9018
      // This is really just a consequence of the general rule that you can
9019
      // only delete a function on its first declaration.
9020
0
      Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
9021
0
          << FD->isImplicit() << (int)DCK;
9022
0
      DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9023
0
                                  DefaultedComparisonAnalyzer::ExplainDeleted)
9024
0
          .visit();
9025
0
      return true;
9026
0
    }
9027
0
    if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
9028
      // C++20 [class.compare.default]p1:
9029
      //   [...] A definition of a comparison operator as defaulted that appears
9030
      //   in a class shall be the first declaration of that function.
9031
0
      Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class)
9032
0
          << (int)DCK;
9033
0
      Diag(FD->getCanonicalDecl()->getLocation(),
9034
0
           diag::note_previous_declaration);
9035
0
      return true;
9036
0
    }
9037
0
  }
9038
9039
  // If we want to delete the function, then do so; there's nothing else to
9040
  // check in that case.
9041
0
  if (Info.Deleted) {
9042
0
    SetDeclDeleted(FD, FD->getLocation());
9043
0
    if (!inTemplateInstantiation() && !FD->isImplicit()) {
9044
0
      Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
9045
0
          << (int)DCK;
9046
0
      DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9047
0
                                  DefaultedComparisonAnalyzer::ExplainDeleted)
9048
0
          .visit();
9049
0
      if (FD->getDefaultLoc().isValid())
9050
0
        Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
9051
0
            << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
9052
0
    }
9053
0
    return false;
9054
0
  }
9055
9056
  // C++2a [class.spaceship]p2:
9057
  //   The return type is deduced as the common comparison type of R0, R1, ...
9058
0
  if (DCK == DefaultedComparisonKind::ThreeWay &&
9059
0
      FD->getDeclaredReturnType()->isUndeducedAutoType()) {
9060
0
    SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
9061
0
    if (RetLoc.isInvalid())
9062
0
      RetLoc = FD->getBeginLoc();
9063
    // FIXME: Should we really care whether we have the complete type and the
9064
    // 'enumerator' constants here? A forward declaration seems sufficient.
9065
0
    QualType Cat = CheckComparisonCategoryType(
9066
0
        Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
9067
0
    if (Cat.isNull())
9068
0
      return true;
9069
0
    Context.adjustDeducedFunctionResultType(
9070
0
        FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
9071
0
  }
9072
9073
  // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9074
  //   An explicitly-defaulted function that is not defined as deleted may be
9075
  //   declared constexpr or consteval only if it is constexpr-compatible.
9076
  // C++2a [class.compare.default]p3 [P2002R0]:
9077
  //   A defaulted comparison function is constexpr-compatible if it satisfies
9078
  //   the requirements for a constexpr function [...]
9079
  // The only relevant requirements are that the parameter and return types are
9080
  // literal types. The remaining conditions are checked by the analyzer.
9081
  //
9082
  // We support P2448R2 in language modes earlier than C++23 as an extension.
9083
  // The concept of constexpr-compatible was removed.
9084
  // C++23 [dcl.fct.def.default]p3 [P2448R2]
9085
  //  A function explicitly defaulted on its first declaration is implicitly
9086
  //  inline, and is implicitly constexpr if it is constexpr-suitable.
9087
  // C++23 [dcl.constexpr]p3
9088
  //   A function is constexpr-suitable if
9089
  //    - it is not a coroutine, and
9090
  //    - if the function is a constructor or destructor, its class does not
9091
  //      have any virtual base classes.
9092
0
  if (FD->isConstexpr()) {
9093
0
    if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
9094
0
        CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
9095
0
        !Info.Constexpr) {
9096
0
      Diag(FD->getBeginLoc(),
9097
0
           getLangOpts().CPlusPlus23
9098
0
               ? diag::warn_cxx23_compat_defaulted_comparison_constexpr_mismatch
9099
0
               : diag::ext_defaulted_comparison_constexpr_mismatch)
9100
0
          << FD->isImplicit() << (int)DCK << FD->isConsteval();
9101
0
      DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9102
0
                                  DefaultedComparisonAnalyzer::ExplainConstexpr)
9103
0
          .visit();
9104
0
    }
9105
0
  }
9106
9107
  // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9108
  //   If a constexpr-compatible function is explicitly defaulted on its first
9109
  //   declaration, it is implicitly considered to be constexpr.
9110
  // FIXME: Only applying this to the first declaration seems problematic, as
9111
  // simple reorderings can affect the meaning of the program.
9112
0
  if (First && !FD->isConstexpr() && Info.Constexpr)
9113
0
    FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9114
9115
  // C++2a [except.spec]p3:
9116
  //   If a declaration of a function does not have a noexcept-specifier
9117
  //   [and] is defaulted on its first declaration, [...] the exception
9118
  //   specification is as specified below
9119
0
  if (FD->getExceptionSpecType() == EST_None) {
9120
0
    auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9121
0
    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9122
0
    EPI.ExceptionSpec.Type = EST_Unevaluated;
9123
0
    EPI.ExceptionSpec.SourceDecl = FD;
9124
0
    FD->setType(Context.getFunctionType(FPT->getReturnType(),
9125
0
                                        FPT->getParamTypes(), EPI));
9126
0
  }
9127
9128
0
  return false;
9129
0
}
9130
9131
void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9132
0
                                             FunctionDecl *Spaceship) {
9133
0
  Sema::CodeSynthesisContext Ctx;
9134
0
  Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9135
0
  Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9136
0
  Ctx.Entity = Spaceship;
9137
0
  pushCodeSynthesisContext(Ctx);
9138
9139
0
  if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9140
0
    EqualEqual->setImplicit();
9141
9142
0
  popCodeSynthesisContext();
9143
0
}
9144
9145
void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9146
0
                                     DefaultedComparisonKind DCK) {
9147
0
  assert(FD->isDefaulted() && !FD->isDeleted() &&
9148
0
         !FD->doesThisDeclarationHaveABody());
9149
0
  if (FD->willHaveBody() || FD->isInvalidDecl())
9150
0
    return;
9151
9152
0
  SynthesizedFunctionScope Scope(*this, FD);
9153
9154
  // Add a context note for diagnostics produced after this point.
9155
0
  Scope.addContextNote(UseLoc);
9156
9157
0
  {
9158
    // Build and set up the function body.
9159
    // The first parameter has type maybe-ref-to maybe-const T, use that to get
9160
    // the type of the class being compared.
9161
0
    auto PT = FD->getParamDecl(0)->getType();
9162
0
    CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9163
0
    SourceLocation BodyLoc =
9164
0
        FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9165
0
    StmtResult Body =
9166
0
        DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9167
0
    if (Body.isInvalid()) {
9168
0
      FD->setInvalidDecl();
9169
0
      return;
9170
0
    }
9171
0
    FD->setBody(Body.get());
9172
0
    FD->markUsed(Context);
9173
0
  }
9174
9175
  // The exception specification is needed because we are defining the
9176
  // function. Note that this will reuse the body we just built.
9177
0
  ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
9178
9179
0
  if (ASTMutationListener *L = getASTMutationListener())
9180
0
    L->CompletedImplicitDefinition(FD);
9181
0
}
9182
9183
static Sema::ImplicitExceptionSpecification
9184
ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9185
                                        FunctionDecl *FD,
9186
0
                                        Sema::DefaultedComparisonKind DCK) {
9187
0
  ComputingExceptionSpec CES(S, FD, Loc);
9188
0
  Sema::ImplicitExceptionSpecification ExceptSpec(S);
9189
9190
0
  if (FD->isInvalidDecl())
9191
0
    return ExceptSpec;
9192
9193
  // The common case is that we just defined the comparison function. In that
9194
  // case, just look at whether the body can throw.
9195
0
  if (FD->hasBody()) {
9196
0
    ExceptSpec.CalledStmt(FD->getBody());
9197
0
  } else {
9198
    // Otherwise, build a body so we can check it. This should ideally only
9199
    // happen when we're not actually marking the function referenced. (This is
9200
    // only really important for efficiency: we don't want to build and throw
9201
    // away bodies for comparison functions more than we strictly need to.)
9202
9203
    // Pretend to synthesize the function body in an unevaluated context.
9204
    // Note that we can't actually just go ahead and define the function here:
9205
    // we are not permitted to mark its callees as referenced.
9206
0
    Sema::SynthesizedFunctionScope Scope(S, FD);
9207
0
    EnterExpressionEvaluationContext Context(
9208
0
        S, Sema::ExpressionEvaluationContext::Unevaluated);
9209
9210
0
    CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
9211
0
    SourceLocation BodyLoc =
9212
0
        FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9213
0
    StmtResult Body =
9214
0
        DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9215
0
    if (!Body.isInvalid())
9216
0
      ExceptSpec.CalledStmt(Body.get());
9217
9218
    // FIXME: Can we hold onto this body and just transform it to potentially
9219
    // evaluated when we're asked to define the function rather than rebuilding
9220
    // it? Either that, or we should only build the bits of the body that we
9221
    // need (the expressions, not the statements).
9222
0
  }
9223
9224
0
  return ExceptSpec;
9225
0
}
9226
9227
46
void Sema::CheckDelayedMemberExceptionSpecs() {
9228
46
  decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9229
46
  decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9230
9231
46
  std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
9232
46
  std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
9233
9234
  // Perform any deferred checking of exception specifications for virtual
9235
  // destructors.
9236
46
  for (auto &Check : Overriding)
9237
0
    CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
9238
9239
  // Perform any deferred checking of exception specifications for befriended
9240
  // special members.
9241
46
  for (auto &Check : Equivalent)
9242
0
    CheckEquivalentExceptionSpec(Check.second, Check.first);
9243
46
}
9244
9245
namespace {
9246
/// CRTP base class for visiting operations performed by a special member
9247
/// function (or inherited constructor).
9248
template<typename Derived>
9249
struct SpecialMemberVisitor {
9250
  Sema &S;
9251
  CXXMethodDecl *MD;
9252
  Sema::CXXSpecialMember CSM;
9253
  Sema::InheritedConstructorInfo *ICI;
9254
9255
  // Properties of the special member, computed for convenience.
9256
  bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9257
9258
  SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
9259
                       Sema::InheritedConstructorInfo *ICI)
9260
0
      : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9261
0
    switch (CSM) {
9262
0
    case Sema::CXXDefaultConstructor:
9263
0
    case Sema::CXXCopyConstructor:
9264
0
    case Sema::CXXMoveConstructor:
9265
0
      IsConstructor = true;
9266
0
      break;
9267
0
    case Sema::CXXCopyAssignment:
9268
0
    case Sema::CXXMoveAssignment:
9269
0
      IsAssignment = true;
9270
0
      break;
9271
0
    case Sema::CXXDestructor:
9272
0
      break;
9273
0
    case Sema::CXXInvalid:
9274
0
      llvm_unreachable("invalid special member kind");
9275
0
    }
9276
9277
0
    if (MD->getNumExplicitParams()) {
9278
0
      if (const ReferenceType *RT =
9279
0
              MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>())
9280
0
        ConstArg = RT->getPointeeType().isConstQualified();
9281
0
    }
9282
0
  }
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::SpecialMemberVisitor<(anonymous namespace)::SpecialMemberExceptionSpecInfo>::SpecialMemberVisitor(clang::Sema&, clang::CXXMethodDecl*, clang::Sema::CXXSpecialMember, clang::Sema::InheritedConstructorInfo*)
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::SpecialMemberVisitor<(anonymous namespace)::SpecialMemberDeletionInfo>::SpecialMemberVisitor(clang::Sema&, clang::CXXMethodDecl*, clang::Sema::CXXSpecialMember, clang::Sema::InheritedConstructorInfo*)
9283
9284
0
  Derived &getDerived() { return static_cast<Derived&>(*this); }
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::SpecialMemberVisitor<(anonymous namespace)::SpecialMemberExceptionSpecInfo>::getDerived()
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::SpecialMemberVisitor<(anonymous namespace)::SpecialMemberDeletionInfo>::getDerived()
9285
9286
  /// Is this a "move" special member?
9287
0
  bool isMove() const {
9288
0
    return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
9289
0
  }
9290
9291
  /// Look up the corresponding special member in the given class.
9292
  Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9293
0
                                             unsigned Quals, bool IsMutable) {
9294
0
    return lookupCallFromSpecialMember(S, Class, CSM, Quals,
9295
0
                                       ConstArg && !IsMutable);
9296
0
  }
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::SpecialMemberVisitor<(anonymous namespace)::SpecialMemberExceptionSpecInfo>::lookupIn(clang::CXXRecordDecl*, unsigned int, bool)
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::SpecialMemberVisitor<(anonymous namespace)::SpecialMemberDeletionInfo>::lookupIn(clang::CXXRecordDecl*, unsigned int, bool)
9297
9298
  /// Look up the constructor for the specified base class to see if it's
9299
  /// overridden due to this being an inherited constructor.
9300
0
  Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9301
0
    if (!ICI)
9302
0
      return {};
9303
0
    assert(CSM == Sema::CXXDefaultConstructor);
9304
0
    auto *BaseCtor =
9305
0
      cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9306
0
    if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9307
0
      return MD;
9308
0
    return {};
9309
0
  }
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::SpecialMemberVisitor<(anonymous namespace)::SpecialMemberExceptionSpecInfo>::lookupInheritedCtor(clang::CXXRecordDecl*)
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::SpecialMemberVisitor<(anonymous namespace)::SpecialMemberDeletionInfo>::lookupInheritedCtor(clang::CXXRecordDecl*)
9310
9311
  /// A base or member subobject.
9312
  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9313
9314
  /// Get the location to use for a subobject in diagnostics.
9315
0
  static SourceLocation getSubobjectLoc(Subobject Subobj) {
9316
    // FIXME: For an indirect virtual base, the direct base leading to
9317
    // the indirect virtual base would be a more useful choice.
9318
0
    if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
9319
0
      return B->getBaseTypeLoc();
9320
0
    else
9321
0
      return Subobj.get<FieldDecl*>()->getLocation();
9322
0
  }
9323
9324
  enum BasesToVisit {
9325
    /// Visit all non-virtual (direct) bases.
9326
    VisitNonVirtualBases,
9327
    /// Visit all direct bases, virtual or not.
9328
    VisitDirectBases,
9329
    /// Visit all non-virtual bases, and all virtual bases if the class
9330
    /// is not abstract.
9331
    VisitPotentiallyConstructedBases,
9332
    /// Visit all direct or virtual bases.
9333
    VisitAllBases
9334
  };
9335
9336
  // Visit the bases and members of the class.
9337
0
  bool visit(BasesToVisit Bases) {
9338
0
    CXXRecordDecl *RD = MD->getParent();
9339
9340
0
    if (Bases == VisitPotentiallyConstructedBases)
9341
0
      Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9342
9343
0
    for (auto &B : RD->bases())
9344
0
      if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9345
0
          getDerived().visitBase(&B))
9346
0
        return true;
9347
9348
0
    if (Bases == VisitAllBases)
9349
0
      for (auto &B : RD->vbases())
9350
0
        if (getDerived().visitBase(&B))
9351
0
          return true;
9352
9353
0
    for (auto *F : RD->fields())
9354
0
      if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
9355
0
          getDerived().visitField(F))
9356
0
        return true;
9357
9358
0
    return false;
9359
0
  }
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::SpecialMemberVisitor<(anonymous namespace)::SpecialMemberExceptionSpecInfo>::visit((anonymous namespace)::SpecialMemberVisitor<(anonymous namespace)::SpecialMemberExceptionSpecInfo>::BasesToVisit)
Unexecuted instantiation: SemaDeclCXX.cpp:(anonymous namespace)::SpecialMemberVisitor<(anonymous namespace)::SpecialMemberDeletionInfo>::visit((anonymous namespace)::SpecialMemberVisitor<(anonymous namespace)::SpecialMemberDeletionInfo>::BasesToVisit)
9360
};
9361
}
9362
9363
namespace {
9364
struct SpecialMemberDeletionInfo
9365
    : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9366
  bool Diagnose;
9367
9368
  SourceLocation Loc;
9369
9370
  bool AllFieldsAreConst;
9371
9372
  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9373
                            Sema::CXXSpecialMember CSM,
9374
                            Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9375
      : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9376
0
        Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9377
9378
0
  bool inUnion() const { return MD->getParent()->isUnion(); }
9379
9380
0
  Sema::CXXSpecialMember getEffectiveCSM() {
9381
0
    return ICI ? Sema::CXXInvalid : CSM;
9382
0
  }
9383
9384
  bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9385
9386
0
  bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9387
0
  bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9388
9389
  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9390
  bool shouldDeleteForField(FieldDecl *FD);
9391
  bool shouldDeleteForAllConstMembers();
9392
9393
  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9394
                                     unsigned Quals);
9395
  bool shouldDeleteForSubobjectCall(Subobject Subobj,
9396
                                    Sema::SpecialMemberOverloadResult SMOR,
9397
                                    bool IsDtorCallInCtor);
9398
9399
  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9400
};
9401
}
9402
9403
/// Is the given special member inaccessible when used on the given
9404
/// sub-object.
9405
bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9406
0
                                             CXXMethodDecl *target) {
9407
  /// If we're operating on a base class, the object type is the
9408
  /// type of this special member.
9409
0
  QualType objectTy;
9410
0
  AccessSpecifier access = target->getAccess();
9411
0
  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9412
0
    objectTy = S.Context.getTypeDeclType(MD->getParent());
9413
0
    access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9414
9415
  // If we're operating on a field, the object type is the type of the field.
9416
0
  } else {
9417
0
    objectTy = S.Context.getTypeDeclType(target->getParent());
9418
0
  }
9419
9420
0
  return S.isMemberAccessibleForDeletion(
9421
0
      target->getParent(), DeclAccessPair::make(target, access), objectTy);
9422
0
}
9423
9424
/// Check whether we should delete a special member due to the implicit
9425
/// definition containing a call to a special member of a subobject.
9426
bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9427
    Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9428
0
    bool IsDtorCallInCtor) {
9429
0
  CXXMethodDecl *Decl = SMOR.getMethod();
9430
0
  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9431
9432
0
  int DiagKind = -1;
9433
9434
0
  if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9435
0
    DiagKind = !Decl ? 0 : 1;
9436
0
  else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9437
0
    DiagKind = 2;
9438
0
  else if (!isAccessible(Subobj, Decl))
9439
0
    DiagKind = 3;
9440
0
  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9441
0
           !Decl->isTrivial()) {
9442
    // A member of a union must have a trivial corresponding special member.
9443
    // As a weird special case, a destructor call from a union's constructor
9444
    // must be accessible and non-deleted, but need not be trivial. Such a
9445
    // destructor is never actually called, but is semantically checked as
9446
    // if it were.
9447
0
    if (CSM == Sema::CXXDefaultConstructor) {
9448
      // [class.default.ctor]p2:
9449
      //   A defaulted default constructor for class X is defined as deleted if
9450
      //   - X is a union that has a variant member with a non-trivial default
9451
      //     constructor and no variant member of X has a default member
9452
      //     initializer
9453
0
      const auto *RD = cast<CXXRecordDecl>(Field->getParent());
9454
0
      if (!RD->hasInClassInitializer())
9455
0
        DiagKind = 4;
9456
0
    } else {
9457
0
      DiagKind = 4;
9458
0
    }
9459
0
  }
9460
9461
0
  if (DiagKind == -1)
9462
0
    return false;
9463
9464
0
  if (Diagnose) {
9465
0
    if (Field) {
9466
0
      S.Diag(Field->getLocation(),
9467
0
             diag::note_deleted_special_member_class_subobject)
9468
0
        << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9469
0
        << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9470
0
    } else {
9471
0
      CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9472
0
      S.Diag(Base->getBeginLoc(),
9473
0
             diag::note_deleted_special_member_class_subobject)
9474
0
          << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9475
0
          << Base->getType() << DiagKind << IsDtorCallInCtor
9476
0
          << /*IsObjCPtr*/false;
9477
0
    }
9478
9479
0
    if (DiagKind == 1)
9480
0
      S.NoteDeletedFunction(Decl);
9481
    // FIXME: Explain inaccessibility if DiagKind == 3.
9482
0
  }
9483
9484
0
  return true;
9485
0
}
9486
9487
/// Check whether we should delete a special member function due to having a
9488
/// direct or virtual base class or non-static data member of class type M.
9489
bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9490
0
    CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9491
0
  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9492
0
  bool IsMutable = Field && Field->isMutable();
9493
9494
  // C++11 [class.ctor]p5:
9495
  // -- any direct or virtual base class, or non-static data member with no
9496
  //    brace-or-equal-initializer, has class type M (or array thereof) and
9497
  //    either M has no default constructor or overload resolution as applied
9498
  //    to M's default constructor results in an ambiguity or in a function
9499
  //    that is deleted or inaccessible
9500
  // C++11 [class.copy]p11, C++11 [class.copy]p23:
9501
  // -- a direct or virtual base class B that cannot be copied/moved because
9502
  //    overload resolution, as applied to B's corresponding special member,
9503
  //    results in an ambiguity or a function that is deleted or inaccessible
9504
  //    from the defaulted special member
9505
  // C++11 [class.dtor]p5:
9506
  // -- any direct or virtual base class [...] has a type with a destructor
9507
  //    that is deleted or inaccessible
9508
0
  if (!(CSM == Sema::CXXDefaultConstructor &&
9509
0
        Field && Field->hasInClassInitializer()) &&
9510
0
      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9511
0
                                   false))
9512
0
    return true;
9513
9514
  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9515
  // -- any direct or virtual base class or non-static data member has a
9516
  //    type with a destructor that is deleted or inaccessible
9517
0
  if (IsConstructor) {
9518
0
    Sema::SpecialMemberOverloadResult SMOR =
9519
0
        S.LookupSpecialMember(Class, Sema::CXXDestructor,
9520
0
                              false, false, false, false, false);
9521
0
    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9522
0
      return true;
9523
0
  }
9524
9525
0
  return false;
9526
0
}
9527
9528
bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9529
0
    FieldDecl *FD, QualType FieldType) {
9530
  // The defaulted special functions are defined as deleted if this is a variant
9531
  // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9532
  // type under ARC.
9533
0
  if (!FieldType.hasNonTrivialObjCLifetime())
9534
0
    return false;
9535
9536
  // Don't make the defaulted default constructor defined as deleted if the
9537
  // member has an in-class initializer.
9538
0
  if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9539
0
    return false;
9540
9541
0
  if (Diagnose) {
9542
0
    auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9543
0
    S.Diag(FD->getLocation(),
9544
0
           diag::note_deleted_special_member_class_subobject)
9545
0
        << getEffectiveCSM() << ParentClass << /*IsField*/true
9546
0
        << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9547
0
  }
9548
9549
0
  return true;
9550
0
}
9551
9552
/// Check whether we should delete a special member function due to the class
9553
/// having a particular direct or virtual base class.
9554
0
bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9555
0
  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9556
  // If program is correct, BaseClass cannot be null, but if it is, the error
9557
  // must be reported elsewhere.
9558
0
  if (!BaseClass)
9559
0
    return false;
9560
  // If we have an inheriting constructor, check whether we're calling an
9561
  // inherited constructor instead of a default constructor.
9562
0
  Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9563
0
  if (auto *BaseCtor = SMOR.getMethod()) {
9564
    // Note that we do not check access along this path; other than that,
9565
    // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9566
    // FIXME: Check that the base has a usable destructor! Sink this into
9567
    // shouldDeleteForClassSubobject.
9568
0
    if (BaseCtor->isDeleted() && Diagnose) {
9569
0
      S.Diag(Base->getBeginLoc(),
9570
0
             diag::note_deleted_special_member_class_subobject)
9571
0
          << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9572
0
          << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9573
0
          << /*IsObjCPtr*/false;
9574
0
      S.NoteDeletedFunction(BaseCtor);
9575
0
    }
9576
0
    return BaseCtor->isDeleted();
9577
0
  }
9578
0
  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9579
0
}
9580
9581
/// Check whether we should delete a special member function due to the class
9582
/// having a particular non-static data member.
9583
0
bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9584
0
  QualType FieldType = S.Context.getBaseElementType(FD->getType());
9585
0
  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9586
9587
0
  if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9588
0
    return true;
9589
9590
0
  if (CSM == Sema::CXXDefaultConstructor) {
9591
    // For a default constructor, all references must be initialized in-class
9592
    // and, if a union, it must have a non-const member.
9593
0
    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9594
0
      if (Diagnose)
9595
0
        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9596
0
          << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9597
0
      return true;
9598
0
    }
9599
    // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9600
    // data member of const-qualified type (or array thereof) with no
9601
    // brace-or-equal-initializer is not const-default-constructible.
9602
0
    if (!inUnion() && FieldType.isConstQualified() &&
9603
0
        !FD->hasInClassInitializer() &&
9604
0
        (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9605
0
      if (Diagnose)
9606
0
        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9607
0
          << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9608
0
      return true;
9609
0
    }
9610
9611
0
    if (inUnion() && !FieldType.isConstQualified())
9612
0
      AllFieldsAreConst = false;
9613
0
  } else if (CSM == Sema::CXXCopyConstructor) {
9614
    // For a copy constructor, data members must not be of rvalue reference
9615
    // type.
9616
0
    if (FieldType->isRValueReferenceType()) {
9617
0
      if (Diagnose)
9618
0
        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9619
0
          << MD->getParent() << FD << FieldType;
9620
0
      return true;
9621
0
    }
9622
0
  } else if (IsAssignment) {
9623
    // For an assignment operator, data members must not be of reference type.
9624
0
    if (FieldType->isReferenceType()) {
9625
0
      if (Diagnose)
9626
0
        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9627
0
          << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9628
0
      return true;
9629
0
    }
9630
0
    if (!FieldRecord && FieldType.isConstQualified()) {
9631
      // C++11 [class.copy]p23:
9632
      // -- a non-static data member of const non-class type (or array thereof)
9633
0
      if (Diagnose)
9634
0
        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9635
0
          << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9636
0
      return true;
9637
0
    }
9638
0
  }
9639
9640
0
  if (FieldRecord) {
9641
    // Some additional restrictions exist on the variant members.
9642
0
    if (!inUnion() && FieldRecord->isUnion() &&
9643
0
        FieldRecord->isAnonymousStructOrUnion()) {
9644
0
      bool AllVariantFieldsAreConst = true;
9645
9646
      // FIXME: Handle anonymous unions declared within anonymous unions.
9647
0
      for (auto *UI : FieldRecord->fields()) {
9648
0
        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9649
9650
0
        if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9651
0
          return true;
9652
9653
0
        if (!UnionFieldType.isConstQualified())
9654
0
          AllVariantFieldsAreConst = false;
9655
9656
0
        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9657
0
        if (UnionFieldRecord &&
9658
0
            shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9659
0
                                          UnionFieldType.getCVRQualifiers()))
9660
0
          return true;
9661
0
      }
9662
9663
      // At least one member in each anonymous union must be non-const
9664
0
      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9665
0
          !FieldRecord->field_empty()) {
9666
0
        if (Diagnose)
9667
0
          S.Diag(FieldRecord->getLocation(),
9668
0
                 diag::note_deleted_default_ctor_all_const)
9669
0
            << !!ICI << MD->getParent() << /*anonymous union*/1;
9670
0
        return true;
9671
0
      }
9672
9673
      // Don't check the implicit member of the anonymous union type.
9674
      // This is technically non-conformant but supported, and we have a
9675
      // diagnostic for this elsewhere.
9676
0
      return false;
9677
0
    }
9678
9679
0
    if (shouldDeleteForClassSubobject(FieldRecord, FD,
9680
0
                                      FieldType.getCVRQualifiers()))
9681
0
      return true;
9682
0
  }
9683
9684
0
  return false;
9685
0
}
9686
9687
/// C++11 [class.ctor] p5:
9688
///   A defaulted default constructor for a class X is defined as deleted if
9689
/// X is a union and all of its variant members are of const-qualified type.
9690
0
bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9691
  // This is a silly definition, because it gives an empty union a deleted
9692
  // default constructor. Don't do that.
9693
0
  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9694
0
    bool AnyFields = false;
9695
0
    for (auto *F : MD->getParent()->fields())
9696
0
      if ((AnyFields = !F->isUnnamedBitfield()))
9697
0
        break;
9698
0
    if (!AnyFields)
9699
0
      return false;
9700
0
    if (Diagnose)
9701
0
      S.Diag(MD->getParent()->getLocation(),
9702
0
             diag::note_deleted_default_ctor_all_const)
9703
0
        << !!ICI << MD->getParent() << /*not anonymous union*/0;
9704
0
    return true;
9705
0
  }
9706
0
  return false;
9707
0
}
9708
9709
/// Determine whether a defaulted special member function should be defined as
9710
/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9711
/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9712
bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9713
                                     InheritedConstructorInfo *ICI,
9714
0
                                     bool Diagnose) {
9715
0
  if (MD->isInvalidDecl())
9716
0
    return false;
9717
0
  CXXRecordDecl *RD = MD->getParent();
9718
0
  assert(!RD->isDependentType() && "do deletion after instantiation");
9719
0
  if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9720
0
    return false;
9721
9722
  // C++11 [expr.lambda.prim]p19:
9723
  //   The closure type associated with a lambda-expression has a
9724
  //   deleted (8.4.3) default constructor and a deleted copy
9725
  //   assignment operator.
9726
  // C++2a adds back these operators if the lambda has no lambda-capture.
9727
0
  if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9728
0
      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9729
0
    if (Diagnose)
9730
0
      Diag(RD->getLocation(), diag::note_lambda_decl);
9731
0
    return true;
9732
0
  }
9733
9734
  // For an anonymous struct or union, the copy and assignment special members
9735
  // will never be used, so skip the check. For an anonymous union declared at
9736
  // namespace scope, the constructor and destructor are used.
9737
0
  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9738
0
      RD->isAnonymousStructOrUnion())
9739
0
    return false;
9740
9741
  // C++11 [class.copy]p7, p18:
9742
  //   If the class definition declares a move constructor or move assignment
9743
  //   operator, an implicitly declared copy constructor or copy assignment
9744
  //   operator is defined as deleted.
9745
0
  if (MD->isImplicit() &&
9746
0
      (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9747
0
    CXXMethodDecl *UserDeclaredMove = nullptr;
9748
9749
    // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9750
    // deletion of the corresponding copy operation, not both copy operations.
9751
    // MSVC 2015 has adopted the standards conforming behavior.
9752
0
    bool DeletesOnlyMatchingCopy =
9753
0
        getLangOpts().MSVCCompat &&
9754
0
        !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9755
9756
0
    if (RD->hasUserDeclaredMoveConstructor() &&
9757
0
        (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9758
0
      if (!Diagnose) return true;
9759
9760
      // Find any user-declared move constructor.
9761
0
      for (auto *I : RD->ctors()) {
9762
0
        if (I->isMoveConstructor()) {
9763
0
          UserDeclaredMove = I;
9764
0
          break;
9765
0
        }
9766
0
      }
9767
0
      assert(UserDeclaredMove);
9768
0
    } else if (RD->hasUserDeclaredMoveAssignment() &&
9769
0
               (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9770
0
      if (!Diagnose) return true;
9771
9772
      // Find any user-declared move assignment operator.
9773
0
      for (auto *I : RD->methods()) {
9774
0
        if (I->isMoveAssignmentOperator()) {
9775
0
          UserDeclaredMove = I;
9776
0
          break;
9777
0
        }
9778
0
      }
9779
0
      assert(UserDeclaredMove);
9780
0
    }
9781
9782
0
    if (UserDeclaredMove) {
9783
0
      Diag(UserDeclaredMove->getLocation(),
9784
0
           diag::note_deleted_copy_user_declared_move)
9785
0
        << (CSM == CXXCopyAssignment) << RD
9786
0
        << UserDeclaredMove->isMoveAssignmentOperator();
9787
0
      return true;
9788
0
    }
9789
0
  }
9790
9791
  // Do access control from the special member function
9792
0
  ContextRAII MethodContext(*this, MD);
9793
9794
  // C++11 [class.dtor]p5:
9795
  // -- for a virtual destructor, lookup of the non-array deallocation function
9796
  //    results in an ambiguity or in a function that is deleted or inaccessible
9797
0
  if (CSM == CXXDestructor && MD->isVirtual()) {
9798
0
    FunctionDecl *OperatorDelete = nullptr;
9799
0
    DeclarationName Name =
9800
0
      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9801
0
    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9802
0
                                 OperatorDelete, /*Diagnose*/false)) {
9803
0
      if (Diagnose)
9804
0
        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9805
0
      return true;
9806
0
    }
9807
0
  }
9808
9809
0
  SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9810
9811
  // Per DR1611, do not consider virtual bases of constructors of abstract
9812
  // classes, since we are not going to construct them.
9813
  // Per DR1658, do not consider virtual bases of destructors of abstract
9814
  // classes either.
9815
  // Per DR2180, for assignment operators we only assign (and thus only
9816
  // consider) direct bases.
9817
0
  if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9818
0
                                 : SMI.VisitPotentiallyConstructedBases))
9819
0
    return true;
9820
9821
0
  if (SMI.shouldDeleteForAllConstMembers())
9822
0
    return true;
9823
9824
0
  if (getLangOpts().CUDA) {
9825
    // We should delete the special member in CUDA mode if target inference
9826
    // failed.
9827
    // For inherited constructors (non-null ICI), CSM may be passed so that MD
9828
    // is treated as certain special member, which may not reflect what special
9829
    // member MD really is. However inferCUDATargetForImplicitSpecialMember
9830
    // expects CSM to match MD, therefore recalculate CSM.
9831
0
    assert(ICI || CSM == getSpecialMember(MD));
9832
0
    auto RealCSM = CSM;
9833
0
    if (ICI)
9834
0
      RealCSM = getSpecialMember(MD);
9835
9836
0
    return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9837
0
                                                   SMI.ConstArg, Diagnose);
9838
0
  }
9839
9840
0
  return false;
9841
0
}
9842
9843
0
void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9844
0
  DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9845
0
  assert(DFK && "not a defaultable function");
9846
0
  assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9847
9848
0
  if (DFK.isSpecialMember()) {
9849
0
    ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9850
0
                              nullptr, /*Diagnose=*/true);
9851
0
  } else {
9852
0
    DefaultedComparisonAnalyzer(
9853
0
        *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9854
0
        DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9855
0
        .visit();
9856
0
  }
9857
0
}
9858
9859
/// Perform lookup for a special member of the specified kind, and determine
9860
/// whether it is trivial. If the triviality can be determined without the
9861
/// lookup, skip it. This is intended for use when determining whether a
9862
/// special member of a containing object is trivial, and thus does not ever
9863
/// perform overload resolution for default constructors.
9864
///
9865
/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9866
/// member that was most likely to be intended to be trivial, if any.
9867
///
9868
/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9869
/// determine whether the special member is trivial.
9870
static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9871
                                     Sema::CXXSpecialMember CSM, unsigned Quals,
9872
                                     bool ConstRHS,
9873
                                     Sema::TrivialABIHandling TAH,
9874
0
                                     CXXMethodDecl **Selected) {
9875
0
  if (Selected)
9876
0
    *Selected = nullptr;
9877
9878
0
  switch (CSM) {
9879
0
  case Sema::CXXInvalid:
9880
0
    llvm_unreachable("not a special member");
9881
9882
0
  case Sema::CXXDefaultConstructor:
9883
    // C++11 [class.ctor]p5:
9884
    //   A default constructor is trivial if:
9885
    //    - all the [direct subobjects] have trivial default constructors
9886
    //
9887
    // Note, no overload resolution is performed in this case.
9888
0
    if (RD->hasTrivialDefaultConstructor())
9889
0
      return true;
9890
9891
0
    if (Selected) {
9892
      // If there's a default constructor which could have been trivial, dig it
9893
      // out. Otherwise, if there's any user-provided default constructor, point
9894
      // to that as an example of why there's not a trivial one.
9895
0
      CXXConstructorDecl *DefCtor = nullptr;
9896
0
      if (RD->needsImplicitDefaultConstructor())
9897
0
        S.DeclareImplicitDefaultConstructor(RD);
9898
0
      for (auto *CI : RD->ctors()) {
9899
0
        if (!CI->isDefaultConstructor())
9900
0
          continue;
9901
0
        DefCtor = CI;
9902
0
        if (!DefCtor->isUserProvided())
9903
0
          break;
9904
0
      }
9905
9906
0
      *Selected = DefCtor;
9907
0
    }
9908
9909
0
    return false;
9910
9911
0
  case Sema::CXXDestructor:
9912
    // C++11 [class.dtor]p5:
9913
    //   A destructor is trivial if:
9914
    //    - all the direct [subobjects] have trivial destructors
9915
0
    if (RD->hasTrivialDestructor() ||
9916
0
        (TAH == Sema::TAH_ConsiderTrivialABI &&
9917
0
         RD->hasTrivialDestructorForCall()))
9918
0
      return true;
9919
9920
0
    if (Selected) {
9921
0
      if (RD->needsImplicitDestructor())
9922
0
        S.DeclareImplicitDestructor(RD);
9923
0
      *Selected = RD->getDestructor();
9924
0
    }
9925
9926
0
    return false;
9927
9928
0
  case Sema::CXXCopyConstructor:
9929
    // C++11 [class.copy]p12:
9930
    //   A copy constructor is trivial if:
9931
    //    - the constructor selected to copy each direct [subobject] is trivial
9932
0
    if (RD->hasTrivialCopyConstructor() ||
9933
0
        (TAH == Sema::TAH_ConsiderTrivialABI &&
9934
0
         RD->hasTrivialCopyConstructorForCall())) {
9935
0
      if (Quals == Qualifiers::Const)
9936
        // We must either select the trivial copy constructor or reach an
9937
        // ambiguity; no need to actually perform overload resolution.
9938
0
        return true;
9939
0
    } else if (!Selected) {
9940
0
      return false;
9941
0
    }
9942
    // In C++98, we are not supposed to perform overload resolution here, but we
9943
    // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9944
    // cases like B as having a non-trivial copy constructor:
9945
    //   struct A { template<typename T> A(T&); };
9946
    //   struct B { mutable A a; };
9947
0
    goto NeedOverloadResolution;
9948
9949
0
  case Sema::CXXCopyAssignment:
9950
    // C++11 [class.copy]p25:
9951
    //   A copy assignment operator is trivial if:
9952
    //    - the assignment operator selected to copy each direct [subobject] is
9953
    //      trivial
9954
0
    if (RD->hasTrivialCopyAssignment()) {
9955
0
      if (Quals == Qualifiers::Const)
9956
0
        return true;
9957
0
    } else if (!Selected) {
9958
0
      return false;
9959
0
    }
9960
    // In C++98, we are not supposed to perform overload resolution here, but we
9961
    // treat that as a language defect.
9962
0
    goto NeedOverloadResolution;
9963
9964
0
  case Sema::CXXMoveConstructor:
9965
0
  case Sema::CXXMoveAssignment:
9966
0
  NeedOverloadResolution:
9967
0
    Sema::SpecialMemberOverloadResult SMOR =
9968
0
        lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9969
9970
    // The standard doesn't describe how to behave if the lookup is ambiguous.
9971
    // We treat it as not making the member non-trivial, just like the standard
9972
    // mandates for the default constructor. This should rarely matter, because
9973
    // the member will also be deleted.
9974
0
    if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9975
0
      return true;
9976
9977
0
    if (!SMOR.getMethod()) {
9978
0
      assert(SMOR.getKind() ==
9979
0
             Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9980
0
      return false;
9981
0
    }
9982
9983
    // We deliberately don't check if we found a deleted special member. We're
9984
    // not supposed to!
9985
0
    if (Selected)
9986
0
      *Selected = SMOR.getMethod();
9987
9988
0
    if (TAH == Sema::TAH_ConsiderTrivialABI &&
9989
0
        (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9990
0
      return SMOR.getMethod()->isTrivialForCall();
9991
0
    return SMOR.getMethod()->isTrivial();
9992
0
  }
9993
9994
0
  llvm_unreachable("unknown special method kind");
9995
0
}
9996
9997
0
static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9998
0
  for (auto *CI : RD->ctors())
9999
0
    if (!CI->isImplicit())
10000
0
      return CI;
10001
10002
  // Look for constructor templates.
10003
0
  typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
10004
0
  for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10005
0
    if (CXXConstructorDecl *CD =
10006
0
          dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
10007
0
      return CD;
10008
0
  }
10009
10010
0
  return nullptr;
10011
0
}
10012
10013
/// The kind of subobject we are checking for triviality. The values of this
10014
/// enumeration are used in diagnostics.
10015
enum TrivialSubobjectKind {
10016
  /// The subobject is a base class.
10017
  TSK_BaseClass,
10018
  /// The subobject is a non-static data member.
10019
  TSK_Field,
10020
  /// The object is actually the complete object.
10021
  TSK_CompleteObject
10022
};
10023
10024
/// Check whether the special member selected for a given type would be trivial.
10025
static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
10026
                                      QualType SubType, bool ConstRHS,
10027
                                      Sema::CXXSpecialMember CSM,
10028
                                      TrivialSubobjectKind Kind,
10029
0
                                      Sema::TrivialABIHandling TAH, bool Diagnose) {
10030
0
  CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10031
0
  if (!SubRD)
10032
0
    return true;
10033
10034
0
  CXXMethodDecl *Selected;
10035
0
  if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
10036
0
                               ConstRHS, TAH, Diagnose ? &Selected : nullptr))
10037
0
    return true;
10038
10039
0
  if (Diagnose) {
10040
0
    if (ConstRHS)
10041
0
      SubType.addConst();
10042
10043
0
    if (!Selected && CSM == Sema::CXXDefaultConstructor) {
10044
0
      S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
10045
0
        << Kind << SubType.getUnqualifiedType();
10046
0
      if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
10047
0
        S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
10048
0
    } else if (!Selected)
10049
0
      S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
10050
0
        << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10051
0
    else if (Selected->isUserProvided()) {
10052
0
      if (Kind == TSK_CompleteObject)
10053
0
        S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
10054
0
          << Kind << SubType.getUnqualifiedType() << CSM;
10055
0
      else {
10056
0
        S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
10057
0
          << Kind << SubType.getUnqualifiedType() << CSM;
10058
0
        S.Diag(Selected->getLocation(), diag::note_declared_at);
10059
0
      }
10060
0
    } else {
10061
0
      if (Kind != TSK_CompleteObject)
10062
0
        S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
10063
0
          << Kind << SubType.getUnqualifiedType() << CSM;
10064
10065
      // Explain why the defaulted or deleted special member isn't trivial.
10066
0
      S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
10067
0
                               Diagnose);
10068
0
    }
10069
0
  }
10070
10071
0
  return false;
10072
0
}
10073
10074
/// Check whether the members of a class type allow a special member to be
10075
/// trivial.
10076
static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
10077
                                     Sema::CXXSpecialMember CSM,
10078
                                     bool ConstArg,
10079
                                     Sema::TrivialABIHandling TAH,
10080
0
                                     bool Diagnose) {
10081
0
  for (const auto *FI : RD->fields()) {
10082
0
    if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
10083
0
      continue;
10084
10085
0
    QualType FieldType = S.Context.getBaseElementType(FI->getType());
10086
10087
    // Pretend anonymous struct or union members are members of this class.
10088
0
    if (FI->isAnonymousStructOrUnion()) {
10089
0
      if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
10090
0
                                    CSM, ConstArg, TAH, Diagnose))
10091
0
        return false;
10092
0
      continue;
10093
0
    }
10094
10095
    // C++11 [class.ctor]p5:
10096
    //   A default constructor is trivial if [...]
10097
    //    -- no non-static data member of its class has a
10098
    //       brace-or-equal-initializer
10099
0
    if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
10100
0
      if (Diagnose)
10101
0
        S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
10102
0
            << FI;
10103
0
      return false;
10104
0
    }
10105
10106
    // Objective C ARC 4.3.5:
10107
    //   [...] nontrivally ownership-qualified types are [...] not trivially
10108
    //   default constructible, copy constructible, move constructible, copy
10109
    //   assignable, move assignable, or destructible [...]
10110
0
    if (FieldType.hasNonTrivialObjCLifetime()) {
10111
0
      if (Diagnose)
10112
0
        S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
10113
0
          << RD << FieldType.getObjCLifetime();
10114
0
      return false;
10115
0
    }
10116
10117
0
    bool ConstRHS = ConstArg && !FI->isMutable();
10118
0
    if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
10119
0
                                   CSM, TSK_Field, TAH, Diagnose))
10120
0
      return false;
10121
0
  }
10122
10123
0
  return true;
10124
0
}
10125
10126
/// Diagnose why the specified class does not have a trivial special member of
10127
/// the given kind.
10128
0
void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
10129
0
  QualType Ty = Context.getRecordType(RD);
10130
10131
0
  bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
10132
0
  checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
10133
0
                            TSK_CompleteObject, TAH_IgnoreTrivialABI,
10134
0
                            /*Diagnose*/true);
10135
0
}
10136
10137
/// Determine whether a defaulted or deleted special member function is trivial,
10138
/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
10139
/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
10140
bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
10141
0
                                  TrivialABIHandling TAH, bool Diagnose) {
10142
0
  assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
10143
10144
0
  CXXRecordDecl *RD = MD->getParent();
10145
10146
0
  bool ConstArg = false;
10147
10148
  // C++11 [class.copy]p12, p25: [DR1593]
10149
  //   A [special member] is trivial if [...] its parameter-type-list is
10150
  //   equivalent to the parameter-type-list of an implicit declaration [...]
10151
0
  switch (CSM) {
10152
0
  case CXXDefaultConstructor:
10153
0
  case CXXDestructor:
10154
    // Trivial default constructors and destructors cannot have parameters.
10155
0
    break;
10156
10157
0
  case CXXCopyConstructor:
10158
0
  case CXXCopyAssignment: {
10159
0
    const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10160
0
    const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10161
10162
    // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10163
    // if they are not user-provided and their parameter-type-list is equivalent
10164
    // to the parameter-type-list of an implicit declaration. This maintains the
10165
    // behavior before dr2171 was implemented.
10166
    //
10167
    // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10168
    // trivial, if they are not user-provided, regardless of the qualifiers on
10169
    // the reference type.
10170
0
    const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10171
0
                                  LangOptions::ClangABI::Ver14;
10172
0
    if (!RT ||
10173
0
        ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10174
0
         ClangABICompat14)) {
10175
0
      if (Diagnose)
10176
0
        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10177
0
          << Param0->getSourceRange() << Param0->getType()
10178
0
          << Context.getLValueReferenceType(
10179
0
               Context.getRecordType(RD).withConst());
10180
0
      return false;
10181
0
    }
10182
10183
0
    ConstArg = RT->getPointeeType().isConstQualified();
10184
0
    break;
10185
0
  }
10186
10187
0
  case CXXMoveConstructor:
10188
0
  case CXXMoveAssignment: {
10189
    // Trivial move operations always have non-cv-qualified parameters.
10190
0
    const ParmVarDecl *Param0 = MD->getNonObjectParameter(0);
10191
0
    const RValueReferenceType *RT =
10192
0
      Param0->getType()->getAs<RValueReferenceType>();
10193
0
    if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10194
0
      if (Diagnose)
10195
0
        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
10196
0
          << Param0->getSourceRange() << Param0->getType()
10197
0
          << Context.getRValueReferenceType(Context.getRecordType(RD));
10198
0
      return false;
10199
0
    }
10200
0
    break;
10201
0
  }
10202
10203
0
  case CXXInvalid:
10204
0
    llvm_unreachable("not a special member");
10205
0
  }
10206
10207
0
  if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10208
0
    if (Diagnose)
10209
0
      Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
10210
0
           diag::note_nontrivial_default_arg)
10211
0
        << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
10212
0
    return false;
10213
0
  }
10214
0
  if (MD->isVariadic()) {
10215
0
    if (Diagnose)
10216
0
      Diag(MD->getLocation(), diag::note_nontrivial_variadic);
10217
0
    return false;
10218
0
  }
10219
10220
  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10221
  //   A copy/move [constructor or assignment operator] is trivial if
10222
  //    -- the [member] selected to copy/move each direct base class subobject
10223
  //       is trivial
10224
  //
10225
  // C++11 [class.copy]p12, C++11 [class.copy]p25:
10226
  //   A [default constructor or destructor] is trivial if
10227
  //    -- all the direct base classes have trivial [default constructors or
10228
  //       destructors]
10229
0
  for (const auto &BI : RD->bases())
10230
0
    if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
10231
0
                                   ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
10232
0
      return false;
10233
10234
  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10235
  //   A copy/move [constructor or assignment operator] for a class X is
10236
  //   trivial if
10237
  //    -- for each non-static data member of X that is of class type (or array
10238
  //       thereof), the constructor selected to copy/move that member is
10239
  //       trivial
10240
  //
10241
  // C++11 [class.copy]p12, C++11 [class.copy]p25:
10242
  //   A [default constructor or destructor] is trivial if
10243
  //    -- for all of the non-static data members of its class that are of class
10244
  //       type (or array thereof), each such class has a trivial [default
10245
  //       constructor or destructor]
10246
0
  if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
10247
0
    return false;
10248
10249
  // C++11 [class.dtor]p5:
10250
  //   A destructor is trivial if [...]
10251
  //    -- the destructor is not virtual
10252
0
  if (CSM == CXXDestructor && MD->isVirtual()) {
10253
0
    if (Diagnose)
10254
0
      Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
10255
0
    return false;
10256
0
  }
10257
10258
  // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10259
  //   A [special member] for class X is trivial if [...]
10260
  //    -- class X has no virtual functions and no virtual base classes
10261
0
  if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
10262
0
    if (!Diagnose)
10263
0
      return false;
10264
10265
0
    if (RD->getNumVBases()) {
10266
      // Check for virtual bases. We already know that the corresponding
10267
      // member in all bases is trivial, so vbases must all be direct.
10268
0
      CXXBaseSpecifier &BS = *RD->vbases_begin();
10269
0
      assert(BS.isVirtual());
10270
0
      Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
10271
0
      return false;
10272
0
    }
10273
10274
    // Must have a virtual method.
10275
0
    for (const auto *MI : RD->methods()) {
10276
0
      if (MI->isVirtual()) {
10277
0
        SourceLocation MLoc = MI->getBeginLoc();
10278
0
        Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
10279
0
        return false;
10280
0
      }
10281
0
    }
10282
10283
0
    llvm_unreachable("dynamic class with no vbases and no virtual functions");
10284
0
  }
10285
10286
  // Looks like it's trivial!
10287
0
  return true;
10288
0
}
10289
10290
namespace {
10291
struct FindHiddenVirtualMethod {
10292
  Sema *S;
10293
  CXXMethodDecl *Method;
10294
  llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10295
  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10296
10297
private:
10298
  /// Check whether any most overridden method from MD in Methods
10299
  static bool CheckMostOverridenMethods(
10300
      const CXXMethodDecl *MD,
10301
0
      const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10302
0
    if (MD->size_overridden_methods() == 0)
10303
0
      return Methods.count(MD->getCanonicalDecl());
10304
0
    for (const CXXMethodDecl *O : MD->overridden_methods())
10305
0
      if (CheckMostOverridenMethods(O, Methods))
10306
0
        return true;
10307
0
    return false;
10308
0
  }
10309
10310
public:
10311
  /// Member lookup function that determines whether a given C++
10312
  /// method overloads virtual methods in a base class without overriding any,
10313
  /// to be used with CXXRecordDecl::lookupInBases().
10314
0
  bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10315
0
    RecordDecl *BaseRecord =
10316
0
        Specifier->getType()->castAs<RecordType>()->getDecl();
10317
10318
0
    DeclarationName Name = Method->getDeclName();
10319
0
    assert(Name.getNameKind() == DeclarationName::Identifier);
10320
10321
0
    bool foundSameNameMethod = false;
10322
0
    SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10323
0
    for (Path.Decls = BaseRecord->lookup(Name).begin();
10324
0
         Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10325
0
      NamedDecl *D = *Path.Decls;
10326
0
      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10327
0
        MD = MD->getCanonicalDecl();
10328
0
        foundSameNameMethod = true;
10329
        // Interested only in hidden virtual methods.
10330
0
        if (!MD->isVirtual())
10331
0
          continue;
10332
        // If the method we are checking overrides a method from its base
10333
        // don't warn about the other overloaded methods. Clang deviates from
10334
        // GCC by only diagnosing overloads of inherited virtual functions that
10335
        // do not override any other virtual functions in the base. GCC's
10336
        // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10337
        // function from a base class. These cases may be better served by a
10338
        // warning (not specific to virtual functions) on call sites when the
10339
        // call would select a different function from the base class, were it
10340
        // visible.
10341
        // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10342
0
        if (!S->IsOverload(Method, MD, false))
10343
0
          return true;
10344
        // Collect the overload only if its hidden.
10345
0
        if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10346
0
          overloadedMethods.push_back(MD);
10347
0
      }
10348
0
    }
10349
10350
0
    if (foundSameNameMethod)
10351
0
      OverloadedMethods.append(overloadedMethods.begin(),
10352
0
                               overloadedMethods.end());
10353
0
    return foundSameNameMethod;
10354
0
  }
10355
};
10356
} // end anonymous namespace
10357
10358
/// Add the most overridden methods from MD to Methods
10359
static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10360
0
                        llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10361
0
  if (MD->size_overridden_methods() == 0)
10362
0
    Methods.insert(MD->getCanonicalDecl());
10363
0
  else
10364
0
    for (const CXXMethodDecl *O : MD->overridden_methods())
10365
0
      AddMostOverridenMethods(O, Methods);
10366
0
}
10367
10368
/// Check if a method overloads virtual methods in a base class without
10369
/// overriding any.
10370
void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10371
0
                          SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10372
0
  if (!MD->getDeclName().isIdentifier())
10373
0
    return;
10374
10375
0
  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10376
0
                     /*bool RecordPaths=*/false,
10377
0
                     /*bool DetectVirtual=*/false);
10378
0
  FindHiddenVirtualMethod FHVM;
10379
0
  FHVM.Method = MD;
10380
0
  FHVM.S = this;
10381
10382
  // Keep the base methods that were overridden or introduced in the subclass
10383
  // by 'using' in a set. A base method not in this set is hidden.
10384
0
  CXXRecordDecl *DC = MD->getParent();
10385
0
  DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
10386
0
  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10387
0
    NamedDecl *ND = *I;
10388
0
    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10389
0
      ND = shad->getTargetDecl();
10390
0
    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10391
0
      AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10392
0
  }
10393
10394
0
  if (DC->lookupInBases(FHVM, Paths))
10395
0
    OverloadedMethods = FHVM.OverloadedMethods;
10396
0
}
10397
10398
void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10399
0
                          SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10400
0
  for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10401
0
    CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10402
0
    PartialDiagnostic PD = PDiag(
10403
0
         diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10404
0
    HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10405
0
    Diag(overloadedMD->getLocation(), PD);
10406
0
  }
10407
0
}
10408
10409
/// Diagnose methods which overload virtual methods in a base class
10410
/// without overriding any.
10411
0
void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10412
0
  if (MD->isInvalidDecl())
10413
0
    return;
10414
10415
0
  if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10416
0
    return;
10417
10418
0
  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10419
0
  FindHiddenVirtualMethods(MD, OverloadedMethods);
10420
0
  if (!OverloadedMethods.empty()) {
10421
0
    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10422
0
      << MD << (OverloadedMethods.size() > 1);
10423
10424
0
    NoteHiddenVirtualMethods(MD, OverloadedMethods);
10425
0
  }
10426
0
}
10427
10428
0
void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10429
0
  auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10430
    // No diagnostics if this is a template instantiation.
10431
0
    if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
10432
0
      Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10433
0
           diag::ext_cannot_use_trivial_abi) << &RD;
10434
0
      Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10435
0
           diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10436
0
    }
10437
0
    RD.dropAttr<TrivialABIAttr>();
10438
0
  };
10439
10440
  // Ill-formed if the copy and move constructors are deleted.
10441
0
  auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10442
    // If the type is dependent, then assume it might have
10443
    // implicit copy or move ctor because we won't know yet at this point.
10444
0
    if (RD.isDependentType())
10445
0
      return true;
10446
0
    if (RD.needsImplicitCopyConstructor() &&
10447
0
        !RD.defaultedCopyConstructorIsDeleted())
10448
0
      return true;
10449
0
    if (RD.needsImplicitMoveConstructor() &&
10450
0
        !RD.defaultedMoveConstructorIsDeleted())
10451
0
      return true;
10452
0
    for (const CXXConstructorDecl *CD : RD.ctors())
10453
0
      if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10454
0
        return true;
10455
0
    return false;
10456
0
  };
10457
10458
0
  if (!HasNonDeletedCopyOrMoveConstructor()) {
10459
0
    PrintDiagAndRemoveAttr(0);
10460
0
    return;
10461
0
  }
10462
10463
  // Ill-formed if the struct has virtual functions.
10464
0
  if (RD.isPolymorphic()) {
10465
0
    PrintDiagAndRemoveAttr(1);
10466
0
    return;
10467
0
  }
10468
10469
0
  for (const auto &B : RD.bases()) {
10470
    // Ill-formed if the base class is non-trivial for the purpose of calls or a
10471
    // virtual base.
10472
0
    if (!B.getType()->isDependentType() &&
10473
0
        !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10474
0
      PrintDiagAndRemoveAttr(2);
10475
0
      return;
10476
0
    }
10477
10478
0
    if (B.isVirtual()) {
10479
0
      PrintDiagAndRemoveAttr(3);
10480
0
      return;
10481
0
    }
10482
0
  }
10483
10484
0
  for (const auto *FD : RD.fields()) {
10485
    // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10486
    // non-trivial for the purpose of calls.
10487
0
    QualType FT = FD->getType();
10488
0
    if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10489
0
      PrintDiagAndRemoveAttr(4);
10490
0
      return;
10491
0
    }
10492
10493
0
    if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10494
0
      if (!RT->isDependentType() &&
10495
0
          !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10496
0
        PrintDiagAndRemoveAttr(5);
10497
0
        return;
10498
0
      }
10499
0
  }
10500
0
}
10501
10502
void Sema::ActOnFinishCXXMemberSpecification(
10503
    Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10504
0
    SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10505
0
  if (!TagDecl)
10506
0
    return;
10507
10508
0
  AdjustDeclIfTemplate(TagDecl);
10509
10510
0
  for (const ParsedAttr &AL : AttrList) {
10511
0
    if (AL.getKind() != ParsedAttr::AT_Visibility)
10512
0
      continue;
10513
0
    AL.setInvalid();
10514
0
    Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10515
0
  }
10516
10517
0
  ActOnFields(S, RLoc, TagDecl,
10518
0
              llvm::ArrayRef(
10519
                  // strict aliasing violation!
10520
0
                  reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10521
0
                  FieldCollector->getCurNumFields()),
10522
0
              LBrac, RBrac, AttrList);
10523
10524
0
  CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10525
0
}
10526
10527
/// Find the equality comparison functions that should be implicitly declared
10528
/// in a given class definition, per C++2a [class.compare.default]p3.
10529
static void findImplicitlyDeclaredEqualityComparisons(
10530
    ASTContext &Ctx, CXXRecordDecl *RD,
10531
0
    llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10532
0
  DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10533
0
  if (!RD->lookup(EqEq).empty())
10534
    // Member operator== explicitly declared: no implicit operator==s.
10535
0
    return;
10536
10537
  // Traverse friends looking for an '==' or a '<=>'.
10538
0
  for (FriendDecl *Friend : RD->friends()) {
10539
0
    FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10540
0
    if (!FD) continue;
10541
10542
0
    if (FD->getOverloadedOperator() == OO_EqualEqual) {
10543
      // Friend operator== explicitly declared: no implicit operator==s.
10544
0
      Spaceships.clear();
10545
0
      return;
10546
0
    }
10547
10548
0
    if (FD->getOverloadedOperator() == OO_Spaceship &&
10549
0
        FD->isExplicitlyDefaulted())
10550
0
      Spaceships.push_back(FD);
10551
0
  }
10552
10553
  // Look for members named 'operator<=>'.
10554
0
  DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10555
0
  for (NamedDecl *ND : RD->lookup(Cmp)) {
10556
    // Note that we could find a non-function here (either a function template
10557
    // or a using-declaration). Neither case results in an implicit
10558
    // 'operator=='.
10559
0
    if (auto *FD = dyn_cast<FunctionDecl>(ND))
10560
0
      if (FD->isExplicitlyDefaulted())
10561
0
        Spaceships.push_back(FD);
10562
0
  }
10563
0
}
10564
10565
/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10566
/// special functions, such as the default constructor, copy
10567
/// constructor, or destructor, to the given C++ class (C++
10568
/// [special]p1).  This routine can only be executed just before the
10569
/// definition of the class is complete.
10570
0
void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10571
  // Don't add implicit special members to templated classes.
10572
  // FIXME: This means unqualified lookups for 'operator=' within a class
10573
  // template don't work properly.
10574
0
  if (!ClassDecl->isDependentType()) {
10575
0
    if (ClassDecl->needsImplicitDefaultConstructor()) {
10576
0
      ++getASTContext().NumImplicitDefaultConstructors;
10577
10578
0
      if (ClassDecl->hasInheritedConstructor())
10579
0
        DeclareImplicitDefaultConstructor(ClassDecl);
10580
0
    }
10581
10582
0
    if (ClassDecl->needsImplicitCopyConstructor()) {
10583
0
      ++getASTContext().NumImplicitCopyConstructors;
10584
10585
      // If the properties or semantics of the copy constructor couldn't be
10586
      // determined while the class was being declared, force a declaration
10587
      // of it now.
10588
0
      if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10589
0
          ClassDecl->hasInheritedConstructor())
10590
0
        DeclareImplicitCopyConstructor(ClassDecl);
10591
      // For the MS ABI we need to know whether the copy ctor is deleted. A
10592
      // prerequisite for deleting the implicit copy ctor is that the class has
10593
      // a move ctor or move assignment that is either user-declared or whose
10594
      // semantics are inherited from a subobject. FIXME: We should provide a
10595
      // more direct way for CodeGen to ask whether the constructor was deleted.
10596
0
      else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10597
0
               (ClassDecl->hasUserDeclaredMoveConstructor() ||
10598
0
                ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10599
0
                ClassDecl->hasUserDeclaredMoveAssignment() ||
10600
0
                ClassDecl->needsOverloadResolutionForMoveAssignment()))
10601
0
        DeclareImplicitCopyConstructor(ClassDecl);
10602
0
    }
10603
10604
0
    if (getLangOpts().CPlusPlus11 &&
10605
0
        ClassDecl->needsImplicitMoveConstructor()) {
10606
0
      ++getASTContext().NumImplicitMoveConstructors;
10607
10608
0
      if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10609
0
          ClassDecl->hasInheritedConstructor())
10610
0
        DeclareImplicitMoveConstructor(ClassDecl);
10611
0
    }
10612
10613
0
    if (ClassDecl->needsImplicitCopyAssignment()) {
10614
0
      ++getASTContext().NumImplicitCopyAssignmentOperators;
10615
10616
      // If we have a dynamic class, then the copy assignment operator may be
10617
      // virtual, so we have to declare it immediately. This ensures that, e.g.,
10618
      // it shows up in the right place in the vtable and that we diagnose
10619
      // problems with the implicit exception specification.
10620
0
      if (ClassDecl->isDynamicClass() ||
10621
0
          ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10622
0
          ClassDecl->hasInheritedAssignment())
10623
0
        DeclareImplicitCopyAssignment(ClassDecl);
10624
0
    }
10625
10626
0
    if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10627
0
      ++getASTContext().NumImplicitMoveAssignmentOperators;
10628
10629
      // Likewise for the move assignment operator.
10630
0
      if (ClassDecl->isDynamicClass() ||
10631
0
          ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10632
0
          ClassDecl->hasInheritedAssignment())
10633
0
        DeclareImplicitMoveAssignment(ClassDecl);
10634
0
    }
10635
10636
0
    if (ClassDecl->needsImplicitDestructor()) {
10637
0
      ++getASTContext().NumImplicitDestructors;
10638
10639
      // If we have a dynamic class, then the destructor may be virtual, so we
10640
      // have to declare the destructor immediately. This ensures that, e.g., it
10641
      // shows up in the right place in the vtable and that we diagnose problems
10642
      // with the implicit exception specification.
10643
0
      if (ClassDecl->isDynamicClass() ||
10644
0
          ClassDecl->needsOverloadResolutionForDestructor())
10645
0
        DeclareImplicitDestructor(ClassDecl);
10646
0
    }
10647
0
  }
10648
10649
  // C++2a [class.compare.default]p3:
10650
  //   If the member-specification does not explicitly declare any member or
10651
  //   friend named operator==, an == operator function is declared implicitly
10652
  //   for each defaulted three-way comparison operator function defined in
10653
  //   the member-specification
10654
  // FIXME: Consider doing this lazily.
10655
  // We do this during the initial parse for a class template, not during
10656
  // instantiation, so that we can handle unqualified lookups for 'operator=='
10657
  // when parsing the template.
10658
0
  if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10659
0
    llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10660
0
    findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10661
0
                                              DefaultedSpaceships);
10662
0
    for (auto *FD : DefaultedSpaceships)
10663
0
      DeclareImplicitEqualityComparison(ClassDecl, FD);
10664
0
  }
10665
0
}
10666
10667
unsigned
10668
Sema::ActOnReenterTemplateScope(Decl *D,
10669
0
                                llvm::function_ref<Scope *()> EnterScope) {
10670
0
  if (!D)
10671
0
    return 0;
10672
0
  AdjustDeclIfTemplate(D);
10673
10674
  // In order to get name lookup right, reenter template scopes in order from
10675
  // outermost to innermost.
10676
0
  SmallVector<TemplateParameterList *, 4> ParameterLists;
10677
0
  DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10678
10679
0
  if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10680
0
    for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10681
0
      ParameterLists.push_back(DD->getTemplateParameterList(i));
10682
10683
0
    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10684
0
      if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10685
0
        ParameterLists.push_back(FTD->getTemplateParameters());
10686
0
    } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10687
0
      LookupDC = VD->getDeclContext();
10688
10689
0
      if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10690
0
        ParameterLists.push_back(VTD->getTemplateParameters());
10691
0
      else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10692
0
        ParameterLists.push_back(PSD->getTemplateParameters());
10693
0
    }
10694
0
  } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10695
0
    for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10696
0
      ParameterLists.push_back(TD->getTemplateParameterList(i));
10697
10698
0
    if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10699
0
      if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10700
0
        ParameterLists.push_back(CTD->getTemplateParameters());
10701
0
      else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10702
0
        ParameterLists.push_back(PSD->getTemplateParameters());
10703
0
    }
10704
0
  }
10705
  // FIXME: Alias declarations and concepts.
10706
10707
0
  unsigned Count = 0;
10708
0
  Scope *InnermostTemplateScope = nullptr;
10709
0
  for (TemplateParameterList *Params : ParameterLists) {
10710
    // Ignore explicit specializations; they don't contribute to the template
10711
    // depth.
10712
0
    if (Params->size() == 0)
10713
0
      continue;
10714
10715
0
    InnermostTemplateScope = EnterScope();
10716
0
    for (NamedDecl *Param : *Params) {
10717
0
      if (Param->getDeclName()) {
10718
0
        InnermostTemplateScope->AddDecl(Param);
10719
0
        IdResolver.AddDecl(Param);
10720
0
      }
10721
0
    }
10722
0
    ++Count;
10723
0
  }
10724
10725
  // Associate the new template scopes with the corresponding entities.
10726
0
  if (InnermostTemplateScope) {
10727
0
    assert(LookupDC && "no enclosing DeclContext for template lookup");
10728
0
    EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10729
0
  }
10730
10731
0
  return Count;
10732
0
}
10733
10734
0
void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10735
0
  if (!RecordD) return;
10736
0
  AdjustDeclIfTemplate(RecordD);
10737
0
  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10738
0
  PushDeclContext(S, Record);
10739
0
}
10740
10741
0
void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10742
0
  if (!RecordD) return;
10743
0
  PopDeclContext();
10744
0
}
10745
10746
/// This is used to implement the constant expression evaluation part of the
10747
/// attribute enable_if extension. There is nothing in standard C++ which would
10748
/// require reentering parameters.
10749
0
void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10750
0
  if (!Param)
10751
0
    return;
10752
10753
0
  S->AddDecl(Param);
10754
0
  if (Param->getDeclName())
10755
0
    IdResolver.AddDecl(Param);
10756
0
}
10757
10758
/// ActOnStartDelayedCXXMethodDeclaration - We have completed
10759
/// parsing a top-level (non-nested) C++ class, and we are now
10760
/// parsing those parts of the given Method declaration that could
10761
/// not be parsed earlier (C++ [class.mem]p2), such as default
10762
/// arguments. This action should enter the scope of the given
10763
/// Method declaration as if we had just parsed the qualified method
10764
/// name. However, it should not bring the parameters into scope;
10765
/// that will be performed by ActOnDelayedCXXMethodParameter.
10766
0
void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10767
0
}
10768
10769
/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10770
/// C++ method declaration. We're (re-)introducing the given
10771
/// function parameter into scope for use in parsing later parts of
10772
/// the method declaration. For example, we could see an
10773
/// ActOnParamDefaultArgument event for this parameter.
10774
0
void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10775
0
  if (!ParamD)
10776
0
    return;
10777
10778
0
  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10779
10780
0
  S->AddDecl(Param);
10781
0
  if (Param->getDeclName())
10782
0
    IdResolver.AddDecl(Param);
10783
0
}
10784
10785
/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10786
/// processing the delayed method declaration for Method. The method
10787
/// declaration is now considered finished. There may be a separate
10788
/// ActOnStartOfFunctionDef action later (not necessarily
10789
/// immediately!) for this method, if it was also defined inside the
10790
/// class body.
10791
0
void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10792
0
  if (!MethodD)
10793
0
    return;
10794
10795
0
  AdjustDeclIfTemplate(MethodD);
10796
10797
0
  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10798
10799
  // Now that we have our default arguments, check the constructor
10800
  // again. It could produce additional diagnostics or affect whether
10801
  // the class has implicitly-declared destructors, among other
10802
  // things.
10803
0
  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10804
0
    CheckConstructor(Constructor);
10805
10806
  // Check the default arguments, which we may have added.
10807
0
  if (!Method->isInvalidDecl())
10808
0
    CheckCXXDefaultArguments(Method);
10809
0
}
10810
10811
// Emit the given diagnostic for each non-address-space qualifier.
10812
// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10813
0
static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10814
0
  const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10815
0
  if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10816
0
    bool DiagOccured = false;
10817
0
    FTI.MethodQualifiers->forEachQualifier(
10818
0
        [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10819
0
                                   SourceLocation SL) {
10820
          // This diagnostic should be emitted on any qualifier except an addr
10821
          // space qualifier. However, forEachQualifier currently doesn't visit
10822
          // addr space qualifiers, so there's no way to write this condition
10823
          // right now; we just diagnose on everything.
10824
0
          S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10825
0
          DiagOccured = true;
10826
0
        });
10827
0
    if (DiagOccured)
10828
0
      D.setInvalidType();
10829
0
  }
10830
0
}
10831
10832
/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10833
/// the well-formedness of the constructor declarator @p D with type @p
10834
/// R. If there are any errors in the declarator, this routine will
10835
/// emit diagnostics and set the invalid bit to true.  In any case, the type
10836
/// will be updated to reflect a well-formed type for the constructor and
10837
/// returned.
10838
QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10839
0
                                          StorageClass &SC) {
10840
0
  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10841
10842
  // C++ [class.ctor]p3:
10843
  //   A constructor shall not be virtual (10.3) or static (9.4). A
10844
  //   constructor can be invoked for a const, volatile or const
10845
  //   volatile object. A constructor shall not be declared const,
10846
  //   volatile, or const volatile (9.3.2).
10847
0
  if (isVirtual) {
10848
0
    if (!D.isInvalidType())
10849
0
      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10850
0
        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10851
0
        << SourceRange(D.getIdentifierLoc());
10852
0
    D.setInvalidType();
10853
0
  }
10854
0
  if (SC == SC_Static) {
10855
0
    if (!D.isInvalidType())
10856
0
      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10857
0
        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10858
0
        << SourceRange(D.getIdentifierLoc());
10859
0
    D.setInvalidType();
10860
0
    SC = SC_None;
10861
0
  }
10862
10863
0
  if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10864
0
    diagnoseIgnoredQualifiers(
10865
0
        diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10866
0
        D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10867
0
        D.getDeclSpec().getRestrictSpecLoc(),
10868
0
        D.getDeclSpec().getAtomicSpecLoc());
10869
0
    D.setInvalidType();
10870
0
  }
10871
10872
0
  checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10873
10874
  // C++0x [class.ctor]p4:
10875
  //   A constructor shall not be declared with a ref-qualifier.
10876
0
  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10877
0
  if (FTI.hasRefQualifier()) {
10878
0
    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10879
0
      << FTI.RefQualifierIsLValueRef
10880
0
      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10881
0
    D.setInvalidType();
10882
0
  }
10883
10884
  // Rebuild the function type "R" without any type qualifiers (in
10885
  // case any of the errors above fired) and with "void" as the
10886
  // return type, since constructors don't have return types.
10887
0
  const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10888
0
  if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10889
0
    return R;
10890
10891
0
  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10892
0
  EPI.TypeQuals = Qualifiers();
10893
0
  EPI.RefQualifier = RQ_None;
10894
10895
0
  return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10896
0
}
10897
10898
/// CheckConstructor - Checks a fully-formed constructor for
10899
/// well-formedness, issuing any diagnostics required. Returns true if
10900
/// the constructor declarator is invalid.
10901
0
void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10902
0
  CXXRecordDecl *ClassDecl
10903
0
    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10904
0
  if (!ClassDecl)
10905
0
    return Constructor->setInvalidDecl();
10906
10907
  // C++ [class.copy]p3:
10908
  //   A declaration of a constructor for a class X is ill-formed if
10909
  //   its first parameter is of type (optionally cv-qualified) X and
10910
  //   either there are no other parameters or else all other
10911
  //   parameters have default arguments.
10912
0
  if (!Constructor->isInvalidDecl() &&
10913
0
      Constructor->hasOneParamOrDefaultArgs() &&
10914
0
      Constructor->getTemplateSpecializationKind() !=
10915
0
          TSK_ImplicitInstantiation) {
10916
0
    QualType ParamType = Constructor->getParamDecl(0)->getType();
10917
0
    QualType ClassTy = Context.getTagDeclType(ClassDecl);
10918
0
    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10919
0
      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10920
0
      const char *ConstRef
10921
0
        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10922
0
                                                        : " const &";
10923
0
      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10924
0
        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10925
10926
      // FIXME: Rather that making the constructor invalid, we should endeavor
10927
      // to fix the type.
10928
0
      Constructor->setInvalidDecl();
10929
0
    }
10930
0
  }
10931
0
}
10932
10933
/// CheckDestructor - Checks a fully-formed destructor definition for
10934
/// well-formedness, issuing any diagnostics required.  Returns true
10935
/// on error.
10936
0
bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10937
0
  CXXRecordDecl *RD = Destructor->getParent();
10938
10939
0
  if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10940
0
    SourceLocation Loc;
10941
10942
0
    if (!Destructor->isImplicit())
10943
0
      Loc = Destructor->getLocation();
10944
0
    else
10945
0
      Loc = RD->getLocation();
10946
10947
    // If we have a virtual destructor, look up the deallocation function
10948
0
    if (FunctionDecl *OperatorDelete =
10949
0
            FindDeallocationFunctionForDestructor(Loc, RD)) {
10950
0
      Expr *ThisArg = nullptr;
10951
10952
      // If the notional 'delete this' expression requires a non-trivial
10953
      // conversion from 'this' to the type of a destroying operator delete's
10954
      // first parameter, perform that conversion now.
10955
0
      if (OperatorDelete->isDestroyingOperatorDelete()) {
10956
0
        QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10957
0
        if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10958
          // C++ [class.dtor]p13:
10959
          //   ... as if for the expression 'delete this' appearing in a
10960
          //   non-virtual destructor of the destructor's class.
10961
0
          ContextRAII SwitchContext(*this, Destructor);
10962
0
          ExprResult This =
10963
0
              ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10964
0
          assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10965
0
          This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10966
0
          if (This.isInvalid()) {
10967
            // FIXME: Register this as a context note so that it comes out
10968
            // in the right order.
10969
0
            Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10970
0
            return true;
10971
0
          }
10972
0
          ThisArg = This.get();
10973
0
        }
10974
0
      }
10975
10976
0
      DiagnoseUseOfDecl(OperatorDelete, Loc);
10977
0
      MarkFunctionReferenced(Loc, OperatorDelete);
10978
0
      Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10979
0
    }
10980
0
  }
10981
10982
0
  return false;
10983
0
}
10984
10985
/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10986
/// the well-formednes of the destructor declarator @p D with type @p
10987
/// R. If there are any errors in the declarator, this routine will
10988
/// emit diagnostics and set the declarator to invalid.  Even if this happens,
10989
/// will be updated to reflect a well-formed type for the destructor and
10990
/// returned.
10991
QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10992
0
                                         StorageClass& SC) {
10993
  // C++ [class.dtor]p1:
10994
  //   [...] A typedef-name that names a class is a class-name
10995
  //   (7.1.3); however, a typedef-name that names a class shall not
10996
  //   be used as the identifier in the declarator for a destructor
10997
  //   declaration.
10998
0
  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10999
0
  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11000
0
    Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11001
0
      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
11002
0
  else if (const TemplateSpecializationType *TST =
11003
0
             DeclaratorType->getAs<TemplateSpecializationType>())
11004
0
    if (TST->isTypeAlias())
11005
0
      Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
11006
0
        << DeclaratorType << 1;
11007
11008
  // C++ [class.dtor]p2:
11009
  //   A destructor is used to destroy objects of its class type. A
11010
  //   destructor takes no parameters, and no return type can be
11011
  //   specified for it (not even void). The address of a destructor
11012
  //   shall not be taken. A destructor shall not be static. A
11013
  //   destructor can be invoked for a const, volatile or const
11014
  //   volatile object. A destructor shall not be declared const,
11015
  //   volatile or const volatile (9.3.2).
11016
0
  if (SC == SC_Static) {
11017
0
    if (!D.isInvalidType())
11018
0
      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
11019
0
        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11020
0
        << SourceRange(D.getIdentifierLoc())
11021
0
        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
11022
11023
0
    SC = SC_None;
11024
0
  }
11025
0
  if (!D.isInvalidType()) {
11026
    // Destructors don't have return types, but the parser will
11027
    // happily parse something like:
11028
    //
11029
    //   class X {
11030
    //     float ~X();
11031
    //   };
11032
    //
11033
    // The return type will be eliminated later.
11034
0
    if (D.getDeclSpec().hasTypeSpecifier())
11035
0
      Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
11036
0
        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
11037
0
        << SourceRange(D.getIdentifierLoc());
11038
0
    else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11039
0
      diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
11040
0
                                SourceLocation(),
11041
0
                                D.getDeclSpec().getConstSpecLoc(),
11042
0
                                D.getDeclSpec().getVolatileSpecLoc(),
11043
0
                                D.getDeclSpec().getRestrictSpecLoc(),
11044
0
                                D.getDeclSpec().getAtomicSpecLoc());
11045
0
      D.setInvalidType();
11046
0
    }
11047
0
  }
11048
11049
0
  checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
11050
11051
  // C++0x [class.dtor]p2:
11052
  //   A destructor shall not be declared with a ref-qualifier.
11053
0
  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11054
0
  if (FTI.hasRefQualifier()) {
11055
0
    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
11056
0
      << FTI.RefQualifierIsLValueRef
11057
0
      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
11058
0
    D.setInvalidType();
11059
0
  }
11060
11061
  // Make sure we don't have any parameters.
11062
0
  if (FTIHasNonVoidParameters(FTI)) {
11063
0
    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
11064
11065
    // Delete the parameters.
11066
0
    FTI.freeParams();
11067
0
    D.setInvalidType();
11068
0
  }
11069
11070
  // Make sure the destructor isn't variadic.
11071
0
  if (FTI.isVariadic) {
11072
0
    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
11073
0
    D.setInvalidType();
11074
0
  }
11075
11076
  // Rebuild the function type "R" without any type qualifiers or
11077
  // parameters (in case any of the errors above fired) and with
11078
  // "void" as the return type, since destructors don't have return
11079
  // types.
11080
0
  if (!D.isInvalidType())
11081
0
    return R;
11082
11083
0
  const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11084
0
  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11085
0
  EPI.Variadic = false;
11086
0
  EPI.TypeQuals = Qualifiers();
11087
0
  EPI.RefQualifier = RQ_None;
11088
0
  return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI);
11089
0
}
11090
11091
0
static void extendLeft(SourceRange &R, SourceRange Before) {
11092
0
  if (Before.isInvalid())
11093
0
    return;
11094
0
  R.setBegin(Before.getBegin());
11095
0
  if (R.getEnd().isInvalid())
11096
0
    R.setEnd(Before.getEnd());
11097
0
}
11098
11099
0
static void extendRight(SourceRange &R, SourceRange After) {
11100
0
  if (After.isInvalid())
11101
0
    return;
11102
0
  if (R.getBegin().isInvalid())
11103
0
    R.setBegin(After.getBegin());
11104
0
  R.setEnd(After.getEnd());
11105
0
}
11106
11107
/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
11108
/// well-formednes of the conversion function declarator @p D with
11109
/// type @p R. If there are any errors in the declarator, this routine
11110
/// will emit diagnostics and return true. Otherwise, it will return
11111
/// false. Either way, the type @p R will be updated to reflect a
11112
/// well-formed type for the conversion operator.
11113
void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
11114
0
                                     StorageClass& SC) {
11115
  // C++ [class.conv.fct]p1:
11116
  //   Neither parameter types nor return type can be specified. The
11117
  //   type of a conversion function (8.3.5) is "function taking no
11118
  //   parameter returning conversion-type-id."
11119
0
  if (SC == SC_Static) {
11120
0
    if (!D.isInvalidType())
11121
0
      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
11122
0
        << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11123
0
        << D.getName().getSourceRange();
11124
0
    D.setInvalidType();
11125
0
    SC = SC_None;
11126
0
  }
11127
11128
0
  TypeSourceInfo *ConvTSI = nullptr;
11129
0
  QualType ConvType =
11130
0
      GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
11131
11132
0
  const DeclSpec &DS = D.getDeclSpec();
11133
0
  if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11134
    // Conversion functions don't have return types, but the parser will
11135
    // happily parse something like:
11136
    //
11137
    //   class X {
11138
    //     float operator bool();
11139
    //   };
11140
    //
11141
    // The return type will be changed later anyway.
11142
0
    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
11143
0
      << SourceRange(DS.getTypeSpecTypeLoc())
11144
0
      << SourceRange(D.getIdentifierLoc());
11145
0
    D.setInvalidType();
11146
0
  } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11147
    // It's also plausible that the user writes type qualifiers in the wrong
11148
    // place, such as:
11149
    //   struct S { const operator int(); };
11150
    // FIXME: we could provide a fixit to move the qualifiers onto the
11151
    // conversion type.
11152
0
    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
11153
0
        << SourceRange(D.getIdentifierLoc()) << 0;
11154
0
    D.setInvalidType();
11155
0
  }
11156
0
  const auto *Proto = R->castAs<FunctionProtoType>();
11157
  // Make sure we don't have any parameters.
11158
0
  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11159
0
  unsigned NumParam = Proto->getNumParams();
11160
11161
  // [C++2b]
11162
  // A conversion function shall have no non-object parameters.
11163
0
  if (NumParam == 1) {
11164
0
    DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11165
0
    if (const auto *First =
11166
0
            dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param);
11167
0
        First && First->isExplicitObjectParameter())
11168
0
      NumParam--;
11169
0
  }
11170
11171
0
  if (NumParam != 0) {
11172
0
    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
11173
    // Delete the parameters.
11174
0
    FTI.freeParams();
11175
0
    D.setInvalidType();
11176
0
  } else if (Proto->isVariadic()) {
11177
0
    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
11178
0
    D.setInvalidType();
11179
0
  }
11180
11181
  // Diagnose "&operator bool()" and other such nonsense.  This
11182
  // is actually a gcc extension which we don't support.
11183
0
  if (Proto->getReturnType() != ConvType) {
11184
0
    bool NeedsTypedef = false;
11185
0
    SourceRange Before, After;
11186
11187
    // Walk the chunks and extract information on them for our diagnostic.
11188
0
    bool PastFunctionChunk = false;
11189
0
    for (auto &Chunk : D.type_objects()) {
11190
0
      switch (Chunk.Kind) {
11191
0
      case DeclaratorChunk::Function:
11192
0
        if (!PastFunctionChunk) {
11193
0
          if (Chunk.Fun.HasTrailingReturnType) {
11194
0
            TypeSourceInfo *TRT = nullptr;
11195
0
            GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
11196
0
            if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
11197
0
          }
11198
0
          PastFunctionChunk = true;
11199
0
          break;
11200
0
        }
11201
0
        [[fallthrough]];
11202
0
      case DeclaratorChunk::Array:
11203
0
        NeedsTypedef = true;
11204
0
        extendRight(After, Chunk.getSourceRange());
11205
0
        break;
11206
11207
0
      case DeclaratorChunk::Pointer:
11208
0
      case DeclaratorChunk::BlockPointer:
11209
0
      case DeclaratorChunk::Reference:
11210
0
      case DeclaratorChunk::MemberPointer:
11211
0
      case DeclaratorChunk::Pipe:
11212
0
        extendLeft(Before, Chunk.getSourceRange());
11213
0
        break;
11214
11215
0
      case DeclaratorChunk::Paren:
11216
0
        extendLeft(Before, Chunk.Loc);
11217
0
        extendRight(After, Chunk.EndLoc);
11218
0
        break;
11219
0
      }
11220
0
    }
11221
11222
0
    SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11223
0
                         After.isValid()  ? After.getBegin() :
11224
0
                                            D.getIdentifierLoc();
11225
0
    auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
11226
0
    DB << Before << After;
11227
11228
0
    if (!NeedsTypedef) {
11229
0
      DB << /*don't need a typedef*/0;
11230
11231
      // If we can provide a correct fix-it hint, do so.
11232
0
      if (After.isInvalid() && ConvTSI) {
11233
0
        SourceLocation InsertLoc =
11234
0
            getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
11235
0
        DB << FixItHint::CreateInsertion(InsertLoc, " ")
11236
0
           << FixItHint::CreateInsertionFromRange(
11237
0
                  InsertLoc, CharSourceRange::getTokenRange(Before))
11238
0
           << FixItHint::CreateRemoval(Before);
11239
0
      }
11240
0
    } else if (!Proto->getReturnType()->isDependentType()) {
11241
0
      DB << /*typedef*/1 << Proto->getReturnType();
11242
0
    } else if (getLangOpts().CPlusPlus11) {
11243
0
      DB << /*alias template*/2 << Proto->getReturnType();
11244
0
    } else {
11245
0
      DB << /*might not be fixable*/3;
11246
0
    }
11247
11248
    // Recover by incorporating the other type chunks into the result type.
11249
    // Note, this does *not* change the name of the function. This is compatible
11250
    // with the GCC extension:
11251
    //   struct S { &operator int(); } s;
11252
    //   int &r = s.operator int(); // ok in GCC
11253
    //   S::operator int&() {} // error in GCC, function name is 'operator int'.
11254
0
    ConvType = Proto->getReturnType();
11255
0
  }
11256
11257
  // C++ [class.conv.fct]p4:
11258
  //   The conversion-type-id shall not represent a function type nor
11259
  //   an array type.
11260
0
  if (ConvType->isArrayType()) {
11261
0
    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
11262
0
    ConvType = Context.getPointerType(ConvType);
11263
0
    D.setInvalidType();
11264
0
  } else if (ConvType->isFunctionType()) {
11265
0
    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
11266
0
    ConvType = Context.getPointerType(ConvType);
11267
0
    D.setInvalidType();
11268
0
  }
11269
11270
  // Rebuild the function type "R" without any parameters (in case any
11271
  // of the errors above fired) and with the conversion type as the
11272
  // return type.
11273
0
  if (D.isInvalidType())
11274
0
    R = Context.getFunctionType(ConvType, std::nullopt,
11275
0
                                Proto->getExtProtoInfo());
11276
11277
  // C++0x explicit conversion operators.
11278
0
  if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
11279
0
    Diag(DS.getExplicitSpecLoc(),
11280
0
         getLangOpts().CPlusPlus11
11281
0
             ? diag::warn_cxx98_compat_explicit_conversion_functions
11282
0
             : diag::ext_explicit_conversion_functions)
11283
0
        << SourceRange(DS.getExplicitSpecRange());
11284
0
}
11285
11286
/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
11287
/// the declaration of the given C++ conversion function. This routine
11288
/// is responsible for recording the conversion function in the C++
11289
/// class, if possible.
11290
0
Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11291
0
  assert(Conversion && "Expected to receive a conversion function declaration");
11292
11293
0
  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
11294
11295
  // Make sure we aren't redeclaring the conversion function.
11296
0
  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
11297
  // C++ [class.conv.fct]p1:
11298
  //   [...] A conversion function is never used to convert a
11299
  //   (possibly cv-qualified) object to the (possibly cv-qualified)
11300
  //   same object type (or a reference to it), to a (possibly
11301
  //   cv-qualified) base class of that type (or a reference to it),
11302
  //   or to (possibly cv-qualified) void.
11303
0
  QualType ClassType
11304
0
    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11305
0
  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11306
0
    ConvType = ConvTypeRef->getPointeeType();
11307
0
  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11308
0
      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11309
0
    /* Suppress diagnostics for instantiations. */;
11310
0
  else if (Conversion->size_overridden_methods() != 0)
11311
0
    /* Suppress diagnostics for overriding virtual function in a base class. */;
11312
0
  else if (ConvType->isRecordType()) {
11313
0
    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
11314
0
    if (ConvType == ClassType)
11315
0
      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
11316
0
        << ClassType;
11317
0
    else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
11318
0
      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
11319
0
        <<  ClassType << ConvType;
11320
0
  } else if (ConvType->isVoidType()) {
11321
0
    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11322
0
      << ClassType << ConvType;
11323
0
  }
11324
11325
0
  if (FunctionTemplateDecl *ConversionTemplate
11326
0
                                = Conversion->getDescribedFunctionTemplate())
11327
0
    return ConversionTemplate;
11328
11329
0
  return Conversion;
11330
0
}
11331
11332
void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
11333
1
                                             DeclarationName Name, QualType R) {
11334
1
  CheckExplicitObjectMemberFunction(D, Name, R, false, DC);
11335
1
}
11336
11337
0
void Sema::CheckExplicitObjectLambda(Declarator &D) {
11338
0
  CheckExplicitObjectMemberFunction(D, {}, {}, true);
11339
0
}
11340
11341
void Sema::CheckExplicitObjectMemberFunction(Declarator &D,
11342
                                             DeclarationName Name, QualType R,
11343
1
                                             bool IsLambda, DeclContext *DC) {
11344
1
  if (!D.isFunctionDeclarator())
11345
0
    return;
11346
11347
1
  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11348
1
  if (FTI.NumParams == 0)
11349
0
    return;
11350
1
  ParmVarDecl *ExplicitObjectParam = nullptr;
11351
2
  for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11352
1
    const auto &ParamInfo = FTI.Params[Idx];
11353
1
    if (!ParamInfo.Param)
11354
0
      continue;
11355
1
    ParmVarDecl *Param = cast<ParmVarDecl>(ParamInfo.Param);
11356
1
    if (!Param->isExplicitObjectParameter())
11357
1
      continue;
11358
0
    if (Idx == 0) {
11359
0
      ExplicitObjectParam = Param;
11360
0
      continue;
11361
0
    } else {
11362
0
      Diag(Param->getLocation(),
11363
0
           diag::err_explicit_object_parameter_must_be_first)
11364
0
          << IsLambda << Param->getSourceRange();
11365
0
    }
11366
0
  }
11367
1
  if (!ExplicitObjectParam)
11368
1
    return;
11369
11370
0
  if (ExplicitObjectParam->hasDefaultArg()) {
11371
0
    Diag(ExplicitObjectParam->getLocation(),
11372
0
         diag::err_explicit_object_default_arg)
11373
0
        << ExplicitObjectParam->getSourceRange();
11374
0
  }
11375
11376
0
  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) {
11377
0
    Diag(ExplicitObjectParam->getBeginLoc(),
11378
0
         diag::err_explicit_object_parameter_nonmember)
11379
0
        << D.getSourceRange() << /*static=*/0 << IsLambda;
11380
0
    D.setInvalidType();
11381
0
  }
11382
11383
0
  if (D.getDeclSpec().isVirtualSpecified()) {
11384
0
    Diag(ExplicitObjectParam->getBeginLoc(),
11385
0
         diag::err_explicit_object_parameter_nonmember)
11386
0
        << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11387
0
    D.setInvalidType();
11388
0
  }
11389
11390
0
  if (IsLambda && FTI.hasMutableQualifier()) {
11391
0
    Diag(ExplicitObjectParam->getBeginLoc(),
11392
0
         diag::err_explicit_object_parameter_mutable)
11393
0
        << D.getSourceRange();
11394
0
  }
11395
11396
0
  if (IsLambda)
11397
0
    return;
11398
11399
0
  if (!DC || !DC->isRecord()) {
11400
0
    Diag(ExplicitObjectParam->getLocation(),
11401
0
         diag::err_explicit_object_parameter_nonmember)
11402
0
        << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11403
0
    D.setInvalidType();
11404
0
    return;
11405
0
  }
11406
11407
  // CWG2674: constructors and destructors cannot have explicit parameters.
11408
0
  if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11409
0
      Name.getNameKind() == DeclarationName::CXXDestructorName) {
11410
0
    Diag(ExplicitObjectParam->getBeginLoc(),
11411
0
         diag::err_explicit_object_parameter_constructor)
11412
0
        << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11413
0
        << D.getSourceRange();
11414
0
    D.setInvalidType();
11415
0
  }
11416
0
}
11417
11418
namespace {
11419
/// Utility class to accumulate and print a diagnostic listing the invalid
11420
/// specifier(s) on a declaration.
11421
struct BadSpecifierDiagnoser {
11422
  BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11423
0
      : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11424
0
  ~BadSpecifierDiagnoser() {
11425
0
    Diagnostic << Specifiers;
11426
0
  }
11427
11428
0
  template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11429
0
    return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11430
0
  }
Unexecuted instantiation: SemaDeclCXX.cpp:void (anonymous namespace)::BadSpecifierDiagnoser::check<clang::DeclSpec::SCS>(clang::SourceLocation, clang::DeclSpec::SCS)
Unexecuted instantiation: SemaDeclCXX.cpp:void (anonymous namespace)::BadSpecifierDiagnoser::check<clang::DeclSpec::TSC>(clang::SourceLocation, clang::DeclSpec::TSC)
Unexecuted instantiation: SemaDeclCXX.cpp:void (anonymous namespace)::BadSpecifierDiagnoser::check<clang::TypeSpecifierSign>(clang::SourceLocation, clang::TypeSpecifierSign)
Unexecuted instantiation: SemaDeclCXX.cpp:void (anonymous namespace)::BadSpecifierDiagnoser::check<clang::TypeSpecifierWidth>(clang::SourceLocation, clang::TypeSpecifierWidth)
11431
0
  void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11432
0
    return check(SpecLoc,
11433
0
                 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
11434
0
  }
11435
0
  void check(SourceLocation SpecLoc, const char *Spec) {
11436
0
    if (SpecLoc.isInvalid()) return;
11437
0
    Diagnostic << SourceRange(SpecLoc, SpecLoc);
11438
0
    if (!Specifiers.empty()) Specifiers += " ";
11439
0
    Specifiers += Spec;
11440
0
  }
11441
11442
  Sema &S;
11443
  Sema::SemaDiagnosticBuilder Diagnostic;
11444
  std::string Specifiers;
11445
};
11446
}
11447
11448
/// Check the validity of a declarator that we parsed for a deduction-guide.
11449
/// These aren't actually declarators in the grammar, so we need to check that
11450
/// the user didn't specify any pieces that are not part of the deduction-guide
11451
/// grammar. Return true on invalid deduction-guide.
11452
bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11453
0
                                         StorageClass &SC) {
11454
0
  TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11455
0
  TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11456
0
  assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11457
11458
  // C++ [temp.deduct.guide]p3:
11459
  //   A deduction-gide shall be declared in the same scope as the
11460
  //   corresponding class template.
11461
0
  if (!CurContext->getRedeclContext()->Equals(
11462
0
          GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11463
0
    Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11464
0
      << GuidedTemplateDecl;
11465
0
    NoteTemplateLocation(*GuidedTemplateDecl);
11466
0
  }
11467
11468
0
  auto &DS = D.getMutableDeclSpec();
11469
  // We leave 'friend' and 'virtual' to be rejected in the normal way.
11470
0
  if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11471
0
      DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11472
0
      DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11473
0
    BadSpecifierDiagnoser Diagnoser(
11474
0
        *this, D.getIdentifierLoc(),
11475
0
        diag::err_deduction_guide_invalid_specifier);
11476
11477
0
    Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11478
0
    DS.ClearStorageClassSpecs();
11479
0
    SC = SC_None;
11480
11481
    // 'explicit' is permitted.
11482
0
    Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11483
0
    Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11484
0
    Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11485
0
    DS.ClearConstexprSpec();
11486
11487
0
    Diagnoser.check(DS.getConstSpecLoc(), "const");
11488
0
    Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11489
0
    Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11490
0
    Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11491
0
    Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11492
0
    DS.ClearTypeQualifiers();
11493
11494
0
    Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11495
0
    Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11496
0
    Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11497
0
    Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11498
0
    DS.ClearTypeSpecType();
11499
0
  }
11500
11501
0
  if (D.isInvalidType())
11502
0
    return true;
11503
11504
  // Check the declarator is simple enough.
11505
0
  bool FoundFunction = false;
11506
0
  for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11507
0
    if (Chunk.Kind == DeclaratorChunk::Paren)
11508
0
      continue;
11509
0
    if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11510
0
      Diag(D.getDeclSpec().getBeginLoc(),
11511
0
           diag::err_deduction_guide_with_complex_decl)
11512
0
          << D.getSourceRange();
11513
0
      break;
11514
0
    }
11515
0
    if (!Chunk.Fun.hasTrailingReturnType())
11516
0
      return Diag(D.getName().getBeginLoc(),
11517
0
                  diag::err_deduction_guide_no_trailing_return_type);
11518
11519
    // Check that the return type is written as a specialization of
11520
    // the template specified as the deduction-guide's name.
11521
    // The template name may not be qualified. [temp.deduct.guide]
11522
0
    ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11523
0
    TypeSourceInfo *TSI = nullptr;
11524
0
    QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11525
0
    assert(TSI && "deduction guide has valid type but invalid return type?");
11526
0
    bool AcceptableReturnType = false;
11527
0
    bool MightInstantiateToSpecialization = false;
11528
0
    if (auto RetTST =
11529
0
            TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11530
0
      TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11531
0
      bool TemplateMatches =
11532
0
          Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11533
0
      auto TKind = SpecifiedName.getKind();
11534
      // A Using TemplateName can't actually be valid (either it's qualified, or
11535
      // we're in the wrong scope). But we have diagnosed these problems
11536
      // already.
11537
0
      bool SimplyWritten = TKind == TemplateName::Template ||
11538
0
                           TKind == TemplateName::UsingTemplate;
11539
0
      if (SimplyWritten && TemplateMatches)
11540
0
        AcceptableReturnType = true;
11541
0
      else {
11542
        // This could still instantiate to the right type, unless we know it
11543
        // names the wrong class template.
11544
0
        auto *TD = SpecifiedName.getAsTemplateDecl();
11545
0
        MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11546
0
                                             !TemplateMatches);
11547
0
      }
11548
0
    } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11549
0
      MightInstantiateToSpecialization = true;
11550
0
    }
11551
11552
0
    if (!AcceptableReturnType)
11553
0
      return Diag(TSI->getTypeLoc().getBeginLoc(),
11554
0
                  diag::err_deduction_guide_bad_trailing_return_type)
11555
0
             << GuidedTemplate << TSI->getType()
11556
0
             << MightInstantiateToSpecialization
11557
0
             << TSI->getTypeLoc().getSourceRange();
11558
11559
    // Keep going to check that we don't have any inner declarator pieces (we
11560
    // could still have a function returning a pointer to a function).
11561
0
    FoundFunction = true;
11562
0
  }
11563
11564
0
  if (D.isFunctionDefinition())
11565
    // we can still create a valid deduction guide here.
11566
0
    Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11567
0
  return false;
11568
0
}
11569
11570
//===----------------------------------------------------------------------===//
11571
// Namespace Handling
11572
//===----------------------------------------------------------------------===//
11573
11574
/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11575
/// reopened.
11576
static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11577
                                            SourceLocation Loc,
11578
                                            IdentifierInfo *II, bool *IsInline,
11579
0
                                            NamespaceDecl *PrevNS) {
11580
0
  assert(*IsInline != PrevNS->isInline());
11581
11582
  // 'inline' must appear on the original definition, but not necessarily
11583
  // on all extension definitions, so the note should point to the first
11584
  // definition to avoid confusion.
11585
0
  PrevNS = PrevNS->getFirstDecl();
11586
11587
0
  if (PrevNS->isInline())
11588
    // The user probably just forgot the 'inline', so suggest that it
11589
    // be added back.
11590
0
    S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11591
0
      << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11592
0
  else
11593
0
    S.Diag(Loc, diag::err_inline_namespace_mismatch);
11594
11595
0
  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11596
0
  *IsInline = PrevNS->isInline();
11597
0
}
11598
11599
/// ActOnStartNamespaceDef - This is called at the start of a namespace
11600
/// definition.
11601
Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11602
                                   SourceLocation InlineLoc,
11603
                                   SourceLocation NamespaceLoc,
11604
                                   SourceLocation IdentLoc, IdentifierInfo *II,
11605
                                   SourceLocation LBrace,
11606
                                   const ParsedAttributesView &AttrList,
11607
0
                                   UsingDirectiveDecl *&UD, bool IsNested) {
11608
0
  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11609
  // For anonymous namespace, take the location of the left brace.
11610
0
  SourceLocation Loc = II ? IdentLoc : LBrace;
11611
0
  bool IsInline = InlineLoc.isValid();
11612
0
  bool IsInvalid = false;
11613
0
  bool IsStd = false;
11614
0
  bool AddToKnown = false;
11615
0
  Scope *DeclRegionScope = NamespcScope->getParent();
11616
11617
0
  NamespaceDecl *PrevNS = nullptr;
11618
0
  if (II) {
11619
    // C++ [namespace.std]p7:
11620
    //   A translation unit shall not declare namespace std to be an inline
11621
    //   namespace (9.8.2).
11622
    //
11623
    // Precondition: the std namespace is in the file scope and is declared to
11624
    // be inline
11625
0
    auto DiagnoseInlineStdNS = [&]() {
11626
0
      assert(IsInline && II->isStr("std") &&
11627
0
             CurContext->getRedeclContext()->isTranslationUnit() &&
11628
0
             "Precondition of DiagnoseInlineStdNS not met");
11629
0
      Diag(InlineLoc, diag::err_inline_namespace_std)
11630
0
          << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6));
11631
0
      IsInline = false;
11632
0
    };
11633
    // C++ [namespace.def]p2:
11634
    //   The identifier in an original-namespace-definition shall not
11635
    //   have been previously defined in the declarative region in
11636
    //   which the original-namespace-definition appears. The
11637
    //   identifier in an original-namespace-definition is the name of
11638
    //   the namespace. Subsequently in that declarative region, it is
11639
    //   treated as an original-namespace-name.
11640
    //
11641
    // Since namespace names are unique in their scope, and we don't
11642
    // look through using directives, just look for any ordinary names
11643
    // as if by qualified name lookup.
11644
0
    LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11645
0
                   ForExternalRedeclaration);
11646
0
    LookupQualifiedName(R, CurContext->getRedeclContext());
11647
0
    NamedDecl *PrevDecl =
11648
0
        R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11649
0
    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11650
11651
0
    if (PrevNS) {
11652
      // This is an extended namespace definition.
11653
0
      if (IsInline && II->isStr("std") &&
11654
0
          CurContext->getRedeclContext()->isTranslationUnit())
11655
0
        DiagnoseInlineStdNS();
11656
0
      else if (IsInline != PrevNS->isInline())
11657
0
        DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11658
0
                                        &IsInline, PrevNS);
11659
0
    } else if (PrevDecl) {
11660
      // This is an invalid name redefinition.
11661
0
      Diag(Loc, diag::err_redefinition_different_kind)
11662
0
        << II;
11663
0
      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11664
0
      IsInvalid = true;
11665
      // Continue on to push Namespc as current DeclContext and return it.
11666
0
    } else if (II->isStr("std") &&
11667
0
               CurContext->getRedeclContext()->isTranslationUnit()) {
11668
0
      if (IsInline)
11669
0
        DiagnoseInlineStdNS();
11670
      // This is the first "real" definition of the namespace "std", so update
11671
      // our cache of the "std" namespace to point at this definition.
11672
0
      PrevNS = getStdNamespace();
11673
0
      IsStd = true;
11674
0
      AddToKnown = !IsInline;
11675
0
    } else {
11676
      // We've seen this namespace for the first time.
11677
0
      AddToKnown = !IsInline;
11678
0
    }
11679
0
  } else {
11680
    // Anonymous namespaces.
11681
11682
    // Determine whether the parent already has an anonymous namespace.
11683
0
    DeclContext *Parent = CurContext->getRedeclContext();
11684
0
    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11685
0
      PrevNS = TU->getAnonymousNamespace();
11686
0
    } else {
11687
0
      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11688
0
      PrevNS = ND->getAnonymousNamespace();
11689
0
    }
11690
11691
0
    if (PrevNS && IsInline != PrevNS->isInline())
11692
0
      DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11693
0
                                      &IsInline, PrevNS);
11694
0
  }
11695
11696
0
  NamespaceDecl *Namespc = NamespaceDecl::Create(
11697
0
      Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11698
0
  if (IsInvalid)
11699
0
    Namespc->setInvalidDecl();
11700
11701
0
  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11702
0
  AddPragmaAttributes(DeclRegionScope, Namespc);
11703
11704
  // FIXME: Should we be merging attributes?
11705
0
  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11706
0
    PushNamespaceVisibilityAttr(Attr, Loc);
11707
11708
0
  if (IsStd)
11709
0
    StdNamespace = Namespc;
11710
0
  if (AddToKnown)
11711
0
    KnownNamespaces[Namespc] = false;
11712
11713
0
  if (II) {
11714
0
    PushOnScopeChains(Namespc, DeclRegionScope);
11715
0
  } else {
11716
    // Link the anonymous namespace into its parent.
11717
0
    DeclContext *Parent = CurContext->getRedeclContext();
11718
0
    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11719
0
      TU->setAnonymousNamespace(Namespc);
11720
0
    } else {
11721
0
      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11722
0
    }
11723
11724
0
    CurContext->addDecl(Namespc);
11725
11726
    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
11727
    //   behaves as if it were replaced by
11728
    //     namespace unique { /* empty body */ }
11729
    //     using namespace unique;
11730
    //     namespace unique { namespace-body }
11731
    //   where all occurrences of 'unique' in a translation unit are
11732
    //   replaced by the same identifier and this identifier differs
11733
    //   from all other identifiers in the entire program.
11734
11735
    // We just create the namespace with an empty name and then add an
11736
    // implicit using declaration, just like the standard suggests.
11737
    //
11738
    // CodeGen enforces the "universally unique" aspect by giving all
11739
    // declarations semantically contained within an anonymous
11740
    // namespace internal linkage.
11741
11742
0
    if (!PrevNS) {
11743
0
      UD = UsingDirectiveDecl::Create(Context, Parent,
11744
0
                                      /* 'using' */ LBrace,
11745
0
                                      /* 'namespace' */ SourceLocation(),
11746
0
                                      /* qualifier */ NestedNameSpecifierLoc(),
11747
0
                                      /* identifier */ SourceLocation(),
11748
0
                                      Namespc,
11749
0
                                      /* Ancestor */ Parent);
11750
0
      UD->setImplicit();
11751
0
      Parent->addDecl(UD);
11752
0
    }
11753
0
  }
11754
11755
0
  ActOnDocumentableDecl(Namespc);
11756
11757
  // Although we could have an invalid decl (i.e. the namespace name is a
11758
  // redefinition), push it as current DeclContext and try to continue parsing.
11759
  // FIXME: We should be able to push Namespc here, so that the each DeclContext
11760
  // for the namespace has the declarations that showed up in that particular
11761
  // namespace definition.
11762
0
  PushDeclContext(NamespcScope, Namespc);
11763
0
  return Namespc;
11764
0
}
11765
11766
/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11767
/// is a namespace alias, returns the namespace it points to.
11768
0
static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11769
0
  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11770
0
    return AD->getNamespace();
11771
0
  return dyn_cast_or_null<NamespaceDecl>(D);
11772
0
}
11773
11774
/// ActOnFinishNamespaceDef - This callback is called after a namespace is
11775
/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11776
0
void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11777
0
  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11778
0
  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11779
0
  Namespc->setRBraceLoc(RBrace);
11780
0
  PopDeclContext();
11781
0
  if (Namespc->hasAttr<VisibilityAttr>())
11782
0
    PopPragmaVisibility(true, RBrace);
11783
  // If this namespace contains an export-declaration, export it now.
11784
0
  if (DeferredExportedNamespaces.erase(Namespc))
11785
0
    Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11786
0
}
11787
11788
0
CXXRecordDecl *Sema::getStdBadAlloc() const {
11789
0
  return cast_or_null<CXXRecordDecl>(
11790
0
                                  StdBadAlloc.get(Context.getExternalSource()));
11791
0
}
11792
11793
0
EnumDecl *Sema::getStdAlignValT() const {
11794
0
  return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11795
0
}
11796
11797
0
NamespaceDecl *Sema::getStdNamespace() const {
11798
0
  return cast_or_null<NamespaceDecl>(
11799
0
                                 StdNamespace.get(Context.getExternalSource()));
11800
0
}
11801
namespace {
11802
11803
enum UnsupportedSTLSelect {
11804
  USS_InvalidMember,
11805
  USS_MissingMember,
11806
  USS_NonTrivial,
11807
  USS_Other
11808
};
11809
11810
struct InvalidSTLDiagnoser {
11811
  Sema &S;
11812
  SourceLocation Loc;
11813
  QualType TyForDiags;
11814
11815
  QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11816
0
                      const VarDecl *VD = nullptr) {
11817
0
    {
11818
0
      auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11819
0
               << TyForDiags << ((int)Sel);
11820
0
      if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11821
0
        assert(!Name.empty());
11822
0
        D << Name;
11823
0
      }
11824
0
    }
11825
0
    if (Sel == USS_InvalidMember) {
11826
0
      S.Diag(VD->getLocation(), diag::note_var_declared_here)
11827
0
          << VD << VD->getSourceRange();
11828
0
    }
11829
0
    return QualType();
11830
0
  }
11831
};
11832
} // namespace
11833
11834
QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11835
                                           SourceLocation Loc,
11836
0
                                           ComparisonCategoryUsage Usage) {
11837
0
  assert(getLangOpts().CPlusPlus &&
11838
0
         "Looking for comparison category type outside of C++.");
11839
11840
  // Use an elaborated type for diagnostics which has a name containing the
11841
  // prepended 'std' namespace but not any inline namespace names.
11842
0
  auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11843
0
    auto *NNS =
11844
0
        NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11845
0
    return Context.getElaboratedType(ElaboratedTypeKeyword::None, NNS,
11846
0
                                     Info->getType());
11847
0
  };
11848
11849
  // Check if we've already successfully checked the comparison category type
11850
  // before. If so, skip checking it again.
11851
0
  ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11852
0
  if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11853
    // The only thing we need to check is that the type has a reachable
11854
    // definition in the current context.
11855
0
    if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11856
0
      return QualType();
11857
11858
0
    return Info->getType();
11859
0
  }
11860
11861
  // If lookup failed
11862
0
  if (!Info) {
11863
0
    std::string NameForDiags = "std::";
11864
0
    NameForDiags += ComparisonCategories::getCategoryString(Kind);
11865
0
    Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11866
0
        << NameForDiags << (int)Usage;
11867
0
    return QualType();
11868
0
  }
11869
11870
0
  assert(Info->Kind == Kind);
11871
0
  assert(Info->Record);
11872
11873
  // Update the Record decl in case we encountered a forward declaration on our
11874
  // first pass. FIXME: This is a bit of a hack.
11875
0
  if (Info->Record->hasDefinition())
11876
0
    Info->Record = Info->Record->getDefinition();
11877
11878
0
  if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11879
0
    return QualType();
11880
11881
0
  InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11882
11883
0
  if (!Info->Record->isTriviallyCopyable())
11884
0
    return UnsupportedSTLError(USS_NonTrivial);
11885
11886
0
  for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11887
0
    CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11888
    // Tolerate empty base classes.
11889
0
    if (Base->isEmpty())
11890
0
      continue;
11891
    // Reject STL implementations which have at least one non-empty base.
11892
0
    return UnsupportedSTLError();
11893
0
  }
11894
11895
  // Check that the STL has implemented the types using a single integer field.
11896
  // This expectation allows better codegen for builtin operators. We require:
11897
  //   (1) The class has exactly one field.
11898
  //   (2) The field is an integral or enumeration type.
11899
0
  auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11900
0
  if (std::distance(FIt, FEnd) != 1 ||
11901
0
      !FIt->getType()->isIntegralOrEnumerationType()) {
11902
0
    return UnsupportedSTLError();
11903
0
  }
11904
11905
  // Build each of the require values and store them in Info.
11906
0
  for (ComparisonCategoryResult CCR :
11907
0
       ComparisonCategories::getPossibleResultsForType(Kind)) {
11908
0
    StringRef MemName = ComparisonCategories::getResultString(CCR);
11909
0
    ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11910
11911
0
    if (!ValInfo)
11912
0
      return UnsupportedSTLError(USS_MissingMember, MemName);
11913
11914
0
    VarDecl *VD = ValInfo->VD;
11915
0
    assert(VD && "should not be null!");
11916
11917
    // Attempt to diagnose reasons why the STL definition of this type
11918
    // might be foobar, including it failing to be a constant expression.
11919
    // TODO Handle more ways the lookup or result can be invalid.
11920
0
    if (!VD->isStaticDataMember() ||
11921
0
        !VD->isUsableInConstantExpressions(Context))
11922
0
      return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11923
11924
    // Attempt to evaluate the var decl as a constant expression and extract
11925
    // the value of its first field as a ICE. If this fails, the STL
11926
    // implementation is not supported.
11927
0
    if (!ValInfo->hasValidIntValue())
11928
0
      return UnsupportedSTLError();
11929
11930
0
    MarkVariableReferenced(Loc, VD);
11931
0
  }
11932
11933
  // We've successfully built the required types and expressions. Update
11934
  // the cache and return the newly cached value.
11935
0
  FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11936
0
  return Info->getType();
11937
0
}
11938
11939
/// Retrieve the special "std" namespace, which may require us to
11940
/// implicitly define the namespace.
11941
0
NamespaceDecl *Sema::getOrCreateStdNamespace() {
11942
0
  if (!StdNamespace) {
11943
    // The "std" namespace has not yet been defined, so build one implicitly.
11944
0
    StdNamespace = NamespaceDecl::Create(
11945
0
        Context, Context.getTranslationUnitDecl(),
11946
0
        /*Inline=*/false, SourceLocation(), SourceLocation(),
11947
0
        &PP.getIdentifierTable().get("std"),
11948
0
        /*PrevDecl=*/nullptr, /*Nested=*/false);
11949
0
    getStdNamespace()->setImplicit(true);
11950
    // We want the created NamespaceDecl to be available for redeclaration
11951
    // lookups, but not for regular name lookups.
11952
0
    Context.getTranslationUnitDecl()->addDecl(getStdNamespace());
11953
0
    getStdNamespace()->clearIdentifierNamespace();
11954
0
  }
11955
11956
0
  return getStdNamespace();
11957
0
}
11958
11959
0
bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11960
0
  assert(getLangOpts().CPlusPlus &&
11961
0
         "Looking for std::initializer_list outside of C++.");
11962
11963
  // We're looking for implicit instantiations of
11964
  // template <typename E> class std::initializer_list.
11965
11966
0
  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11967
0
    return false;
11968
11969
0
  ClassTemplateDecl *Template = nullptr;
11970
0
  const TemplateArgument *Arguments = nullptr;
11971
11972
0
  if (const RecordType *RT = Ty->getAs<RecordType>()) {
11973
11974
0
    ClassTemplateSpecializationDecl *Specialization =
11975
0
        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11976
0
    if (!Specialization)
11977
0
      return false;
11978
11979
0
    Template = Specialization->getSpecializedTemplate();
11980
0
    Arguments = Specialization->getTemplateArgs().data();
11981
0
  } else if (const TemplateSpecializationType *TST =
11982
0
                 Ty->getAs<TemplateSpecializationType>()) {
11983
0
    Template = dyn_cast_or_null<ClassTemplateDecl>(
11984
0
        TST->getTemplateName().getAsTemplateDecl());
11985
0
    Arguments = TST->template_arguments().begin();
11986
0
  }
11987
0
  if (!Template)
11988
0
    return false;
11989
11990
0
  if (!StdInitializerList) {
11991
    // Haven't recognized std::initializer_list yet, maybe this is it.
11992
0
    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11993
0
    if (TemplateClass->getIdentifier() !=
11994
0
            &PP.getIdentifierTable().get("initializer_list") ||
11995
0
        !getStdNamespace()->InEnclosingNamespaceSetOf(
11996
0
            TemplateClass->getDeclContext()))
11997
0
      return false;
11998
    // This is a template called std::initializer_list, but is it the right
11999
    // template?
12000
0
    TemplateParameterList *Params = Template->getTemplateParameters();
12001
0
    if (Params->getMinRequiredArguments() != 1)
12002
0
      return false;
12003
0
    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
12004
0
      return false;
12005
12006
    // It's the right template.
12007
0
    StdInitializerList = Template;
12008
0
  }
12009
12010
0
  if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
12011
0
    return false;
12012
12013
  // This is an instance of std::initializer_list. Find the argument type.
12014
0
  if (Element)
12015
0
    *Element = Arguments[0].getAsType();
12016
0
  return true;
12017
0
}
12018
12019
0
static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
12020
0
  NamespaceDecl *Std = S.getStdNamespace();
12021
0
  if (!Std) {
12022
0
    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12023
0
    return nullptr;
12024
0
  }
12025
12026
0
  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
12027
0
                      Loc, Sema::LookupOrdinaryName);
12028
0
  if (!S.LookupQualifiedName(Result, Std)) {
12029
0
    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
12030
0
    return nullptr;
12031
0
  }
12032
0
  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12033
0
  if (!Template) {
12034
0
    Result.suppressDiagnostics();
12035
    // We found something weird. Complain about the first thing we found.
12036
0
    NamedDecl *Found = *Result.begin();
12037
0
    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
12038
0
    return nullptr;
12039
0
  }
12040
12041
  // We found some template called std::initializer_list. Now verify that it's
12042
  // correct.
12043
0
  TemplateParameterList *Params = Template->getTemplateParameters();
12044
0
  if (Params->getMinRequiredArguments() != 1 ||
12045
0
      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
12046
0
    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
12047
0
    return nullptr;
12048
0
  }
12049
12050
0
  return Template;
12051
0
}
12052
12053
0
QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
12054
0
  if (!StdInitializerList) {
12055
0
    StdInitializerList = LookupStdInitializerList(*this, Loc);
12056
0
    if (!StdInitializerList)
12057
0
      return QualType();
12058
0
  }
12059
12060
0
  TemplateArgumentListInfo Args(Loc, Loc);
12061
0
  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
12062
0
                                       Context.getTrivialTypeSourceInfo(Element,
12063
0
                                                                        Loc)));
12064
0
  return Context.getElaboratedType(
12065
0
      ElaboratedTypeKeyword::None,
12066
0
      NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()),
12067
0
      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
12068
0
}
12069
12070
0
bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
12071
  // C++ [dcl.init.list]p2:
12072
  //   A constructor is an initializer-list constructor if its first parameter
12073
  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
12074
  //   std::initializer_list<E> for some type E, and either there are no other
12075
  //   parameters or else all other parameters have default arguments.
12076
0
  if (!Ctor->hasOneParamOrDefaultArgs())
12077
0
    return false;
12078
12079
0
  QualType ArgType = Ctor->getParamDecl(0)->getType();
12080
0
  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12081
0
    ArgType = RT->getPointeeType().getUnqualifiedType();
12082
12083
0
  return isStdInitializerList(ArgType, nullptr);
12084
0
}
12085
12086
/// Determine whether a using statement is in a context where it will be
12087
/// apply in all contexts.
12088
0
static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
12089
0
  switch (CurContext->getDeclKind()) {
12090
0
    case Decl::TranslationUnit:
12091
0
      return true;
12092
0
    case Decl::LinkageSpec:
12093
0
      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
12094
0
    default:
12095
0
      return false;
12096
0
  }
12097
0
}
12098
12099
namespace {
12100
12101
// Callback to only accept typo corrections that are namespaces.
12102
class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12103
public:
12104
0
  bool ValidateCandidate(const TypoCorrection &candidate) override {
12105
0
    if (NamedDecl *ND = candidate.getCorrectionDecl())
12106
0
      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
12107
0
    return false;
12108
0
  }
12109
12110
0
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
12111
0
    return std::make_unique<NamespaceValidatorCCC>(*this);
12112
0
  }
12113
};
12114
12115
}
12116
12117
static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12118
0
                                       Sema &S) {
12119
0
  auto *ND = cast<NamespaceDecl>(Corrected.getFoundDecl());
12120
0
  Module *M = ND->getOwningModule();
12121
0
  assert(M && "hidden namespace definition not in a module?");
12122
12123
0
  if (M->isExplicitGlobalModule())
12124
0
    S.Diag(Corrected.getCorrectionRange().getBegin(),
12125
0
           diag::err_module_unimported_use_header)
12126
0
        << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12127
0
        << /*Header Name*/ false;
12128
0
  else
12129
0
    S.Diag(Corrected.getCorrectionRange().getBegin(),
12130
0
           diag::err_module_unimported_use)
12131
0
        << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12132
0
        << M->getTopLevelModuleName();
12133
0
}
12134
12135
static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
12136
                                       CXXScopeSpec &SS,
12137
                                       SourceLocation IdentLoc,
12138
0
                                       IdentifierInfo *Ident) {
12139
0
  R.clear();
12140
0
  NamespaceValidatorCCC CCC{};
12141
0
  if (TypoCorrection Corrected =
12142
0
          S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
12143
0
                        Sema::CTK_ErrorRecovery)) {
12144
    // Generally we find it is confusing more than helpful to diagnose the
12145
    // invisible namespace.
12146
    // See https://github.com/llvm/llvm-project/issues/73893.
12147
    //
12148
    // However, we should diagnose when the users are trying to using an
12149
    // invisible namespace. So we handle the case specially here.
12150
0
    if (isa_and_nonnull<NamespaceDecl>(Corrected.getFoundDecl()) &&
12151
0
        Corrected.requiresImport()) {
12152
0
      DiagnoseInvisibleNamespace(Corrected, S);
12153
0
    } else if (DeclContext *DC = S.computeDeclContext(SS, false)) {
12154
0
      std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
12155
0
      bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
12156
0
                              Ident->getName().equals(CorrectedStr);
12157
0
      S.diagnoseTypo(Corrected,
12158
0
                     S.PDiag(diag::err_using_directive_member_suggest)
12159
0
                       << Ident << DC << DroppedSpecifier << SS.getRange(),
12160
0
                     S.PDiag(diag::note_namespace_defined_here));
12161
0
    } else {
12162
0
      S.diagnoseTypo(Corrected,
12163
0
                     S.PDiag(diag::err_using_directive_suggest) << Ident,
12164
0
                     S.PDiag(diag::note_namespace_defined_here));
12165
0
    }
12166
0
    R.addDecl(Corrected.getFoundDecl());
12167
0
    return true;
12168
0
  }
12169
0
  return false;
12170
0
}
12171
12172
Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
12173
                                SourceLocation NamespcLoc, CXXScopeSpec &SS,
12174
                                SourceLocation IdentLoc,
12175
                                IdentifierInfo *NamespcName,
12176
0
                                const ParsedAttributesView &AttrList) {
12177
0
  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12178
0
  assert(NamespcName && "Invalid NamespcName.");
12179
0
  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12180
12181
  // This can only happen along a recovery path.
12182
0
  while (S->isTemplateParamScope())
12183
0
    S = S->getParent();
12184
0
  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12185
12186
0
  UsingDirectiveDecl *UDir = nullptr;
12187
0
  NestedNameSpecifier *Qualifier = nullptr;
12188
0
  if (SS.isSet())
12189
0
    Qualifier = SS.getScopeRep();
12190
12191
  // Lookup namespace name.
12192
0
  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12193
0
  LookupParsedName(R, S, &SS);
12194
0
  if (R.isAmbiguous())
12195
0
    return nullptr;
12196
12197
0
  if (R.empty()) {
12198
0
    R.clear();
12199
    // Allow "using namespace std;" or "using namespace ::std;" even if
12200
    // "std" hasn't been defined yet, for GCC compatibility.
12201
0
    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
12202
0
        NamespcName->isStr("std")) {
12203
0
      Diag(IdentLoc, diag::ext_using_undefined_std);
12204
0
      R.addDecl(getOrCreateStdNamespace());
12205
0
      R.resolveKind();
12206
0
    }
12207
    // Otherwise, attempt typo correction.
12208
0
    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
12209
0
  }
12210
12211
0
  if (!R.empty()) {
12212
0
    NamedDecl *Named = R.getRepresentativeDecl();
12213
0
    NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12214
0
    assert(NS && "expected namespace decl");
12215
12216
    // The use of a nested name specifier may trigger deprecation warnings.
12217
0
    DiagnoseUseOfDecl(Named, IdentLoc);
12218
12219
    // C++ [namespace.udir]p1:
12220
    //   A using-directive specifies that the names in the nominated
12221
    //   namespace can be used in the scope in which the
12222
    //   using-directive appears after the using-directive. During
12223
    //   unqualified name lookup (3.4.1), the names appear as if they
12224
    //   were declared in the nearest enclosing namespace which
12225
    //   contains both the using-directive and the nominated
12226
    //   namespace. [Note: in this context, "contains" means "contains
12227
    //   directly or indirectly". ]
12228
12229
    // Find enclosing context containing both using-directive and
12230
    // nominated namespace.
12231
0
    DeclContext *CommonAncestor = NS;
12232
0
    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
12233
0
      CommonAncestor = CommonAncestor->getParent();
12234
12235
0
    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
12236
0
                                      SS.getWithLocInContext(Context),
12237
0
                                      IdentLoc, Named, CommonAncestor);
12238
12239
0
    if (IsUsingDirectiveInToplevelContext(CurContext) &&
12240
0
        !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
12241
0
      Diag(IdentLoc, diag::warn_using_directive_in_header);
12242
0
    }
12243
12244
0
    PushUsingDirective(S, UDir);
12245
0
  } else {
12246
0
    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12247
0
  }
12248
12249
0
  if (UDir)
12250
0
    ProcessDeclAttributeList(S, UDir, AttrList);
12251
12252
0
  return UDir;
12253
0
}
12254
12255
0
void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12256
  // If the scope has an associated entity and the using directive is at
12257
  // namespace or translation unit scope, add the UsingDirectiveDecl into
12258
  // its lookup structure so qualified name lookup can find it.
12259
0
  DeclContext *Ctx = S->getEntity();
12260
0
  if (Ctx && !Ctx->isFunctionOrMethod())
12261
0
    Ctx->addDecl(UDir);
12262
0
  else
12263
    // Otherwise, it is at block scope. The using-directives will affect lookup
12264
    // only to the end of the scope.
12265
0
    S->PushUsingDirective(UDir);
12266
0
}
12267
12268
Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12269
                                  SourceLocation UsingLoc,
12270
                                  SourceLocation TypenameLoc, CXXScopeSpec &SS,
12271
                                  UnqualifiedId &Name,
12272
                                  SourceLocation EllipsisLoc,
12273
0
                                  const ParsedAttributesView &AttrList) {
12274
0
  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12275
12276
0
  if (SS.isEmpty()) {
12277
0
    Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
12278
0
    return nullptr;
12279
0
  }
12280
12281
0
  switch (Name.getKind()) {
12282
0
  case UnqualifiedIdKind::IK_ImplicitSelfParam:
12283
0
  case UnqualifiedIdKind::IK_Identifier:
12284
0
  case UnqualifiedIdKind::IK_OperatorFunctionId:
12285
0
  case UnqualifiedIdKind::IK_LiteralOperatorId:
12286
0
  case UnqualifiedIdKind::IK_ConversionFunctionId:
12287
0
    break;
12288
12289
0
  case UnqualifiedIdKind::IK_ConstructorName:
12290
0
  case UnqualifiedIdKind::IK_ConstructorTemplateId:
12291
    // C++11 inheriting constructors.
12292
0
    Diag(Name.getBeginLoc(),
12293
0
         getLangOpts().CPlusPlus11
12294
0
             ? diag::warn_cxx98_compat_using_decl_constructor
12295
0
             : diag::err_using_decl_constructor)
12296
0
        << SS.getRange();
12297
12298
0
    if (getLangOpts().CPlusPlus11) break;
12299
12300
0
    return nullptr;
12301
12302
0
  case UnqualifiedIdKind::IK_DestructorName:
12303
0
    Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
12304
0
    return nullptr;
12305
12306
0
  case UnqualifiedIdKind::IK_TemplateId:
12307
0
    Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
12308
0
        << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12309
0
    return nullptr;
12310
12311
0
  case UnqualifiedIdKind::IK_DeductionGuideName:
12312
0
    llvm_unreachable("cannot parse qualified deduction guide name");
12313
0
  }
12314
12315
0
  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12316
0
  DeclarationName TargetName = TargetNameInfo.getName();
12317
0
  if (!TargetName)
12318
0
    return nullptr;
12319
12320
  // Warn about access declarations.
12321
0
  if (UsingLoc.isInvalid()) {
12322
0
    Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
12323
0
                                 ? diag::err_access_decl
12324
0
                                 : diag::warn_access_decl_deprecated)
12325
0
        << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
12326
0
  }
12327
12328
0
  if (EllipsisLoc.isInvalid()) {
12329
0
    if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
12330
0
        DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
12331
0
      return nullptr;
12332
0
  } else {
12333
0
    if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
12334
0
        !TargetNameInfo.containsUnexpandedParameterPack()) {
12335
0
      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
12336
0
        << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12337
0
      EllipsisLoc = SourceLocation();
12338
0
    }
12339
0
  }
12340
12341
0
  NamedDecl *UD =
12342
0
      BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
12343
0
                            SS, TargetNameInfo, EllipsisLoc, AttrList,
12344
0
                            /*IsInstantiation*/ false,
12345
0
                            AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
12346
0
  if (UD)
12347
0
    PushOnScopeChains(UD, S, /*AddToContext*/ false);
12348
12349
0
  return UD;
12350
0
}
12351
12352
Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12353
                                      SourceLocation UsingLoc,
12354
                                      SourceLocation EnumLoc,
12355
                                      SourceLocation IdentLoc,
12356
0
                                      IdentifierInfo &II, CXXScopeSpec *SS) {
12357
0
  assert(!SS->isInvalid() && "ScopeSpec is invalid");
12358
0
  TypeSourceInfo *TSI = nullptr;
12359
0
  QualType EnumTy = GetTypeFromParser(
12360
0
      getTypeName(II, IdentLoc, S, SS, /*isClassName=*/false,
12361
0
                  /*HasTrailingDot=*/false,
12362
0
                  /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false,
12363
0
                  /*WantNontrivialTypeSourceInfo=*/true),
12364
0
      &TSI);
12365
0
  if (EnumTy.isNull()) {
12366
0
    Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS)
12367
0
                       ? diag::err_using_enum_is_dependent
12368
0
                       : diag::err_unknown_typename)
12369
0
        << II.getName()
12370
0
        << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, IdentLoc);
12371
0
    return nullptr;
12372
0
  }
12373
12374
0
  auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
12375
0
  if (!Enum) {
12376
0
    Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
12377
0
    return nullptr;
12378
0
  }
12379
12380
0
  if (auto *Def = Enum->getDefinition())
12381
0
    Enum = Def;
12382
12383
0
  if (TSI == nullptr)
12384
0
    TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
12385
12386
0
  auto *UD =
12387
0
      BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
12388
12389
0
  if (UD)
12390
0
    PushOnScopeChains(UD, S, /*AddToContext*/ false);
12391
12392
0
  return UD;
12393
0
}
12394
12395
/// Determine whether a using declaration considers the given
12396
/// declarations as "equivalent", e.g., if they are redeclarations of
12397
/// the same entity or are both typedefs of the same type.
12398
static bool
12399
0
IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12400
0
  if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12401
0
    return true;
12402
12403
0
  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
12404
0
    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
12405
0
      return Context.hasSameType(TD1->getUnderlyingType(),
12406
0
                                 TD2->getUnderlyingType());
12407
12408
  // Two using_if_exists using-declarations are equivalent if both are
12409
  // unresolved.
12410
0
  if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
12411
0
      isa<UnresolvedUsingIfExistsDecl>(D2))
12412
0
    return true;
12413
12414
0
  return false;
12415
0
}
12416
12417
12418
/// Determines whether to create a using shadow decl for a particular
12419
/// decl, given the set of decls existing prior to this using lookup.
12420
bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12421
                                const LookupResult &Previous,
12422
0
                                UsingShadowDecl *&PrevShadow) {
12423
  // Diagnose finding a decl which is not from a base class of the
12424
  // current class.  We do this now because there are cases where this
12425
  // function will silently decide not to build a shadow decl, which
12426
  // will pre-empt further diagnostics.
12427
  //
12428
  // We don't need to do this in C++11 because we do the check once on
12429
  // the qualifier.
12430
  //
12431
  // FIXME: diagnose the following if we care enough:
12432
  //   struct A { int foo; };
12433
  //   struct B : A { using A::foo; };
12434
  //   template <class T> struct C : A {};
12435
  //   template <class T> struct D : C<T> { using B::foo; } // <---
12436
  // This is invalid (during instantiation) in C++03 because B::foo
12437
  // resolves to the using decl in B, which is not a base class of D<T>.
12438
  // We can't diagnose it immediately because C<T> is an unknown
12439
  // specialization. The UsingShadowDecl in D<T> then points directly
12440
  // to A::foo, which will look well-formed when we instantiate.
12441
  // The right solution is to not collapse the shadow-decl chain.
12442
0
  if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12443
0
    if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12444
0
      DeclContext *OrigDC = Orig->getDeclContext();
12445
12446
      // Handle enums and anonymous structs.
12447
0
      if (isa<EnumDecl>(OrigDC))
12448
0
        OrigDC = OrigDC->getParent();
12449
0
      CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12450
0
      while (OrigRec->isAnonymousStructOrUnion())
12451
0
        OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12452
12453
0
      if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12454
0
        if (OrigDC == CurContext) {
12455
0
          Diag(Using->getLocation(),
12456
0
               diag::err_using_decl_nested_name_specifier_is_current_class)
12457
0
              << Using->getQualifierLoc().getSourceRange();
12458
0
          Diag(Orig->getLocation(), diag::note_using_decl_target);
12459
0
          Using->setInvalidDecl();
12460
0
          return true;
12461
0
        }
12462
12463
0
        Diag(Using->getQualifierLoc().getBeginLoc(),
12464
0
             diag::err_using_decl_nested_name_specifier_is_not_base_class)
12465
0
            << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12466
0
            << Using->getQualifierLoc().getSourceRange();
12467
0
        Diag(Orig->getLocation(), diag::note_using_decl_target);
12468
0
        Using->setInvalidDecl();
12469
0
        return true;
12470
0
      }
12471
0
    }
12472
12473
0
  if (Previous.empty()) return false;
12474
12475
0
  NamedDecl *Target = Orig;
12476
0
  if (isa<UsingShadowDecl>(Target))
12477
0
    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12478
12479
  // If the target happens to be one of the previous declarations, we
12480
  // don't have a conflict.
12481
  //
12482
  // FIXME: but we might be increasing its access, in which case we
12483
  // should redeclare it.
12484
0
  NamedDecl *NonTag = nullptr, *Tag = nullptr;
12485
0
  bool FoundEquivalentDecl = false;
12486
0
  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12487
0
         I != E; ++I) {
12488
0
    NamedDecl *D = (*I)->getUnderlyingDecl();
12489
    // We can have UsingDecls in our Previous results because we use the same
12490
    // LookupResult for checking whether the UsingDecl itself is a valid
12491
    // redeclaration.
12492
0
    if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12493
0
      continue;
12494
12495
0
    if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12496
      // C++ [class.mem]p19:
12497
      //   If T is the name of a class, then [every named member other than
12498
      //   a non-static data member] shall have a name different from T
12499
0
      if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12500
0
          !isa<IndirectFieldDecl>(Target) &&
12501
0
          !isa<UnresolvedUsingValueDecl>(Target) &&
12502
0
          DiagnoseClassNameShadow(
12503
0
              CurContext,
12504
0
              DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12505
0
        return true;
12506
0
    }
12507
12508
0
    if (IsEquivalentForUsingDecl(Context, D, Target)) {
12509
0
      if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12510
0
        PrevShadow = Shadow;
12511
0
      FoundEquivalentDecl = true;
12512
0
    } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
12513
      // We don't conflict with an existing using shadow decl of an equivalent
12514
      // declaration, but we're not a redeclaration of it.
12515
0
      FoundEquivalentDecl = true;
12516
0
    }
12517
12518
0
    if (isVisible(D))
12519
0
      (isa<TagDecl>(D) ? Tag : NonTag) = D;
12520
0
  }
12521
12522
0
  if (FoundEquivalentDecl)
12523
0
    return false;
12524
12525
  // Always emit a diagnostic for a mismatch between an unresolved
12526
  // using_if_exists and a resolved using declaration in either direction.
12527
0
  if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12528
0
      (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12529
0
    if (!NonTag && !Tag)
12530
0
      return false;
12531
0
    Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12532
0
    Diag(Target->getLocation(), diag::note_using_decl_target);
12533
0
    Diag((NonTag ? NonTag : Tag)->getLocation(),
12534
0
         diag::note_using_decl_conflict);
12535
0
    BUD->setInvalidDecl();
12536
0
    return true;
12537
0
  }
12538
12539
0
  if (FunctionDecl *FD = Target->getAsFunction()) {
12540
0
    NamedDecl *OldDecl = nullptr;
12541
0
    switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12542
0
                          /*IsForUsingDecl*/ true)) {
12543
0
    case Ovl_Overload:
12544
0
      return false;
12545
12546
0
    case Ovl_NonFunction:
12547
0
      Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12548
0
      break;
12549
12550
    // We found a decl with the exact signature.
12551
0
    case Ovl_Match:
12552
      // If we're in a record, we want to hide the target, so we
12553
      // return true (without a diagnostic) to tell the caller not to
12554
      // build a shadow decl.
12555
0
      if (CurContext->isRecord())
12556
0
        return true;
12557
12558
      // If we're not in a record, this is an error.
12559
0
      Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12560
0
      break;
12561
0
    }
12562
12563
0
    Diag(Target->getLocation(), diag::note_using_decl_target);
12564
0
    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12565
0
    BUD->setInvalidDecl();
12566
0
    return true;
12567
0
  }
12568
12569
  // Target is not a function.
12570
12571
0
  if (isa<TagDecl>(Target)) {
12572
    // No conflict between a tag and a non-tag.
12573
0
    if (!Tag) return false;
12574
12575
0
    Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12576
0
    Diag(Target->getLocation(), diag::note_using_decl_target);
12577
0
    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12578
0
    BUD->setInvalidDecl();
12579
0
    return true;
12580
0
  }
12581
12582
  // No conflict between a tag and a non-tag.
12583
0
  if (!NonTag) return false;
12584
12585
0
  Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12586
0
  Diag(Target->getLocation(), diag::note_using_decl_target);
12587
0
  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12588
0
  BUD->setInvalidDecl();
12589
0
  return true;
12590
0
}
12591
12592
/// Determine whether a direct base class is a virtual base class.
12593
0
static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12594
0
  if (!Derived->getNumVBases())
12595
0
    return false;
12596
0
  for (auto &B : Derived->bases())
12597
0
    if (B.getType()->getAsCXXRecordDecl() == Base)
12598
0
      return B.isVirtual();
12599
0
  llvm_unreachable("not a direct base class");
12600
0
}
12601
12602
/// Builds a shadow declaration corresponding to a 'using' declaration.
12603
UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12604
                                            NamedDecl *Orig,
12605
0
                                            UsingShadowDecl *PrevDecl) {
12606
  // If we resolved to another shadow declaration, just coalesce them.
12607
0
  NamedDecl *Target = Orig;
12608
0
  if (isa<UsingShadowDecl>(Target)) {
12609
0
    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12610
0
    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12611
0
  }
12612
12613
0
  NamedDecl *NonTemplateTarget = Target;
12614
0
  if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12615
0
    NonTemplateTarget = TargetTD->getTemplatedDecl();
12616
12617
0
  UsingShadowDecl *Shadow;
12618
0
  if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12619
0
    UsingDecl *Using = cast<UsingDecl>(BUD);
12620
0
    bool IsVirtualBase =
12621
0
        isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12622
0
                            Using->getQualifier()->getAsRecordDecl());
12623
0
    Shadow = ConstructorUsingShadowDecl::Create(
12624
0
        Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12625
0
  } else {
12626
0
    Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12627
0
                                     Target->getDeclName(), BUD, Target);
12628
0
  }
12629
0
  BUD->addShadowDecl(Shadow);
12630
12631
0
  Shadow->setAccess(BUD->getAccess());
12632
0
  if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12633
0
    Shadow->setInvalidDecl();
12634
12635
0
  Shadow->setPreviousDecl(PrevDecl);
12636
12637
0
  if (S)
12638
0
    PushOnScopeChains(Shadow, S);
12639
0
  else
12640
0
    CurContext->addDecl(Shadow);
12641
12642
12643
0
  return Shadow;
12644
0
}
12645
12646
/// Hides a using shadow declaration.  This is required by the current
12647
/// using-decl implementation when a resolvable using declaration in a
12648
/// class is followed by a declaration which would hide or override
12649
/// one or more of the using decl's targets; for example:
12650
///
12651
///   struct Base { void foo(int); };
12652
///   struct Derived : Base {
12653
///     using Base::foo;
12654
///     void foo(int);
12655
///   };
12656
///
12657
/// The governing language is C++03 [namespace.udecl]p12:
12658
///
12659
///   When a using-declaration brings names from a base class into a
12660
///   derived class scope, member functions in the derived class
12661
///   override and/or hide member functions with the same name and
12662
///   parameter types in a base class (rather than conflicting).
12663
///
12664
/// There are two ways to implement this:
12665
///   (1) optimistically create shadow decls when they're not hidden
12666
///       by existing declarations, or
12667
///   (2) don't create any shadow decls (or at least don't make them
12668
///       visible) until we've fully parsed/instantiated the class.
12669
/// The problem with (1) is that we might have to retroactively remove
12670
/// a shadow decl, which requires several O(n) operations because the
12671
/// decl structures are (very reasonably) not designed for removal.
12672
/// (2) avoids this but is very fiddly and phase-dependent.
12673
0
void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12674
0
  if (Shadow->getDeclName().getNameKind() ==
12675
0
        DeclarationName::CXXConversionFunctionName)
12676
0
    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12677
12678
  // Remove it from the DeclContext...
12679
0
  Shadow->getDeclContext()->removeDecl(Shadow);
12680
12681
  // ...and the scope, if applicable...
12682
0
  if (S) {
12683
0
    S->RemoveDecl(Shadow);
12684
0
    IdResolver.RemoveDecl(Shadow);
12685
0
  }
12686
12687
  // ...and the using decl.
12688
0
  Shadow->getIntroducer()->removeShadowDecl(Shadow);
12689
12690
  // TODO: complain somehow if Shadow was used.  It shouldn't
12691
  // be possible for this to happen, because...?
12692
0
}
12693
12694
/// Find the base specifier for a base class with the given type.
12695
static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12696
                                                QualType DesiredBase,
12697
0
                                                bool &AnyDependentBases) {
12698
  // Check whether the named type is a direct base class.
12699
0
  CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12700
0
    .getUnqualifiedType();
12701
0
  for (auto &Base : Derived->bases()) {
12702
0
    CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12703
0
    if (CanonicalDesiredBase == BaseType)
12704
0
      return &Base;
12705
0
    if (BaseType->isDependentType())
12706
0
      AnyDependentBases = true;
12707
0
  }
12708
0
  return nullptr;
12709
0
}
12710
12711
namespace {
12712
class UsingValidatorCCC final : public CorrectionCandidateCallback {
12713
public:
12714
  UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12715
                    NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12716
      : HasTypenameKeyword(HasTypenameKeyword),
12717
        IsInstantiation(IsInstantiation), OldNNS(NNS),
12718
0
        RequireMemberOf(RequireMemberOf) {}
12719
12720
0
  bool ValidateCandidate(const TypoCorrection &Candidate) override {
12721
0
    NamedDecl *ND = Candidate.getCorrectionDecl();
12722
12723
    // Keywords are not valid here.
12724
0
    if (!ND || isa<NamespaceDecl>(ND))
12725
0
      return false;
12726
12727
    // Completely unqualified names are invalid for a 'using' declaration.
12728
0
    if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12729
0
      return false;
12730
12731
    // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12732
    // reject.
12733
12734
0
    if (RequireMemberOf) {
12735
0
      auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12736
0
      if (FoundRecord && FoundRecord->isInjectedClassName()) {
12737
        // No-one ever wants a using-declaration to name an injected-class-name
12738
        // of a base class, unless they're declaring an inheriting constructor.
12739
0
        ASTContext &Ctx = ND->getASTContext();
12740
0
        if (!Ctx.getLangOpts().CPlusPlus11)
12741
0
          return false;
12742
0
        QualType FoundType = Ctx.getRecordType(FoundRecord);
12743
12744
        // Check that the injected-class-name is named as a member of its own
12745
        // type; we don't want to suggest 'using Derived::Base;', since that
12746
        // means something else.
12747
0
        NestedNameSpecifier *Specifier =
12748
0
            Candidate.WillReplaceSpecifier()
12749
0
                ? Candidate.getCorrectionSpecifier()
12750
0
                : OldNNS;
12751
0
        if (!Specifier->getAsType() ||
12752
0
            !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12753
0
          return false;
12754
12755
        // Check that this inheriting constructor declaration actually names a
12756
        // direct base class of the current class.
12757
0
        bool AnyDependentBases = false;
12758
0
        if (!findDirectBaseWithType(RequireMemberOf,
12759
0
                                    Ctx.getRecordType(FoundRecord),
12760
0
                                    AnyDependentBases) &&
12761
0
            !AnyDependentBases)
12762
0
          return false;
12763
0
      } else {
12764
0
        auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12765
0
        if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12766
0
          return false;
12767
12768
        // FIXME: Check that the base class member is accessible?
12769
0
      }
12770
0
    } else {
12771
0
      auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12772
0
      if (FoundRecord && FoundRecord->isInjectedClassName())
12773
0
        return false;
12774
0
    }
12775
12776
0
    if (isa<TypeDecl>(ND))
12777
0
      return HasTypenameKeyword || !IsInstantiation;
12778
12779
0
    return !HasTypenameKeyword;
12780
0
  }
12781
12782
0
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
12783
0
    return std::make_unique<UsingValidatorCCC>(*this);
12784
0
  }
12785
12786
private:
12787
  bool HasTypenameKeyword;
12788
  bool IsInstantiation;
12789
  NestedNameSpecifier *OldNNS;
12790
  CXXRecordDecl *RequireMemberOf;
12791
};
12792
} // end anonymous namespace
12793
12794
/// Remove decls we can't actually see from a lookup being used to declare
12795
/// shadow using decls.
12796
///
12797
/// \param S - The scope of the potential shadow decl
12798
/// \param Previous - The lookup of a potential shadow decl's name.
12799
0
void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12800
  // It is really dumb that we have to do this.
12801
0
  LookupResult::Filter F = Previous.makeFilter();
12802
0
  while (F.hasNext()) {
12803
0
    NamedDecl *D = F.next();
12804
0
    if (!isDeclInScope(D, CurContext, S))
12805
0
      F.erase();
12806
    // If we found a local extern declaration that's not ordinarily visible,
12807
    // and this declaration is being added to a non-block scope, ignore it.
12808
    // We're only checking for scope conflicts here, not also for violations
12809
    // of the linkage rules.
12810
0
    else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12811
0
             !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12812
0
      F.erase();
12813
0
  }
12814
0
  F.done();
12815
0
}
12816
12817
/// Builds a using declaration.
12818
///
12819
/// \param IsInstantiation - Whether this call arises from an
12820
///   instantiation of an unresolved using declaration.  We treat
12821
///   the lookup differently for these declarations.
12822
NamedDecl *Sema::BuildUsingDeclaration(
12823
    Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12824
    bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12825
    DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12826
    const ParsedAttributesView &AttrList, bool IsInstantiation,
12827
0
    bool IsUsingIfExists) {
12828
0
  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12829
0
  SourceLocation IdentLoc = NameInfo.getLoc();
12830
0
  assert(IdentLoc.isValid() && "Invalid TargetName location.");
12831
12832
  // FIXME: We ignore attributes for now.
12833
12834
  // For an inheriting constructor declaration, the name of the using
12835
  // declaration is the name of a constructor in this class, not in the
12836
  // base class.
12837
0
  DeclarationNameInfo UsingName = NameInfo;
12838
0
  if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12839
0
    if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12840
0
      UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12841
0
          Context.getCanonicalType(Context.getRecordType(RD))));
12842
12843
  // Do the redeclaration lookup in the current scope.
12844
0
  LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12845
0
                        ForVisibleRedeclaration);
12846
0
  Previous.setHideTags(false);
12847
0
  if (S) {
12848
0
    LookupName(Previous, S);
12849
12850
0
    FilterUsingLookup(S, Previous);
12851
0
  } else {
12852
0
    assert(IsInstantiation && "no scope in non-instantiation");
12853
0
    if (CurContext->isRecord())
12854
0
      LookupQualifiedName(Previous, CurContext);
12855
0
    else {
12856
      // No redeclaration check is needed here; in non-member contexts we
12857
      // diagnosed all possible conflicts with other using-declarations when
12858
      // building the template:
12859
      //
12860
      // For a dependent non-type using declaration, the only valid case is
12861
      // if we instantiate to a single enumerator. We check for conflicts
12862
      // between shadow declarations we introduce, and we check in the template
12863
      // definition for conflicts between a non-type using declaration and any
12864
      // other declaration, which together covers all cases.
12865
      //
12866
      // A dependent typename using declaration will never successfully
12867
      // instantiate, since it will always name a class member, so we reject
12868
      // that in the template definition.
12869
0
    }
12870
0
  }
12871
12872
  // Check for invalid redeclarations.
12873
0
  if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12874
0
                                  SS, IdentLoc, Previous))
12875
0
    return nullptr;
12876
12877
  // 'using_if_exists' doesn't make sense on an inherited constructor.
12878
0
  if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12879
0
                             DeclarationName::CXXConstructorName) {
12880
0
    Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12881
0
    return nullptr;
12882
0
  }
12883
12884
0
  DeclContext *LookupContext = computeDeclContext(SS);
12885
0
  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12886
0
  if (!LookupContext || EllipsisLoc.isValid()) {
12887
0
    NamedDecl *D;
12888
    // Dependent scope, or an unexpanded pack
12889
0
    if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12890
0
                                                  SS, NameInfo, IdentLoc))
12891
0
      return nullptr;
12892
12893
0
    if (HasTypenameKeyword) {
12894
      // FIXME: not all declaration name kinds are legal here
12895
0
      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12896
0
                                              UsingLoc, TypenameLoc,
12897
0
                                              QualifierLoc,
12898
0
                                              IdentLoc, NameInfo.getName(),
12899
0
                                              EllipsisLoc);
12900
0
    } else {
12901
0
      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12902
0
                                           QualifierLoc, NameInfo, EllipsisLoc);
12903
0
    }
12904
0
    D->setAccess(AS);
12905
0
    CurContext->addDecl(D);
12906
0
    ProcessDeclAttributeList(S, D, AttrList);
12907
0
    return D;
12908
0
  }
12909
12910
0
  auto Build = [&](bool Invalid) {
12911
0
    UsingDecl *UD =
12912
0
        UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12913
0
                          UsingName, HasTypenameKeyword);
12914
0
    UD->setAccess(AS);
12915
0
    CurContext->addDecl(UD);
12916
0
    ProcessDeclAttributeList(S, UD, AttrList);
12917
0
    UD->setInvalidDecl(Invalid);
12918
0
    return UD;
12919
0
  };
12920
0
  auto BuildInvalid = [&]{ return Build(true); };
12921
0
  auto BuildValid = [&]{ return Build(false); };
12922
12923
0
  if (RequireCompleteDeclContext(SS, LookupContext))
12924
0
    return BuildInvalid();
12925
12926
  // Look up the target name.
12927
0
  LookupResult R(*this, NameInfo, LookupOrdinaryName);
12928
12929
  // Unlike most lookups, we don't always want to hide tag
12930
  // declarations: tag names are visible through the using declaration
12931
  // even if hidden by ordinary names, *except* in a dependent context
12932
  // where they may be used by two-phase lookup.
12933
0
  if (!IsInstantiation)
12934
0
    R.setHideTags(false);
12935
12936
  // For the purposes of this lookup, we have a base object type
12937
  // equal to that of the current context.
12938
0
  if (CurContext->isRecord()) {
12939
0
    R.setBaseObjectType(
12940
0
                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12941
0
  }
12942
12943
0
  LookupQualifiedName(R, LookupContext);
12944
12945
  // Validate the context, now we have a lookup
12946
0
  if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12947
0
                              IdentLoc, &R))
12948
0
    return nullptr;
12949
12950
0
  if (R.empty() && IsUsingIfExists)
12951
0
    R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12952
0
                                                  UsingName.getName()),
12953
0
              AS_public);
12954
12955
  // Try to correct typos if possible. If constructor name lookup finds no
12956
  // results, that means the named class has no explicit constructors, and we
12957
  // suppressed declaring implicit ones (probably because it's dependent or
12958
  // invalid).
12959
0
  if (R.empty() &&
12960
0
      NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12961
    // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12962
    // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12963
    // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12964
0
    auto *II = NameInfo.getName().getAsIdentifierInfo();
12965
0
    if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12966
0
        CurContext->isStdNamespace() &&
12967
0
        isa<TranslationUnitDecl>(LookupContext) &&
12968
0
        getSourceManager().isInSystemHeader(UsingLoc))
12969
0
      return nullptr;
12970
0
    UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12971
0
                          dyn_cast<CXXRecordDecl>(CurContext));
12972
0
    if (TypoCorrection Corrected =
12973
0
            CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12974
0
                        CTK_ErrorRecovery)) {
12975
      // We reject candidates where DroppedSpecifier == true, hence the
12976
      // literal '0' below.
12977
0
      diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12978
0
                                << NameInfo.getName() << LookupContext << 0
12979
0
                                << SS.getRange());
12980
12981
      // If we picked a correction with no attached Decl we can't do anything
12982
      // useful with it, bail out.
12983
0
      NamedDecl *ND = Corrected.getCorrectionDecl();
12984
0
      if (!ND)
12985
0
        return BuildInvalid();
12986
12987
      // If we corrected to an inheriting constructor, handle it as one.
12988
0
      auto *RD = dyn_cast<CXXRecordDecl>(ND);
12989
0
      if (RD && RD->isInjectedClassName()) {
12990
        // The parent of the injected class name is the class itself.
12991
0
        RD = cast<CXXRecordDecl>(RD->getParent());
12992
12993
        // Fix up the information we'll use to build the using declaration.
12994
0
        if (Corrected.WillReplaceSpecifier()) {
12995
0
          NestedNameSpecifierLocBuilder Builder;
12996
0
          Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12997
0
                              QualifierLoc.getSourceRange());
12998
0
          QualifierLoc = Builder.getWithLocInContext(Context);
12999
0
        }
13000
13001
        // In this case, the name we introduce is the name of a derived class
13002
        // constructor.
13003
0
        auto *CurClass = cast<CXXRecordDecl>(CurContext);
13004
0
        UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13005
0
            Context.getCanonicalType(Context.getRecordType(CurClass))));
13006
0
        UsingName.setNamedTypeInfo(nullptr);
13007
0
        for (auto *Ctor : LookupConstructors(RD))
13008
0
          R.addDecl(Ctor);
13009
0
        R.resolveKind();
13010
0
      } else {
13011
        // FIXME: Pick up all the declarations if we found an overloaded
13012
        // function.
13013
0
        UsingName.setName(ND->getDeclName());
13014
0
        R.addDecl(ND);
13015
0
      }
13016
0
    } else {
13017
0
      Diag(IdentLoc, diag::err_no_member)
13018
0
        << NameInfo.getName() << LookupContext << SS.getRange();
13019
0
      return BuildInvalid();
13020
0
    }
13021
0
  }
13022
13023
0
  if (R.isAmbiguous())
13024
0
    return BuildInvalid();
13025
13026
0
  if (HasTypenameKeyword) {
13027
    // If we asked for a typename and got a non-type decl, error out.
13028
0
    if (!R.getAsSingle<TypeDecl>() &&
13029
0
        !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13030
0
      Diag(IdentLoc, diag::err_using_typename_non_type);
13031
0
      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
13032
0
        Diag((*I)->getUnderlyingDecl()->getLocation(),
13033
0
             diag::note_using_decl_target);
13034
0
      return BuildInvalid();
13035
0
    }
13036
0
  } else {
13037
    // If we asked for a non-typename and we got a type, error out,
13038
    // but only if this is an instantiation of an unresolved using
13039
    // decl.  Otherwise just silently find the type name.
13040
0
    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13041
0
      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
13042
0
      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
13043
0
      return BuildInvalid();
13044
0
    }
13045
0
  }
13046
13047
  // C++14 [namespace.udecl]p6:
13048
  // A using-declaration shall not name a namespace.
13049
0
  if (R.getAsSingle<NamespaceDecl>()) {
13050
0
    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
13051
0
      << SS.getRange();
13052
0
    return BuildInvalid();
13053
0
  }
13054
13055
0
  UsingDecl *UD = BuildValid();
13056
13057
  // Some additional rules apply to inheriting constructors.
13058
0
  if (UsingName.getName().getNameKind() ==
13059
0
        DeclarationName::CXXConstructorName) {
13060
    // Suppress access diagnostics; the access check is instead performed at the
13061
    // point of use for an inheriting constructor.
13062
0
    R.suppressDiagnostics();
13063
0
    if (CheckInheritingConstructorUsingDecl(UD))
13064
0
      return UD;
13065
0
  }
13066
13067
0
  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
13068
0
    UsingShadowDecl *PrevDecl = nullptr;
13069
0
    if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
13070
0
      BuildUsingShadowDecl(S, UD, *I, PrevDecl);
13071
0
  }
13072
13073
0
  return UD;
13074
0
}
13075
13076
NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
13077
                                           SourceLocation UsingLoc,
13078
                                           SourceLocation EnumLoc,
13079
                                           SourceLocation NameLoc,
13080
                                           TypeSourceInfo *EnumType,
13081
0
                                           EnumDecl *ED) {
13082
0
  bool Invalid = false;
13083
13084
0
  if (CurContext->getRedeclContext()->isRecord()) {
13085
    /// In class scope, check if this is a duplicate, for better a diagnostic.
13086
0
    DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13087
0
    LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13088
0
                          ForVisibleRedeclaration);
13089
13090
0
    LookupName(Previous, S);
13091
13092
0
    for (NamedDecl *D : Previous)
13093
0
      if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
13094
0
        if (UED->getEnumDecl() == ED) {
13095
0
          Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
13096
0
              << SourceRange(EnumLoc, NameLoc);
13097
0
          Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
13098
0
          Invalid = true;
13099
0
          break;
13100
0
        }
13101
0
  }
13102
13103
0
  if (RequireCompleteEnumDecl(ED, NameLoc))
13104
0
    Invalid = true;
13105
13106
0
  UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
13107
0
                                            EnumLoc, NameLoc, EnumType);
13108
0
  UD->setAccess(AS);
13109
0
  CurContext->addDecl(UD);
13110
13111
0
  if (Invalid) {
13112
0
    UD->setInvalidDecl();
13113
0
    return UD;
13114
0
  }
13115
13116
  // Create the shadow decls for each enumerator
13117
0
  for (EnumConstantDecl *EC : ED->enumerators()) {
13118
0
    UsingShadowDecl *PrevDecl = nullptr;
13119
0
    DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13120
0
    LookupResult Previous(*this, DNI, LookupOrdinaryName,
13121
0
                          ForVisibleRedeclaration);
13122
0
    LookupName(Previous, S);
13123
0
    FilterUsingLookup(S, Previous);
13124
13125
0
    if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
13126
0
      BuildUsingShadowDecl(S, UD, EC, PrevDecl);
13127
0
  }
13128
13129
0
  return UD;
13130
0
}
13131
13132
NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
13133
0
                                    ArrayRef<NamedDecl *> Expansions) {
13134
0
  assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13135
0
         isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13136
0
         isa<UsingPackDecl>(InstantiatedFrom));
13137
13138
0
  auto *UPD =
13139
0
      UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
13140
0
  UPD->setAccess(InstantiatedFrom->getAccess());
13141
0
  CurContext->addDecl(UPD);
13142
0
  return UPD;
13143
0
}
13144
13145
/// Additional checks for a using declaration referring to a constructor name.
13146
0
bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
13147
0
  assert(!UD->hasTypename() && "expecting a constructor name");
13148
13149
0
  const Type *SourceType = UD->getQualifier()->getAsType();
13150
0
  assert(SourceType &&
13151
0
         "Using decl naming constructor doesn't have type in scope spec.");
13152
0
  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
13153
13154
  // Check whether the named type is a direct base class.
13155
0
  bool AnyDependentBases = false;
13156
0
  auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
13157
0
                                      AnyDependentBases);
13158
0
  if (!Base && !AnyDependentBases) {
13159
0
    Diag(UD->getUsingLoc(),
13160
0
         diag::err_using_decl_constructor_not_in_direct_base)
13161
0
      << UD->getNameInfo().getSourceRange()
13162
0
      << QualType(SourceType, 0) << TargetClass;
13163
0
    UD->setInvalidDecl();
13164
0
    return true;
13165
0
  }
13166
13167
0
  if (Base)
13168
0
    Base->setInheritConstructors();
13169
13170
0
  return false;
13171
0
}
13172
13173
/// Checks that the given using declaration is not an invalid
13174
/// redeclaration.  Note that this is checking only for the using decl
13175
/// itself, not for any ill-formedness among the UsingShadowDecls.
13176
bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
13177
                                       bool HasTypenameKeyword,
13178
                                       const CXXScopeSpec &SS,
13179
                                       SourceLocation NameLoc,
13180
0
                                       const LookupResult &Prev) {
13181
0
  NestedNameSpecifier *Qual = SS.getScopeRep();
13182
13183
  // C++03 [namespace.udecl]p8:
13184
  // C++0x [namespace.udecl]p10:
13185
  //   A using-declaration is a declaration and can therefore be used
13186
  //   repeatedly where (and only where) multiple declarations are
13187
  //   allowed.
13188
  //
13189
  // That's in non-member contexts.
13190
0
  if (!CurContext->getRedeclContext()->isRecord()) {
13191
    // A dependent qualifier outside a class can only ever resolve to an
13192
    // enumeration type. Therefore it conflicts with any other non-type
13193
    // declaration in the same scope.
13194
    // FIXME: How should we check for dependent type-type conflicts at block
13195
    // scope?
13196
0
    if (Qual->isDependent() && !HasTypenameKeyword) {
13197
0
      for (auto *D : Prev) {
13198
0
        if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
13199
0
          bool OldCouldBeEnumerator =
13200
0
              isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
13201
0
          Diag(NameLoc,
13202
0
               OldCouldBeEnumerator ? diag::err_redefinition
13203
0
                                    : diag::err_redefinition_different_kind)
13204
0
              << Prev.getLookupName();
13205
0
          Diag(D->getLocation(), diag::note_previous_definition);
13206
0
          return true;
13207
0
        }
13208
0
      }
13209
0
    }
13210
0
    return false;
13211
0
  }
13212
13213
0
  const NestedNameSpecifier *CNNS =
13214
0
      Context.getCanonicalNestedNameSpecifier(Qual);
13215
0
  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
13216
0
    NamedDecl *D = *I;
13217
13218
0
    bool DTypename;
13219
0
    NestedNameSpecifier *DQual;
13220
0
    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
13221
0
      DTypename = UD->hasTypename();
13222
0
      DQual = UD->getQualifier();
13223
0
    } else if (UnresolvedUsingValueDecl *UD
13224
0
                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
13225
0
      DTypename = false;
13226
0
      DQual = UD->getQualifier();
13227
0
    } else if (UnresolvedUsingTypenameDecl *UD
13228
0
                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
13229
0
      DTypename = true;
13230
0
      DQual = UD->getQualifier();
13231
0
    } else continue;
13232
13233
    // using decls differ if one says 'typename' and the other doesn't.
13234
    // FIXME: non-dependent using decls?
13235
0
    if (HasTypenameKeyword != DTypename) continue;
13236
13237
    // using decls differ if they name different scopes (but note that
13238
    // template instantiation can cause this check to trigger when it
13239
    // didn't before instantiation).
13240
0
    if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
13241
0
      continue;
13242
13243
0
    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
13244
0
    Diag(D->getLocation(), diag::note_using_decl) << 1;
13245
0
    return true;
13246
0
  }
13247
13248
0
  return false;
13249
0
}
13250
13251
/// Checks that the given nested-name qualifier used in a using decl
13252
/// in the current context is appropriately related to the current
13253
/// scope.  If an error is found, diagnoses it and returns true.
13254
/// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
13255
/// result of that lookup. UD is likewise nullptr, except when we have an
13256
/// already-populated UsingDecl whose shadow decls contain the same information
13257
/// (i.e. we're instantiating a UsingDecl with non-dependent scope).
13258
bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13259
                                   const CXXScopeSpec &SS,
13260
                                   const DeclarationNameInfo &NameInfo,
13261
                                   SourceLocation NameLoc,
13262
0
                                   const LookupResult *R, const UsingDecl *UD) {
13263
0
  DeclContext *NamedContext = computeDeclContext(SS);
13264
0
  assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13265
0
         "resolvable context must have exactly one set of decls");
13266
13267
  // C++ 20 permits using an enumerator that does not have a class-hierarchy
13268
  // relationship.
13269
0
  bool Cxx20Enumerator = false;
13270
0
  if (NamedContext) {
13271
0
    EnumConstantDecl *EC = nullptr;
13272
0
    if (R)
13273
0
      EC = R->getAsSingle<EnumConstantDecl>();
13274
0
    else if (UD && UD->shadow_size() == 1)
13275
0
      EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
13276
0
    if (EC)
13277
0
      Cxx20Enumerator = getLangOpts().CPlusPlus20;
13278
13279
0
    if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
13280
      // C++14 [namespace.udecl]p7:
13281
      // A using-declaration shall not name a scoped enumerator.
13282
      // C++20 p1099 permits enumerators.
13283
0
      if (EC && R && ED->isScoped())
13284
0
        Diag(SS.getBeginLoc(),
13285
0
             getLangOpts().CPlusPlus20
13286
0
                 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13287
0
                 : diag::ext_using_decl_scoped_enumerator)
13288
0
            << SS.getRange();
13289
13290
      // We want to consider the scope of the enumerator
13291
0
      NamedContext = ED->getDeclContext();
13292
0
    }
13293
0
  }
13294
13295
0
  if (!CurContext->isRecord()) {
13296
    // C++03 [namespace.udecl]p3:
13297
    // C++0x [namespace.udecl]p8:
13298
    //   A using-declaration for a class member shall be a member-declaration.
13299
    // C++20 [namespace.udecl]p7
13300
    //   ... other than an enumerator ...
13301
13302
    // If we weren't able to compute a valid scope, it might validly be a
13303
    // dependent class or enumeration scope. If we have a 'typename' keyword,
13304
    // the scope must resolve to a class type.
13305
0
    if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13306
0
                     : !HasTypename)
13307
0
      return false; // OK
13308
13309
0
    Diag(NameLoc,
13310
0
         Cxx20Enumerator
13311
0
             ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13312
0
             : diag::err_using_decl_can_not_refer_to_class_member)
13313
0
        << SS.getRange();
13314
13315
0
    if (Cxx20Enumerator)
13316
0
      return false; // OK
13317
13318
0
    auto *RD = NamedContext
13319
0
                   ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
13320
0
                   : nullptr;
13321
0
    if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
13322
      // See if there's a helpful fixit
13323
13324
0
      if (!R) {
13325
        // We will have already diagnosed the problem on the template
13326
        // definition,  Maybe we should do so again?
13327
0
      } else if (R->getAsSingle<TypeDecl>()) {
13328
0
        if (getLangOpts().CPlusPlus11) {
13329
          // Convert 'using X::Y;' to 'using Y = X::Y;'.
13330
0
          Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
13331
0
            << 0 // alias declaration
13332
0
            << FixItHint::CreateInsertion(SS.getBeginLoc(),
13333
0
                                          NameInfo.getName().getAsString() +
13334
0
                                              " = ");
13335
0
        } else {
13336
          // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13337
0
          SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
13338
0
          Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
13339
0
            << 1 // typedef declaration
13340
0
            << FixItHint::CreateReplacement(UsingLoc, "typedef")
13341
0
            << FixItHint::CreateInsertion(
13342
0
                   InsertLoc, " " + NameInfo.getName().getAsString());
13343
0
        }
13344
0
      } else if (R->getAsSingle<VarDecl>()) {
13345
        // Don't provide a fixit outside C++11 mode; we don't want to suggest
13346
        // repeating the type of the static data member here.
13347
0
        FixItHint FixIt;
13348
0
        if (getLangOpts().CPlusPlus11) {
13349
          // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13350
0
          FixIt = FixItHint::CreateReplacement(
13351
0
              UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
13352
0
        }
13353
13354
0
        Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13355
0
          << 2 // reference declaration
13356
0
          << FixIt;
13357
0
      } else if (R->getAsSingle<EnumConstantDecl>()) {
13358
        // Don't provide a fixit outside C++11 mode; we don't want to suggest
13359
        // repeating the type of the enumeration here, and we can't do so if
13360
        // the type is anonymous.
13361
0
        FixItHint FixIt;
13362
0
        if (getLangOpts().CPlusPlus11) {
13363
          // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13364
0
          FixIt = FixItHint::CreateReplacement(
13365
0
              UsingLoc,
13366
0
              "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13367
0
        }
13368
13369
0
        Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
13370
0
          << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
13371
0
          << FixIt;
13372
0
      }
13373
0
    }
13374
13375
0
    return true; // Fail
13376
0
  }
13377
13378
  // If the named context is dependent, we can't decide much.
13379
0
  if (!NamedContext) {
13380
    // FIXME: in C++0x, we can diagnose if we can prove that the
13381
    // nested-name-specifier does not refer to a base class, which is
13382
    // still possible in some cases.
13383
13384
    // Otherwise we have to conservatively report that things might be
13385
    // okay.
13386
0
    return false;
13387
0
  }
13388
13389
  // The current scope is a record.
13390
0
  if (!NamedContext->isRecord()) {
13391
    // Ideally this would point at the last name in the specifier,
13392
    // but we don't have that level of source info.
13393
0
    Diag(SS.getBeginLoc(),
13394
0
         Cxx20Enumerator
13395
0
             ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13396
0
             : diag::err_using_decl_nested_name_specifier_is_not_class)
13397
0
        << SS.getScopeRep() << SS.getRange();
13398
13399
0
    if (Cxx20Enumerator)
13400
0
      return false; // OK
13401
13402
0
    return true;
13403
0
  }
13404
13405
0
  if (!NamedContext->isDependentContext() &&
13406
0
      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
13407
0
    return true;
13408
13409
0
  if (getLangOpts().CPlusPlus11) {
13410
    // C++11 [namespace.udecl]p3:
13411
    //   In a using-declaration used as a member-declaration, the
13412
    //   nested-name-specifier shall name a base class of the class
13413
    //   being defined.
13414
13415
0
    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
13416
0
                                 cast<CXXRecordDecl>(NamedContext))) {
13417
13418
0
      if (Cxx20Enumerator) {
13419
0
        Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13420
0
            << SS.getRange();
13421
0
        return false;
13422
0
      }
13423
13424
0
      if (CurContext == NamedContext) {
13425
0
        Diag(SS.getBeginLoc(),
13426
0
             diag::err_using_decl_nested_name_specifier_is_current_class)
13427
0
            << SS.getRange();
13428
0
        return !getLangOpts().CPlusPlus20;
13429
0
      }
13430
13431
0
      if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
13432
0
        Diag(SS.getBeginLoc(),
13433
0
             diag::err_using_decl_nested_name_specifier_is_not_base_class)
13434
0
            << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
13435
0
            << SS.getRange();
13436
0
      }
13437
0
      return true;
13438
0
    }
13439
13440
0
    return false;
13441
0
  }
13442
13443
  // C++03 [namespace.udecl]p4:
13444
  //   A using-declaration used as a member-declaration shall refer
13445
  //   to a member of a base class of the class being defined [etc.].
13446
13447
  // Salient point: SS doesn't have to name a base class as long as
13448
  // lookup only finds members from base classes.  Therefore we can
13449
  // diagnose here only if we can prove that can't happen,
13450
  // i.e. if the class hierarchies provably don't intersect.
13451
13452
  // TODO: it would be nice if "definitely valid" results were cached
13453
  // in the UsingDecl and UsingShadowDecl so that these checks didn't
13454
  // need to be repeated.
13455
13456
0
  llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
13457
0
  auto Collect = [&Bases](const CXXRecordDecl *Base) {
13458
0
    Bases.insert(Base);
13459
0
    return true;
13460
0
  };
13461
13462
  // Collect all bases. Return false if we find a dependent base.
13463
0
  if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
13464
0
    return false;
13465
13466
  // Returns true if the base is dependent or is one of the accumulated base
13467
  // classes.
13468
0
  auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13469
0
    return !Bases.count(Base);
13470
0
  };
13471
13472
  // Return false if the class has a dependent base or if it or one
13473
  // of its bases is present in the base set of the current context.
13474
0
  if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13475
0
      !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13476
0
    return false;
13477
13478
0
  Diag(SS.getRange().getBegin(),
13479
0
       diag::err_using_decl_nested_name_specifier_is_not_base_class)
13480
0
    << SS.getScopeRep()
13481
0
    << cast<CXXRecordDecl>(CurContext)
13482
0
    << SS.getRange();
13483
13484
0
  return true;
13485
0
}
13486
13487
Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13488
                                  MultiTemplateParamsArg TemplateParamLists,
13489
                                  SourceLocation UsingLoc, UnqualifiedId &Name,
13490
                                  const ParsedAttributesView &AttrList,
13491
0
                                  TypeResult Type, Decl *DeclFromDeclSpec) {
13492
  // Skip up to the relevant declaration scope.
13493
0
  while (S->isTemplateParamScope())
13494
0
    S = S->getParent();
13495
0
  assert((S->getFlags() & Scope::DeclScope) &&
13496
0
         "got alias-declaration outside of declaration scope");
13497
13498
0
  if (Type.isInvalid())
13499
0
    return nullptr;
13500
13501
0
  bool Invalid = false;
13502
0
  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13503
0
  TypeSourceInfo *TInfo = nullptr;
13504
0
  GetTypeFromParser(Type.get(), &TInfo);
13505
13506
0
  if (DiagnoseClassNameShadow(CurContext, NameInfo))
13507
0
    return nullptr;
13508
13509
0
  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13510
0
                                      UPPC_DeclarationType)) {
13511
0
    Invalid = true;
13512
0
    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13513
0
                                             TInfo->getTypeLoc().getBeginLoc());
13514
0
  }
13515
13516
0
  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13517
0
                        TemplateParamLists.size()
13518
0
                            ? forRedeclarationInCurContext()
13519
0
                            : ForVisibleRedeclaration);
13520
0
  LookupName(Previous, S);
13521
13522
  // Warn about shadowing the name of a template parameter.
13523
0
  if (Previous.isSingleResult() &&
13524
0
      Previous.getFoundDecl()->isTemplateParameter()) {
13525
0
    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13526
0
    Previous.clear();
13527
0
  }
13528
13529
0
  assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13530
0
         "name in alias declaration must be an identifier");
13531
0
  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
13532
0
                                               Name.StartLocation,
13533
0
                                               Name.Identifier, TInfo);
13534
13535
0
  NewTD->setAccess(AS);
13536
13537
0
  if (Invalid)
13538
0
    NewTD->setInvalidDecl();
13539
13540
0
  ProcessDeclAttributeList(S, NewTD, AttrList);
13541
0
  AddPragmaAttributes(S, NewTD);
13542
13543
0
  CheckTypedefForVariablyModifiedType(S, NewTD);
13544
0
  Invalid |= NewTD->isInvalidDecl();
13545
13546
0
  bool Redeclaration = false;
13547
13548
0
  NamedDecl *NewND;
13549
0
  if (TemplateParamLists.size()) {
13550
0
    TypeAliasTemplateDecl *OldDecl = nullptr;
13551
0
    TemplateParameterList *OldTemplateParams = nullptr;
13552
13553
0
    if (TemplateParamLists.size() != 1) {
13554
0
      Diag(UsingLoc, diag::err_alias_template_extra_headers)
13555
0
        << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13556
0
         TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13557
0
    }
13558
0
    TemplateParameterList *TemplateParams = TemplateParamLists[0];
13559
13560
    // Check that we can declare a template here.
13561
0
    if (CheckTemplateDeclScope(S, TemplateParams))
13562
0
      return nullptr;
13563
13564
    // Only consider previous declarations in the same scope.
13565
0
    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13566
0
                         /*ExplicitInstantiationOrSpecialization*/false);
13567
0
    if (!Previous.empty()) {
13568
0
      Redeclaration = true;
13569
13570
0
      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13571
0
      if (!OldDecl && !Invalid) {
13572
0
        Diag(UsingLoc, diag::err_redefinition_different_kind)
13573
0
          << Name.Identifier;
13574
13575
0
        NamedDecl *OldD = Previous.getRepresentativeDecl();
13576
0
        if (OldD->getLocation().isValid())
13577
0
          Diag(OldD->getLocation(), diag::note_previous_definition);
13578
13579
0
        Invalid = true;
13580
0
      }
13581
13582
0
      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13583
0
        if (TemplateParameterListsAreEqual(TemplateParams,
13584
0
                                           OldDecl->getTemplateParameters(),
13585
0
                                           /*Complain=*/true,
13586
0
                                           TPL_TemplateMatch))
13587
0
          OldTemplateParams =
13588
0
              OldDecl->getMostRecentDecl()->getTemplateParameters();
13589
0
        else
13590
0
          Invalid = true;
13591
13592
0
        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13593
0
        if (!Invalid &&
13594
0
            !Context.hasSameType(OldTD->getUnderlyingType(),
13595
0
                                 NewTD->getUnderlyingType())) {
13596
          // FIXME: The C++0x standard does not clearly say this is ill-formed,
13597
          // but we can't reasonably accept it.
13598
0
          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13599
0
            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13600
0
          if (OldTD->getLocation().isValid())
13601
0
            Diag(OldTD->getLocation(), diag::note_previous_definition);
13602
0
          Invalid = true;
13603
0
        }
13604
0
      }
13605
0
    }
13606
13607
    // Merge any previous default template arguments into our parameters,
13608
    // and check the parameter list.
13609
0
    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13610
0
                                   TPC_TypeAliasTemplate))
13611
0
      return nullptr;
13612
13613
0
    TypeAliasTemplateDecl *NewDecl =
13614
0
      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13615
0
                                    Name.Identifier, TemplateParams,
13616
0
                                    NewTD);
13617
0
    NewTD->setDescribedAliasTemplate(NewDecl);
13618
13619
0
    NewDecl->setAccess(AS);
13620
13621
0
    if (Invalid)
13622
0
      NewDecl->setInvalidDecl();
13623
0
    else if (OldDecl) {
13624
0
      NewDecl->setPreviousDecl(OldDecl);
13625
0
      CheckRedeclarationInModule(NewDecl, OldDecl);
13626
0
    }
13627
13628
0
    NewND = NewDecl;
13629
0
  } else {
13630
0
    if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13631
0
      setTagNameForLinkagePurposes(TD, NewTD);
13632
0
      handleTagNumbering(TD, S);
13633
0
    }
13634
0
    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13635
0
    NewND = NewTD;
13636
0
  }
13637
13638
0
  PushOnScopeChains(NewND, S);
13639
0
  ActOnDocumentableDecl(NewND);
13640
0
  return NewND;
13641
0
}
13642
13643
Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13644
                                   SourceLocation AliasLoc,
13645
                                   IdentifierInfo *Alias, CXXScopeSpec &SS,
13646
                                   SourceLocation IdentLoc,
13647
0
                                   IdentifierInfo *Ident) {
13648
13649
  // Lookup the namespace name.
13650
0
  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13651
0
  LookupParsedName(R, S, &SS);
13652
13653
0
  if (R.isAmbiguous())
13654
0
    return nullptr;
13655
13656
0
  if (R.empty()) {
13657
0
    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13658
0
      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13659
0
      return nullptr;
13660
0
    }
13661
0
  }
13662
0
  assert(!R.isAmbiguous() && !R.empty());
13663
0
  NamedDecl *ND = R.getRepresentativeDecl();
13664
13665
  // Check if we have a previous declaration with the same name.
13666
0
  LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13667
0
                     ForVisibleRedeclaration);
13668
0
  LookupName(PrevR, S);
13669
13670
  // Check we're not shadowing a template parameter.
13671
0
  if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13672
0
    DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13673
0
    PrevR.clear();
13674
0
  }
13675
13676
  // Filter out any other lookup result from an enclosing scope.
13677
0
  FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13678
0
                       /*AllowInlineNamespace*/false);
13679
13680
  // Find the previous declaration and check that we can redeclare it.
13681
0
  NamespaceAliasDecl *Prev = nullptr;
13682
0
  if (PrevR.isSingleResult()) {
13683
0
    NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13684
0
    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13685
      // We already have an alias with the same name that points to the same
13686
      // namespace; check that it matches.
13687
0
      if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13688
0
        Prev = AD;
13689
0
      } else if (isVisible(PrevDecl)) {
13690
0
        Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13691
0
          << Alias;
13692
0
        Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13693
0
          << AD->getNamespace();
13694
0
        return nullptr;
13695
0
      }
13696
0
    } else if (isVisible(PrevDecl)) {
13697
0
      unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13698
0
                            ? diag::err_redefinition
13699
0
                            : diag::err_redefinition_different_kind;
13700
0
      Diag(AliasLoc, DiagID) << Alias;
13701
0
      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13702
0
      return nullptr;
13703
0
    }
13704
0
  }
13705
13706
  // The use of a nested name specifier may trigger deprecation warnings.
13707
0
  DiagnoseUseOfDecl(ND, IdentLoc);
13708
13709
0
  NamespaceAliasDecl *AliasDecl =
13710
0
    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13711
0
                               Alias, SS.getWithLocInContext(Context),
13712
0
                               IdentLoc, ND);
13713
0
  if (Prev)
13714
0
    AliasDecl->setPreviousDecl(Prev);
13715
13716
0
  PushOnScopeChains(AliasDecl, S);
13717
0
  return AliasDecl;
13718
0
}
13719
13720
namespace {
13721
struct SpecialMemberExceptionSpecInfo
13722
    : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13723
  SourceLocation Loc;
13724
  Sema::ImplicitExceptionSpecification ExceptSpec;
13725
13726
  SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13727
                                 Sema::CXXSpecialMember CSM,
13728
                                 Sema::InheritedConstructorInfo *ICI,
13729
                                 SourceLocation Loc)
13730
0
      : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13731
13732
  bool visitBase(CXXBaseSpecifier *Base);
13733
  bool visitField(FieldDecl *FD);
13734
13735
  void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13736
                           unsigned Quals);
13737
13738
  void visitSubobjectCall(Subobject Subobj,
13739
                          Sema::SpecialMemberOverloadResult SMOR);
13740
};
13741
}
13742
13743
0
bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13744
0
  auto *RT = Base->getType()->getAs<RecordType>();
13745
0
  if (!RT)
13746
0
    return false;
13747
13748
0
  auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13749
0
  Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13750
0
  if (auto *BaseCtor = SMOR.getMethod()) {
13751
0
    visitSubobjectCall(Base, BaseCtor);
13752
0
    return false;
13753
0
  }
13754
13755
0
  visitClassSubobject(BaseClass, Base, 0);
13756
0
  return false;
13757
0
}
13758
13759
0
bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13760
0
  if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13761
0
    Expr *E = FD->getInClassInitializer();
13762
0
    if (!E)
13763
      // FIXME: It's a little wasteful to build and throw away a
13764
      // CXXDefaultInitExpr here.
13765
      // FIXME: We should have a single context note pointing at Loc, and
13766
      // this location should be MD->getLocation() instead, since that's
13767
      // the location where we actually use the default init expression.
13768
0
      E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13769
0
    if (E)
13770
0
      ExceptSpec.CalledExpr(E);
13771
0
  } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13772
0
                            ->getAs<RecordType>()) {
13773
0
    visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13774
0
                        FD->getType().getCVRQualifiers());
13775
0
  }
13776
0
  return false;
13777
0
}
13778
13779
void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13780
                                                         Subobject Subobj,
13781
0
                                                         unsigned Quals) {
13782
0
  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13783
0
  bool IsMutable = Field && Field->isMutable();
13784
0
  visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13785
0
}
13786
13787
void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13788
0
    Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13789
  // Note, if lookup fails, it doesn't matter what exception specification we
13790
  // choose because the special member will be deleted.
13791
0
  if (CXXMethodDecl *MD = SMOR.getMethod())
13792
0
    ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13793
0
}
13794
13795
0
bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13796
0
  llvm::APSInt Result;
13797
0
  ExprResult Converted = CheckConvertedConstantExpression(
13798
0
      ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13799
0
  ExplicitSpec.setExpr(Converted.get());
13800
0
  if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13801
0
    ExplicitSpec.setKind(Result.getBoolValue()
13802
0
                             ? ExplicitSpecKind::ResolvedTrue
13803
0
                             : ExplicitSpecKind::ResolvedFalse);
13804
0
    return true;
13805
0
  }
13806
0
  ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13807
0
  return false;
13808
0
}
13809
13810
0
ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13811
0
  ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13812
0
  if (!ExplicitExpr->isTypeDependent())
13813
0
    tryResolveExplicitSpecifier(ES);
13814
0
  return ES;
13815
0
}
13816
13817
static Sema::ImplicitExceptionSpecification
13818
ComputeDefaultedSpecialMemberExceptionSpec(
13819
    Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13820
0
    Sema::InheritedConstructorInfo *ICI) {
13821
0
  ComputingExceptionSpec CES(S, MD, Loc);
13822
13823
0
  CXXRecordDecl *ClassDecl = MD->getParent();
13824
13825
  // C++ [except.spec]p14:
13826
  //   An implicitly declared special member function (Clause 12) shall have an
13827
  //   exception-specification. [...]
13828
0
  SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13829
0
  if (ClassDecl->isInvalidDecl())
13830
0
    return Info.ExceptSpec;
13831
13832
  // FIXME: If this diagnostic fires, we're probably missing a check for
13833
  // attempting to resolve an exception specification before it's known
13834
  // at a higher level.
13835
0
  if (S.RequireCompleteType(MD->getLocation(),
13836
0
                            S.Context.getRecordType(ClassDecl),
13837
0
                            diag::err_exception_spec_incomplete_type))
13838
0
    return Info.ExceptSpec;
13839
13840
  // C++1z [except.spec]p7:
13841
  //   [Look for exceptions thrown by] a constructor selected [...] to
13842
  //   initialize a potentially constructed subobject,
13843
  // C++1z [except.spec]p8:
13844
  //   The exception specification for an implicitly-declared destructor, or a
13845
  //   destructor without a noexcept-specifier, is potentially-throwing if and
13846
  //   only if any of the destructors for any of its potentially constructed
13847
  //   subojects is potentially throwing.
13848
  // FIXME: We respect the first rule but ignore the "potentially constructed"
13849
  // in the second rule to resolve a core issue (no number yet) that would have
13850
  // us reject:
13851
  //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13852
  //   struct B : A {};
13853
  //   struct C : B { void f(); };
13854
  // ... due to giving B::~B() a non-throwing exception specification.
13855
0
  Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13856
0
                                : Info.VisitAllBases);
13857
13858
0
  return Info.ExceptSpec;
13859
0
}
13860
13861
namespace {
13862
/// RAII object to register a special member as being currently declared.
13863
struct DeclaringSpecialMember {
13864
  Sema &S;
13865
  Sema::SpecialMemberDecl D;
13866
  Sema::ContextRAII SavedContext;
13867
  bool WasAlreadyBeingDeclared;
13868
13869
  DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13870
0
      : S(S), D(RD, CSM), SavedContext(S, RD) {
13871
0
    WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13872
0
    if (WasAlreadyBeingDeclared)
13873
      // This almost never happens, but if it does, ensure that our cache
13874
      // doesn't contain a stale result.
13875
0
      S.SpecialMemberCache.clear();
13876
0
    else {
13877
      // Register a note to be produced if we encounter an error while
13878
      // declaring the special member.
13879
0
      Sema::CodeSynthesisContext Ctx;
13880
0
      Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13881
      // FIXME: We don't have a location to use here. Using the class's
13882
      // location maintains the fiction that we declare all special members
13883
      // with the class, but (1) it's not clear that lying about that helps our
13884
      // users understand what's going on, and (2) there may be outer contexts
13885
      // on the stack (some of which are relevant) and printing them exposes
13886
      // our lies.
13887
0
      Ctx.PointOfInstantiation = RD->getLocation();
13888
0
      Ctx.Entity = RD;
13889
0
      Ctx.SpecialMember = CSM;
13890
0
      S.pushCodeSynthesisContext(Ctx);
13891
0
    }
13892
0
  }
13893
0
  ~DeclaringSpecialMember() {
13894
0
    if (!WasAlreadyBeingDeclared) {
13895
0
      S.SpecialMembersBeingDeclared.erase(D);
13896
0
      S.popCodeSynthesisContext();
13897
0
    }
13898
0
  }
13899
13900
  /// Are we already trying to declare this special member?
13901
0
  bool isAlreadyBeingDeclared() const {
13902
0
    return WasAlreadyBeingDeclared;
13903
0
  }
13904
};
13905
}
13906
13907
0
void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13908
  // Look up any existing declarations, but don't trigger declaration of all
13909
  // implicit special members with this name.
13910
0
  DeclarationName Name = FD->getDeclName();
13911
0
  LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13912
0
                 ForExternalRedeclaration);
13913
0
  for (auto *D : FD->getParent()->lookup(Name))
13914
0
    if (auto *Acceptable = R.getAcceptableDecl(D))
13915
0
      R.addDecl(Acceptable);
13916
0
  R.resolveKind();
13917
0
  R.suppressDiagnostics();
13918
13919
0
  CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13920
0
                           FD->isThisDeclarationADefinition());
13921
0
}
13922
13923
void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13924
                                          QualType ResultTy,
13925
0
                                          ArrayRef<QualType> Args) {
13926
  // Build an exception specification pointing back at this constructor.
13927
0
  FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13928
13929
0
  LangAS AS = getDefaultCXXMethodAddrSpace();
13930
0
  if (AS != LangAS::Default) {
13931
0
    EPI.TypeQuals.addAddressSpace(AS);
13932
0
  }
13933
13934
0
  auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13935
0
  SpecialMem->setType(QT);
13936
13937
  // During template instantiation of implicit special member functions we need
13938
  // a reliable TypeSourceInfo for the function prototype in order to allow
13939
  // functions to be substituted.
13940
0
  if (inTemplateInstantiation() &&
13941
0
      cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13942
0
    TypeSourceInfo *TSI =
13943
0
        Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13944
0
    SpecialMem->setTypeSourceInfo(TSI);
13945
0
  }
13946
0
}
13947
13948
CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13949
0
                                                     CXXRecordDecl *ClassDecl) {
13950
  // C++ [class.ctor]p5:
13951
  //   A default constructor for a class X is a constructor of class X
13952
  //   that can be called without an argument. If there is no
13953
  //   user-declared constructor for class X, a default constructor is
13954
  //   implicitly declared. An implicitly-declared default constructor
13955
  //   is an inline public member of its class.
13956
0
  assert(ClassDecl->needsImplicitDefaultConstructor() &&
13957
0
         "Should not build implicit default constructor!");
13958
13959
0
  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13960
0
  if (DSM.isAlreadyBeingDeclared())
13961
0
    return nullptr;
13962
13963
0
  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13964
0
                                                     CXXDefaultConstructor,
13965
0
                                                     false);
13966
13967
  // Create the actual constructor declaration.
13968
0
  CanQualType ClassType
13969
0
    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13970
0
  SourceLocation ClassLoc = ClassDecl->getLocation();
13971
0
  DeclarationName Name
13972
0
    = Context.DeclarationNames.getCXXConstructorName(ClassType);
13973
0
  DeclarationNameInfo NameInfo(Name, ClassLoc);
13974
0
  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13975
0
      Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13976
0
      /*TInfo=*/nullptr, ExplicitSpecifier(),
13977
0
      getCurFPFeatures().isFPConstrained(),
13978
0
      /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13979
0
      Constexpr ? ConstexprSpecKind::Constexpr
13980
0
                : ConstexprSpecKind::Unspecified);
13981
0
  DefaultCon->setAccess(AS_public);
13982
0
  DefaultCon->setDefaulted();
13983
13984
0
  setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt);
13985
13986
0
  if (getLangOpts().CUDA)
13987
0
    inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13988
0
                                            DefaultCon,
13989
0
                                            /* ConstRHS */ false,
13990
0
                                            /* Diagnose */ false);
13991
13992
  // We don't need to use SpecialMemberIsTrivial here; triviality for default
13993
  // constructors is easy to compute.
13994
0
  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13995
13996
  // Note that we have declared this constructor.
13997
0
  ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13998
13999
0
  Scope *S = getScopeForContext(ClassDecl);
14000
0
  CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
14001
14002
0
  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
14003
0
    SetDeclDeleted(DefaultCon, ClassLoc);
14004
14005
0
  if (S)
14006
0
    PushOnScopeChains(DefaultCon, S, false);
14007
0
  ClassDecl->addDecl(DefaultCon);
14008
14009
0
  return DefaultCon;
14010
0
}
14011
14012
void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
14013
0
                                            CXXConstructorDecl *Constructor) {
14014
0
  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14015
0
          !Constructor->doesThisDeclarationHaveABody() &&
14016
0
          !Constructor->isDeleted()) &&
14017
0
    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14018
0
  if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14019
0
    return;
14020
14021
0
  CXXRecordDecl *ClassDecl = Constructor->getParent();
14022
0
  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14023
14024
0
  SynthesizedFunctionScope Scope(*this, Constructor);
14025
14026
  // The exception specification is needed because we are defining the
14027
  // function.
14028
0
  ResolveExceptionSpec(CurrentLocation,
14029
0
                       Constructor->getType()->castAs<FunctionProtoType>());
14030
0
  MarkVTableUsed(CurrentLocation, ClassDecl);
14031
14032
  // Add a context note for diagnostics produced after this point.
14033
0
  Scope.addContextNote(CurrentLocation);
14034
14035
0
  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14036
0
    Constructor->setInvalidDecl();
14037
0
    return;
14038
0
  }
14039
14040
0
  SourceLocation Loc = Constructor->getEndLoc().isValid()
14041
0
                           ? Constructor->getEndLoc()
14042
0
                           : Constructor->getLocation();
14043
0
  Constructor->setBody(new (Context) CompoundStmt(Loc));
14044
0
  Constructor->markUsed(Context);
14045
14046
0
  if (ASTMutationListener *L = getASTMutationListener()) {
14047
0
    L->CompletedImplicitDefinition(Constructor);
14048
0
  }
14049
14050
0
  DiagnoseUninitializedFields(*this, Constructor);
14051
0
}
14052
14053
0
void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
14054
  // Perform any delayed checks on exception specifications.
14055
0
  CheckDelayedMemberExceptionSpecs();
14056
0
}
14057
14058
/// Find or create the fake constructor we synthesize to model constructing an
14059
/// object of a derived class via a constructor of a base class.
14060
CXXConstructorDecl *
14061
Sema::findInheritingConstructor(SourceLocation Loc,
14062
                                CXXConstructorDecl *BaseCtor,
14063
0
                                ConstructorUsingShadowDecl *Shadow) {
14064
0
  CXXRecordDecl *Derived = Shadow->getParent();
14065
0
  SourceLocation UsingLoc = Shadow->getLocation();
14066
14067
  // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14068
  // For now we use the name of the base class constructor as a member of the
14069
  // derived class to indicate a (fake) inherited constructor name.
14070
0
  DeclarationName Name = BaseCtor->getDeclName();
14071
14072
  // Check to see if we already have a fake constructor for this inherited
14073
  // constructor call.
14074
0
  for (NamedDecl *Ctor : Derived->lookup(Name))
14075
0
    if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
14076
0
                               ->getInheritedConstructor()
14077
0
                               .getConstructor(),
14078
0
                           BaseCtor))
14079
0
      return cast<CXXConstructorDecl>(Ctor);
14080
14081
0
  DeclarationNameInfo NameInfo(Name, UsingLoc);
14082
0
  TypeSourceInfo *TInfo =
14083
0
      Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
14084
0
  FunctionProtoTypeLoc ProtoLoc =
14085
0
      TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
14086
14087
  // Check the inherited constructor is valid and find the list of base classes
14088
  // from which it was inherited.
14089
0
  InheritedConstructorInfo ICI(*this, Loc, Shadow);
14090
14091
0
  bool Constexpr =
14092
0
      BaseCtor->isConstexpr() &&
14093
0
      defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
14094
0
                                        false, BaseCtor, &ICI);
14095
14096
0
  CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
14097
0
      Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
14098
0
      BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14099
0
      /*isInline=*/true,
14100
0
      /*isImplicitlyDeclared=*/true,
14101
0
      Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
14102
0
      InheritedConstructor(Shadow, BaseCtor),
14103
0
      BaseCtor->getTrailingRequiresClause());
14104
0
  if (Shadow->isInvalidDecl())
14105
0
    DerivedCtor->setInvalidDecl();
14106
14107
  // Build an unevaluated exception specification for this fake constructor.
14108
0
  const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14109
0
  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14110
0
  EPI.ExceptionSpec.Type = EST_Unevaluated;
14111
0
  EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14112
0
  DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
14113
0
                                               FPT->getParamTypes(), EPI));
14114
14115
  // Build the parameter declarations.
14116
0
  SmallVector<ParmVarDecl *, 16> ParamDecls;
14117
0
  for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14118
0
    TypeSourceInfo *TInfo =
14119
0
        Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
14120
0
    ParmVarDecl *PD = ParmVarDecl::Create(
14121
0
        Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
14122
0
        FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
14123
0
    PD->setScopeInfo(0, I);
14124
0
    PD->setImplicit();
14125
    // Ensure attributes are propagated onto parameters (this matters for
14126
    // format, pass_object_size, ...).
14127
0
    mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
14128
0
    ParamDecls.push_back(PD);
14129
0
    ProtoLoc.setParam(I, PD);
14130
0
  }
14131
14132
  // Set up the new constructor.
14133
0
  assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14134
0
  DerivedCtor->setAccess(BaseCtor->getAccess());
14135
0
  DerivedCtor->setParams(ParamDecls);
14136
0
  Derived->addDecl(DerivedCtor);
14137
14138
0
  if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
14139
0
    SetDeclDeleted(DerivedCtor, UsingLoc);
14140
14141
0
  return DerivedCtor;
14142
0
}
14143
14144
0
void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
14145
0
  InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14146
0
                               Ctor->getInheritedConstructor().getShadowDecl());
14147
0
  ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
14148
0
                            /*Diagnose*/true);
14149
0
}
14150
14151
void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
14152
0
                                       CXXConstructorDecl *Constructor) {
14153
0
  CXXRecordDecl *ClassDecl = Constructor->getParent();
14154
0
  assert(Constructor->getInheritedConstructor() &&
14155
0
         !Constructor->doesThisDeclarationHaveABody() &&
14156
0
         !Constructor->isDeleted());
14157
0
  if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14158
0
    return;
14159
14160
  // Initializations are performed "as if by a defaulted default constructor",
14161
  // so enter the appropriate scope.
14162
0
  SynthesizedFunctionScope Scope(*this, Constructor);
14163
14164
  // The exception specification is needed because we are defining the
14165
  // function.
14166
0
  ResolveExceptionSpec(CurrentLocation,
14167
0
                       Constructor->getType()->castAs<FunctionProtoType>());
14168
0
  MarkVTableUsed(CurrentLocation, ClassDecl);
14169
14170
  // Add a context note for diagnostics produced after this point.
14171
0
  Scope.addContextNote(CurrentLocation);
14172
14173
0
  ConstructorUsingShadowDecl *Shadow =
14174
0
      Constructor->getInheritedConstructor().getShadowDecl();
14175
0
  CXXConstructorDecl *InheritedCtor =
14176
0
      Constructor->getInheritedConstructor().getConstructor();
14177
14178
  // [class.inhctor.init]p1:
14179
  //   initialization proceeds as if a defaulted default constructor is used to
14180
  //   initialize the D object and each base class subobject from which the
14181
  //   constructor was inherited
14182
14183
0
  InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14184
0
  CXXRecordDecl *RD = Shadow->getParent();
14185
0
  SourceLocation InitLoc = Shadow->getLocation();
14186
14187
  // Build explicit initializers for all base classes from which the
14188
  // constructor was inherited.
14189
0
  SmallVector<CXXCtorInitializer*, 8> Inits;
14190
0
  for (bool VBase : {false, true}) {
14191
0
    for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14192
0
      if (B.isVirtual() != VBase)
14193
0
        continue;
14194
14195
0
      auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14196
0
      if (!BaseRD)
14197
0
        continue;
14198
14199
0
      auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
14200
0
      if (!BaseCtor.first)
14201
0
        continue;
14202
14203
0
      MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
14204
0
      ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
14205
0
          InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14206
14207
0
      auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
14208
0
      Inits.push_back(new (Context) CXXCtorInitializer(
14209
0
          Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14210
0
          SourceLocation()));
14211
0
    }
14212
0
  }
14213
14214
  // We now proceed as if for a defaulted default constructor, with the relevant
14215
  // initializers replaced.
14216
14217
0
  if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
14218
0
    Constructor->setInvalidDecl();
14219
0
    return;
14220
0
  }
14221
14222
0
  Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14223
0
  Constructor->markUsed(Context);
14224
14225
0
  if (ASTMutationListener *L = getASTMutationListener()) {
14226
0
    L->CompletedImplicitDefinition(Constructor);
14227
0
  }
14228
14229
0
  DiagnoseUninitializedFields(*this, Constructor);
14230
0
}
14231
14232
0
CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
14233
  // C++ [class.dtor]p2:
14234
  //   If a class has no user-declared destructor, a destructor is
14235
  //   declared implicitly. An implicitly-declared destructor is an
14236
  //   inline public member of its class.
14237
0
  assert(ClassDecl->needsImplicitDestructor());
14238
14239
0
  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
14240
0
  if (DSM.isAlreadyBeingDeclared())
14241
0
    return nullptr;
14242
14243
0
  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14244
0
                                                     CXXDestructor,
14245
0
                                                     false);
14246
14247
  // Create the actual destructor declaration.
14248
0
  CanQualType ClassType
14249
0
    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
14250
0
  SourceLocation ClassLoc = ClassDecl->getLocation();
14251
0
  DeclarationName Name
14252
0
    = Context.DeclarationNames.getCXXDestructorName(ClassType);
14253
0
  DeclarationNameInfo NameInfo(Name, ClassLoc);
14254
0
  CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
14255
0
      Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
14256
0
      getCurFPFeatures().isFPConstrained(),
14257
0
      /*isInline=*/true,
14258
0
      /*isImplicitlyDeclared=*/true,
14259
0
      Constexpr ? ConstexprSpecKind::Constexpr
14260
0
                : ConstexprSpecKind::Unspecified);
14261
0
  Destructor->setAccess(AS_public);
14262
0
  Destructor->setDefaulted();
14263
14264
0
  setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt);
14265
14266
0
  if (getLangOpts().CUDA)
14267
0
    inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
14268
0
                                            Destructor,
14269
0
                                            /* ConstRHS */ false,
14270
0
                                            /* Diagnose */ false);
14271
14272
  // We don't need to use SpecialMemberIsTrivial here; triviality for
14273
  // destructors is easy to compute.
14274
0
  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14275
0
  Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14276
0
                                ClassDecl->hasTrivialDestructorForCall());
14277
14278
  // Note that we have declared this destructor.
14279
0
  ++getASTContext().NumImplicitDestructorsDeclared;
14280
14281
0
  Scope *S = getScopeForContext(ClassDecl);
14282
0
  CheckImplicitSpecialMemberDeclaration(S, Destructor);
14283
14284
  // We can't check whether an implicit destructor is deleted before we complete
14285
  // the definition of the class, because its validity depends on the alignment
14286
  // of the class. We'll check this from ActOnFields once the class is complete.
14287
0
  if (ClassDecl->isCompleteDefinition() &&
14288
0
      ShouldDeleteSpecialMember(Destructor, CXXDestructor))
14289
0
    SetDeclDeleted(Destructor, ClassLoc);
14290
14291
  // Introduce this destructor into its scope.
14292
0
  if (S)
14293
0
    PushOnScopeChains(Destructor, S, false);
14294
0
  ClassDecl->addDecl(Destructor);
14295
14296
0
  return Destructor;
14297
0
}
14298
14299
void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14300
0
                                    CXXDestructorDecl *Destructor) {
14301
0
  assert((Destructor->isDefaulted() &&
14302
0
          !Destructor->doesThisDeclarationHaveABody() &&
14303
0
          !Destructor->isDeleted()) &&
14304
0
         "DefineImplicitDestructor - call it for implicit default dtor");
14305
0
  if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14306
0
    return;
14307
14308
0
  CXXRecordDecl *ClassDecl = Destructor->getParent();
14309
0
  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14310
14311
0
  SynthesizedFunctionScope Scope(*this, Destructor);
14312
14313
  // The exception specification is needed because we are defining the
14314
  // function.
14315
0
  ResolveExceptionSpec(CurrentLocation,
14316
0
                       Destructor->getType()->castAs<FunctionProtoType>());
14317
0
  MarkVTableUsed(CurrentLocation, ClassDecl);
14318
14319
  // Add a context note for diagnostics produced after this point.
14320
0
  Scope.addContextNote(CurrentLocation);
14321
14322
0
  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14323
0
                                         Destructor->getParent());
14324
14325
0
  if (CheckDestructor(Destructor)) {
14326
0
    Destructor->setInvalidDecl();
14327
0
    return;
14328
0
  }
14329
14330
0
  SourceLocation Loc = Destructor->getEndLoc().isValid()
14331
0
                           ? Destructor->getEndLoc()
14332
0
                           : Destructor->getLocation();
14333
0
  Destructor->setBody(new (Context) CompoundStmt(Loc));
14334
0
  Destructor->markUsed(Context);
14335
14336
0
  if (ASTMutationListener *L = getASTMutationListener()) {
14337
0
    L->CompletedImplicitDefinition(Destructor);
14338
0
  }
14339
0
}
14340
14341
void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14342
0
                                          CXXDestructorDecl *Destructor) {
14343
0
  if (Destructor->isInvalidDecl())
14344
0
    return;
14345
14346
0
  CXXRecordDecl *ClassDecl = Destructor->getParent();
14347
0
  assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14348
0
         "implicit complete dtors unneeded outside MS ABI");
14349
0
  assert(ClassDecl->getNumVBases() > 0 &&
14350
0
         "complete dtor only exists for classes with vbases");
14351
14352
0
  SynthesizedFunctionScope Scope(*this, Destructor);
14353
14354
  // Add a context note for diagnostics produced after this point.
14355
0
  Scope.addContextNote(CurrentLocation);
14356
14357
0
  MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
14358
0
}
14359
14360
/// Perform any semantic analysis which needs to be delayed until all
14361
/// pending class member declarations have been parsed.
14362
0
void Sema::ActOnFinishCXXMemberDecls() {
14363
  // If the context is an invalid C++ class, just suppress these checks.
14364
0
  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
14365
0
    if (Record->isInvalidDecl()) {
14366
0
      DelayedOverridingExceptionSpecChecks.clear();
14367
0
      DelayedEquivalentExceptionSpecChecks.clear();
14368
0
      return;
14369
0
    }
14370
0
    checkForMultipleExportedDefaultConstructors(*this, Record);
14371
0
  }
14372
0
}
14373
14374
0
void Sema::ActOnFinishCXXNonNestedClass() {
14375
0
  referenceDLLExportedClassMethods();
14376
14377
0
  if (!DelayedDllExportMemberFunctions.empty()) {
14378
0
    SmallVector<CXXMethodDecl*, 4> WorkList;
14379
0
    std::swap(DelayedDllExportMemberFunctions, WorkList);
14380
0
    for (CXXMethodDecl *M : WorkList) {
14381
0
      DefineDefaultedFunction(*this, M, M->getLocation());
14382
14383
      // Pass the method to the consumer to get emitted. This is not necessary
14384
      // for explicit instantiation definitions, as they will get emitted
14385
      // anyway.
14386
0
      if (M->getParent()->getTemplateSpecializationKind() !=
14387
0
          TSK_ExplicitInstantiationDefinition)
14388
0
        ActOnFinishInlineFunctionDef(M);
14389
0
    }
14390
0
  }
14391
0
}
14392
14393
0
void Sema::referenceDLLExportedClassMethods() {
14394
0
  if (!DelayedDllExportClasses.empty()) {
14395
    // Calling ReferenceDllExportedMembers might cause the current function to
14396
    // be called again, so use a local copy of DelayedDllExportClasses.
14397
0
    SmallVector<CXXRecordDecl *, 4> WorkList;
14398
0
    std::swap(DelayedDllExportClasses, WorkList);
14399
0
    for (CXXRecordDecl *Class : WorkList)
14400
0
      ReferenceDllExportedMembers(*this, Class);
14401
0
  }
14402
0
}
14403
14404
0
void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14405
0
  assert(getLangOpts().CPlusPlus11 &&
14406
0
         "adjusting dtor exception specs was introduced in c++11");
14407
14408
0
  if (Destructor->isDependentContext())
14409
0
    return;
14410
14411
  // C++11 [class.dtor]p3:
14412
  //   A declaration of a destructor that does not have an exception-
14413
  //   specification is implicitly considered to have the same exception-
14414
  //   specification as an implicit declaration.
14415
0
  const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14416
0
  if (DtorType->hasExceptionSpec())
14417
0
    return;
14418
14419
  // Replace the destructor's type, building off the existing one. Fortunately,
14420
  // the only thing of interest in the destructor type is its extended info.
14421
  // The return and arguments are fixed.
14422
0
  FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14423
0
  EPI.ExceptionSpec.Type = EST_Unevaluated;
14424
0
  EPI.ExceptionSpec.SourceDecl = Destructor;
14425
0
  Destructor->setType(
14426
0
      Context.getFunctionType(Context.VoidTy, std::nullopt, EPI));
14427
14428
  // FIXME: If the destructor has a body that could throw, and the newly created
14429
  // spec doesn't allow exceptions, we should emit a warning, because this
14430
  // change in behavior can break conforming C++03 programs at runtime.
14431
  // However, we don't have a body or an exception specification yet, so it
14432
  // needs to be done somewhere else.
14433
0
}
14434
14435
namespace {
14436
/// An abstract base class for all helper classes used in building the
14437
//  copy/move operators. These classes serve as factory functions and help us
14438
//  avoid using the same Expr* in the AST twice.
14439
class ExprBuilder {
14440
  ExprBuilder(const ExprBuilder&) = delete;
14441
  ExprBuilder &operator=(const ExprBuilder&) = delete;
14442
14443
protected:
14444
0
  static Expr *assertNotNull(Expr *E) {
14445
0
    assert(E && "Expression construction must not fail.");
14446
0
    return E;
14447
0
  }
14448
14449
public:
14450
0
  ExprBuilder() {}
14451
0
  virtual ~ExprBuilder() {}
14452
14453
  virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14454
};
14455
14456
class RefBuilder: public ExprBuilder {
14457
  VarDecl *Var;
14458
  QualType VarType;
14459
14460
public:
14461
0
  Expr *build(Sema &S, SourceLocation Loc) const override {
14462
0
    return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14463
0
  }
14464
14465
  RefBuilder(VarDecl *Var, QualType VarType)
14466
0
      : Var(Var), VarType(VarType) {}
14467
};
14468
14469
class ThisBuilder: public ExprBuilder {
14470
public:
14471
0
  Expr *build(Sema &S, SourceLocation Loc) const override {
14472
0
    return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14473
0
  }
14474
};
14475
14476
class CastBuilder: public ExprBuilder {
14477
  const ExprBuilder &Builder;
14478
  QualType Type;
14479
  ExprValueKind Kind;
14480
  const CXXCastPath &Path;
14481
14482
public:
14483
0
  Expr *build(Sema &S, SourceLocation Loc) const override {
14484
0
    return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14485
0
                                             CK_UncheckedDerivedToBase, Kind,
14486
0
                                             &Path).get());
14487
0
  }
14488
14489
  CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14490
              const CXXCastPath &Path)
14491
0
      : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14492
};
14493
14494
class DerefBuilder: public ExprBuilder {
14495
  const ExprBuilder &Builder;
14496
14497
public:
14498
0
  Expr *build(Sema &S, SourceLocation Loc) const override {
14499
0
    return assertNotNull(
14500
0
        S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14501
0
  }
14502
14503
0
  DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14504
};
14505
14506
class MemberBuilder: public ExprBuilder {
14507
  const ExprBuilder &Builder;
14508
  QualType Type;
14509
  CXXScopeSpec SS;
14510
  bool IsArrow;
14511
  LookupResult &MemberLookup;
14512
14513
public:
14514
0
  Expr *build(Sema &S, SourceLocation Loc) const override {
14515
0
    return assertNotNull(S.BuildMemberReferenceExpr(
14516
0
        Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14517
0
        nullptr, MemberLookup, nullptr, nullptr).get());
14518
0
  }
14519
14520
  MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14521
                LookupResult &MemberLookup)
14522
      : Builder(Builder), Type(Type), IsArrow(IsArrow),
14523
0
        MemberLookup(MemberLookup) {}
14524
};
14525
14526
class MoveCastBuilder: public ExprBuilder {
14527
  const ExprBuilder &Builder;
14528
14529
public:
14530
0
  Expr *build(Sema &S, SourceLocation Loc) const override {
14531
0
    return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14532
0
  }
14533
14534
0
  MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14535
};
14536
14537
class LvalueConvBuilder: public ExprBuilder {
14538
  const ExprBuilder &Builder;
14539
14540
public:
14541
0
  Expr *build(Sema &S, SourceLocation Loc) const override {
14542
0
    return assertNotNull(
14543
0
        S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14544
0
  }
14545
14546
0
  LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14547
};
14548
14549
class SubscriptBuilder: public ExprBuilder {
14550
  const ExprBuilder &Base;
14551
  const ExprBuilder &Index;
14552
14553
public:
14554
0
  Expr *build(Sema &S, SourceLocation Loc) const override {
14555
0
    return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14556
0
        Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14557
0
  }
14558
14559
  SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14560
0
      : Base(Base), Index(Index) {}
14561
};
14562
14563
} // end anonymous namespace
14564
14565
/// When generating a defaulted copy or move assignment operator, if a field
14566
/// should be copied with __builtin_memcpy rather than via explicit assignments,
14567
/// do so. This optimization only applies for arrays of scalars, and for arrays
14568
/// of class type where the selected copy/move-assignment operator is trivial.
14569
static StmtResult
14570
buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14571
0
                           const ExprBuilder &ToB, const ExprBuilder &FromB) {
14572
  // Compute the size of the memory buffer to be copied.
14573
0
  QualType SizeType = S.Context.getSizeType();
14574
0
  llvm::APInt Size(S.Context.getTypeSize(SizeType),
14575
0
                   S.Context.getTypeSizeInChars(T).getQuantity());
14576
14577
  // Take the address of the field references for "from" and "to". We
14578
  // directly construct UnaryOperators here because semantic analysis
14579
  // does not permit us to take the address of an xvalue.
14580
0
  Expr *From = FromB.build(S, Loc);
14581
0
  From = UnaryOperator::Create(
14582
0
      S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14583
0
      VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14584
0
  Expr *To = ToB.build(S, Loc);
14585
0
  To = UnaryOperator::Create(
14586
0
      S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14587
0
      VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14588
14589
0
  const Type *E = T->getBaseElementTypeUnsafe();
14590
0
  bool NeedsCollectableMemCpy =
14591
0
      E->isRecordType() &&
14592
0
      E->castAs<RecordType>()->getDecl()->hasObjectMember();
14593
14594
  // Create a reference to the __builtin_objc_memmove_collectable function
14595
0
  StringRef MemCpyName = NeedsCollectableMemCpy ?
14596
0
    "__builtin_objc_memmove_collectable" :
14597
0
    "__builtin_memcpy";
14598
0
  LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14599
0
                 Sema::LookupOrdinaryName);
14600
0
  S.LookupName(R, S.TUScope, true);
14601
14602
0
  FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14603
0
  if (!MemCpy)
14604
    // Something went horribly wrong earlier, and we will have complained
14605
    // about it.
14606
0
    return StmtError();
14607
14608
0
  ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14609
0
                                            VK_PRValue, Loc, nullptr);
14610
0
  assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14611
14612
0
  Expr *CallArgs[] = {
14613
0
    To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14614
0
  };
14615
0
  ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14616
0
                                    Loc, CallArgs, Loc);
14617
14618
0
  assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14619
0
  return Call.getAs<Stmt>();
14620
0
}
14621
14622
/// Builds a statement that copies/moves the given entity from \p From to
14623
/// \c To.
14624
///
14625
/// This routine is used to copy/move the members of a class with an
14626
/// implicitly-declared copy/move assignment operator. When the entities being
14627
/// copied are arrays, this routine builds for loops to copy them.
14628
///
14629
/// \param S The Sema object used for type-checking.
14630
///
14631
/// \param Loc The location where the implicit copy/move is being generated.
14632
///
14633
/// \param T The type of the expressions being copied/moved. Both expressions
14634
/// must have this type.
14635
///
14636
/// \param To The expression we are copying/moving to.
14637
///
14638
/// \param From The expression we are copying/moving from.
14639
///
14640
/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14641
/// Otherwise, it's a non-static member subobject.
14642
///
14643
/// \param Copying Whether we're copying or moving.
14644
///
14645
/// \param Depth Internal parameter recording the depth of the recursion.
14646
///
14647
/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14648
/// if a memcpy should be used instead.
14649
static StmtResult
14650
buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14651
                                 const ExprBuilder &To, const ExprBuilder &From,
14652
                                 bool CopyingBaseSubobject, bool Copying,
14653
0
                                 unsigned Depth = 0) {
14654
  // C++11 [class.copy]p28:
14655
  //   Each subobject is assigned in the manner appropriate to its type:
14656
  //
14657
  //     - if the subobject is of class type, as if by a call to operator= with
14658
  //       the subobject as the object expression and the corresponding
14659
  //       subobject of x as a single function argument (as if by explicit
14660
  //       qualification; that is, ignoring any possible virtual overriding
14661
  //       functions in more derived classes);
14662
  //
14663
  // C++03 [class.copy]p13:
14664
  //     - if the subobject is of class type, the copy assignment operator for
14665
  //       the class is used (as if by explicit qualification; that is,
14666
  //       ignoring any possible virtual overriding functions in more derived
14667
  //       classes);
14668
0
  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14669
0
    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14670
14671
    // Look for operator=.
14672
0
    DeclarationName Name
14673
0
      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14674
0
    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14675
0
    S.LookupQualifiedName(OpLookup, ClassDecl, false);
14676
14677
    // Prior to C++11, filter out any result that isn't a copy/move-assignment
14678
    // operator.
14679
0
    if (!S.getLangOpts().CPlusPlus11) {
14680
0
      LookupResult::Filter F = OpLookup.makeFilter();
14681
0
      while (F.hasNext()) {
14682
0
        NamedDecl *D = F.next();
14683
0
        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14684
0
          if (Method->isCopyAssignmentOperator() ||
14685
0
              (!Copying && Method->isMoveAssignmentOperator()))
14686
0
            continue;
14687
14688
0
        F.erase();
14689
0
      }
14690
0
      F.done();
14691
0
    }
14692
14693
    // Suppress the protected check (C++ [class.protected]) for each of the
14694
    // assignment operators we found. This strange dance is required when
14695
    // we're assigning via a base classes's copy-assignment operator. To
14696
    // ensure that we're getting the right base class subobject (without
14697
    // ambiguities), we need to cast "this" to that subobject type; to
14698
    // ensure that we don't go through the virtual call mechanism, we need
14699
    // to qualify the operator= name with the base class (see below). However,
14700
    // this means that if the base class has a protected copy assignment
14701
    // operator, the protected member access check will fail. So, we
14702
    // rewrite "protected" access to "public" access in this case, since we
14703
    // know by construction that we're calling from a derived class.
14704
0
    if (CopyingBaseSubobject) {
14705
0
      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14706
0
           L != LEnd; ++L) {
14707
0
        if (L.getAccess() == AS_protected)
14708
0
          L.setAccess(AS_public);
14709
0
      }
14710
0
    }
14711
14712
    // Create the nested-name-specifier that will be used to qualify the
14713
    // reference to operator=; this is required to suppress the virtual
14714
    // call mechanism.
14715
0
    CXXScopeSpec SS;
14716
0
    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14717
0
    SS.MakeTrivial(S.Context,
14718
0
                   NestedNameSpecifier::Create(S.Context, nullptr, false,
14719
0
                                               CanonicalT),
14720
0
                   Loc);
14721
14722
    // Create the reference to operator=.
14723
0
    ExprResult OpEqualRef
14724
0
      = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14725
0
                                   SS, /*TemplateKWLoc=*/SourceLocation(),
14726
0
                                   /*FirstQualifierInScope=*/nullptr,
14727
0
                                   OpLookup,
14728
0
                                   /*TemplateArgs=*/nullptr, /*S*/nullptr,
14729
0
                                   /*SuppressQualifierCheck=*/true);
14730
0
    if (OpEqualRef.isInvalid())
14731
0
      return StmtError();
14732
14733
    // Build the call to the assignment operator.
14734
14735
0
    Expr *FromInst = From.build(S, Loc);
14736
0
    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14737
0
                                                  OpEqualRef.getAs<Expr>(),
14738
0
                                                  Loc, FromInst, Loc);
14739
0
    if (Call.isInvalid())
14740
0
      return StmtError();
14741
14742
    // If we built a call to a trivial 'operator=' while copying an array,
14743
    // bail out. We'll replace the whole shebang with a memcpy.
14744
0
    CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14745
0
    if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14746
0
      return StmtResult((Stmt*)nullptr);
14747
14748
    // Convert to an expression-statement, and clean up any produced
14749
    // temporaries.
14750
0
    return S.ActOnExprStmt(Call);
14751
0
  }
14752
14753
  //     - if the subobject is of scalar type, the built-in assignment
14754
  //       operator is used.
14755
0
  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14756
0
  if (!ArrayTy) {
14757
0
    ExprResult Assignment = S.CreateBuiltinBinOp(
14758
0
        Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14759
0
    if (Assignment.isInvalid())
14760
0
      return StmtError();
14761
0
    return S.ActOnExprStmt(Assignment);
14762
0
  }
14763
14764
  //     - if the subobject is an array, each element is assigned, in the
14765
  //       manner appropriate to the element type;
14766
14767
  // Construct a loop over the array bounds, e.g.,
14768
  //
14769
  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14770
  //
14771
  // that will copy each of the array elements.
14772
0
  QualType SizeType = S.Context.getSizeType();
14773
14774
  // Create the iteration variable.
14775
0
  IdentifierInfo *IterationVarName = nullptr;
14776
0
  {
14777
0
    SmallString<8> Str;
14778
0
    llvm::raw_svector_ostream OS(Str);
14779
0
    OS << "__i" << Depth;
14780
0
    IterationVarName = &S.Context.Idents.get(OS.str());
14781
0
  }
14782
0
  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14783
0
                                          IterationVarName, SizeType,
14784
0
                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14785
0
                                          SC_None);
14786
14787
  // Initialize the iteration variable to zero.
14788
0
  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14789
0
  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14790
14791
  // Creates a reference to the iteration variable.
14792
0
  RefBuilder IterationVarRef(IterationVar, SizeType);
14793
0
  LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14794
14795
  // Create the DeclStmt that holds the iteration variable.
14796
0
  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14797
14798
  // Subscript the "from" and "to" expressions with the iteration variable.
14799
0
  SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14800
0
  MoveCastBuilder FromIndexMove(FromIndexCopy);
14801
0
  const ExprBuilder *FromIndex;
14802
0
  if (Copying)
14803
0
    FromIndex = &FromIndexCopy;
14804
0
  else
14805
0
    FromIndex = &FromIndexMove;
14806
14807
0
  SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14808
14809
  // Build the copy/move for an individual element of the array.
14810
0
  StmtResult Copy =
14811
0
    buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14812
0
                                     ToIndex, *FromIndex, CopyingBaseSubobject,
14813
0
                                     Copying, Depth + 1);
14814
  // Bail out if copying fails or if we determined that we should use memcpy.
14815
0
  if (Copy.isInvalid() || !Copy.get())
14816
0
    return Copy;
14817
14818
  // Create the comparison against the array bound.
14819
0
  llvm::APInt Upper
14820
0
    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14821
0
  Expr *Comparison = BinaryOperator::Create(
14822
0
      S.Context, IterationVarRefRVal.build(S, Loc),
14823
0
      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14824
0
      S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14825
0
      S.CurFPFeatureOverrides());
14826
14827
  // Create the pre-increment of the iteration variable. We can determine
14828
  // whether the increment will overflow based on the value of the array
14829
  // bound.
14830
0
  Expr *Increment = UnaryOperator::Create(
14831
0
      S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14832
0
      OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14833
14834
  // Construct the loop that copies all elements of this array.
14835
0
  return S.ActOnForStmt(
14836
0
      Loc, Loc, InitStmt,
14837
0
      S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14838
0
      S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14839
0
}
14840
14841
static StmtResult
14842
buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14843
                      const ExprBuilder &To, const ExprBuilder &From,
14844
0
                      bool CopyingBaseSubobject, bool Copying) {
14845
  // Maybe we should use a memcpy?
14846
0
  if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14847
0
      T.isTriviallyCopyableType(S.Context))
14848
0
    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14849
14850
0
  StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14851
0
                                                     CopyingBaseSubobject,
14852
0
                                                     Copying, 0));
14853
14854
  // If we ended up picking a trivial assignment operator for an array of a
14855
  // non-trivially-copyable class type, just emit a memcpy.
14856
0
  if (!Result.isInvalid() && !Result.get())
14857
0
    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14858
14859
0
  return Result;
14860
0
}
14861
14862
0
CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14863
  // Note: The following rules are largely analoguous to the copy
14864
  // constructor rules. Note that virtual bases are not taken into account
14865
  // for determining the argument type of the operator. Note also that
14866
  // operators taking an object instead of a reference are allowed.
14867
0
  assert(ClassDecl->needsImplicitCopyAssignment());
14868
14869
0
  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14870
0
  if (DSM.isAlreadyBeingDeclared())
14871
0
    return nullptr;
14872
14873
0
  QualType ArgType = Context.getTypeDeclType(ClassDecl);
14874
0
  ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
14875
0
                                      ArgType, nullptr);
14876
0
  LangAS AS = getDefaultCXXMethodAddrSpace();
14877
0
  if (AS != LangAS::Default)
14878
0
    ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14879
0
  QualType RetType = Context.getLValueReferenceType(ArgType);
14880
0
  bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14881
0
  if (Const)
14882
0
    ArgType = ArgType.withConst();
14883
14884
0
  ArgType = Context.getLValueReferenceType(ArgType);
14885
14886
0
  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14887
0
                                                     CXXCopyAssignment,
14888
0
                                                     Const);
14889
14890
  //   An implicitly-declared copy assignment operator is an inline public
14891
  //   member of its class.
14892
0
  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14893
0
  SourceLocation ClassLoc = ClassDecl->getLocation();
14894
0
  DeclarationNameInfo NameInfo(Name, ClassLoc);
14895
0
  CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14896
0
      Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14897
0
      /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14898
0
      getCurFPFeatures().isFPConstrained(),
14899
0
      /*isInline=*/true,
14900
0
      Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14901
0
      SourceLocation());
14902
0
  CopyAssignment->setAccess(AS_public);
14903
0
  CopyAssignment->setDefaulted();
14904
0
  CopyAssignment->setImplicit();
14905
14906
0
  setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14907
14908
0
  if (getLangOpts().CUDA)
14909
0
    inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14910
0
                                            CopyAssignment,
14911
0
                                            /* ConstRHS */ Const,
14912
0
                                            /* Diagnose */ false);
14913
14914
  // Add the parameter to the operator.
14915
0
  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14916
0
                                               ClassLoc, ClassLoc,
14917
0
                                               /*Id=*/nullptr, ArgType,
14918
0
                                               /*TInfo=*/nullptr, SC_None,
14919
0
                                               nullptr);
14920
0
  CopyAssignment->setParams(FromParam);
14921
14922
0
  CopyAssignment->setTrivial(
14923
0
    ClassDecl->needsOverloadResolutionForCopyAssignment()
14924
0
      ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14925
0
      : ClassDecl->hasTrivialCopyAssignment());
14926
14927
  // Note that we have added this copy-assignment operator.
14928
0
  ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14929
14930
0
  Scope *S = getScopeForContext(ClassDecl);
14931
0
  CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14932
14933
0
  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14934
0
    ClassDecl->setImplicitCopyAssignmentIsDeleted();
14935
0
    SetDeclDeleted(CopyAssignment, ClassLoc);
14936
0
  }
14937
14938
0
  if (S)
14939
0
    PushOnScopeChains(CopyAssignment, S, false);
14940
0
  ClassDecl->addDecl(CopyAssignment);
14941
14942
0
  return CopyAssignment;
14943
0
}
14944
14945
/// Diagnose an implicit copy operation for a class which is odr-used, but
14946
/// which is deprecated because the class has a user-declared copy constructor,
14947
/// copy assignment operator, or destructor.
14948
0
static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14949
0
  assert(CopyOp->isImplicit());
14950
14951
0
  CXXRecordDecl *RD = CopyOp->getParent();
14952
0
  CXXMethodDecl *UserDeclaredOperation = nullptr;
14953
14954
0
  if (RD->hasUserDeclaredDestructor()) {
14955
0
    UserDeclaredOperation = RD->getDestructor();
14956
0
  } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14957
0
             RD->hasUserDeclaredCopyConstructor()) {
14958
    // Find any user-declared copy constructor.
14959
0
    for (auto *I : RD->ctors()) {
14960
0
      if (I->isCopyConstructor()) {
14961
0
        UserDeclaredOperation = I;
14962
0
        break;
14963
0
      }
14964
0
    }
14965
0
    assert(UserDeclaredOperation);
14966
0
  } else if (isa<CXXConstructorDecl>(CopyOp) &&
14967
0
             RD->hasUserDeclaredCopyAssignment()) {
14968
    // Find any user-declared move assignment operator.
14969
0
    for (auto *I : RD->methods()) {
14970
0
      if (I->isCopyAssignmentOperator()) {
14971
0
        UserDeclaredOperation = I;
14972
0
        break;
14973
0
      }
14974
0
    }
14975
0
    assert(UserDeclaredOperation);
14976
0
  }
14977
14978
0
  if (UserDeclaredOperation) {
14979
0
    bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14980
0
    bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14981
0
    bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14982
0
    unsigned DiagID =
14983
0
        (UDOIsUserProvided && UDOIsDestructor)
14984
0
            ? diag::warn_deprecated_copy_with_user_provided_dtor
14985
0
        : (UDOIsUserProvided && !UDOIsDestructor)
14986
0
            ? diag::warn_deprecated_copy_with_user_provided_copy
14987
0
        : (!UDOIsUserProvided && UDOIsDestructor)
14988
0
            ? diag::warn_deprecated_copy_with_dtor
14989
0
            : diag::warn_deprecated_copy;
14990
0
    S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14991
0
        << RD << IsCopyAssignment;
14992
0
  }
14993
0
}
14994
14995
void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14996
0
                                        CXXMethodDecl *CopyAssignOperator) {
14997
0
  assert((CopyAssignOperator->isDefaulted() &&
14998
0
          CopyAssignOperator->isOverloadedOperator() &&
14999
0
          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15000
0
          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15001
0
          !CopyAssignOperator->isDeleted()) &&
15002
0
         "DefineImplicitCopyAssignment called for wrong function");
15003
0
  if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15004
0
    return;
15005
15006
0
  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15007
0
  if (ClassDecl->isInvalidDecl()) {
15008
0
    CopyAssignOperator->setInvalidDecl();
15009
0
    return;
15010
0
  }
15011
15012
0
  SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15013
15014
  // The exception specification is needed because we are defining the
15015
  // function.
15016
0
  ResolveExceptionSpec(CurrentLocation,
15017
0
                       CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15018
15019
  // Add a context note for diagnostics produced after this point.
15020
0
  Scope.addContextNote(CurrentLocation);
15021
15022
  // C++11 [class.copy]p18:
15023
  //   The [definition of an implicitly declared copy assignment operator] is
15024
  //   deprecated if the class has a user-declared copy constructor or a
15025
  //   user-declared destructor.
15026
0
  if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15027
0
    diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
15028
15029
  // C++0x [class.copy]p30:
15030
  //   The implicitly-defined or explicitly-defaulted copy assignment operator
15031
  //   for a non-union class X performs memberwise copy assignment of its
15032
  //   subobjects. The direct base classes of X are assigned first, in the
15033
  //   order of their declaration in the base-specifier-list, and then the
15034
  //   immediate non-static data members of X are assigned, in the order in
15035
  //   which they were declared in the class definition.
15036
15037
  // The statements that form the synthesized function body.
15038
0
  SmallVector<Stmt*, 8> Statements;
15039
15040
  // The parameter for the "other" object, which we are copying from.
15041
0
  ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0);
15042
0
  Qualifiers OtherQuals = Other->getType().getQualifiers();
15043
0
  QualType OtherRefType = Other->getType();
15044
0
  if (OtherRefType->isLValueReferenceType()) {
15045
0
    OtherRefType = OtherRefType->getPointeeType();
15046
0
    OtherQuals = OtherRefType.getQualifiers();
15047
0
  }
15048
15049
  // Our location for everything implicitly-generated.
15050
0
  SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15051
0
                           ? CopyAssignOperator->getEndLoc()
15052
0
                           : CopyAssignOperator->getLocation();
15053
15054
  // Builds a DeclRefExpr for the "other" object.
15055
0
  RefBuilder OtherRef(Other, OtherRefType);
15056
15057
  // Builds the function object parameter.
15058
0
  std::optional<ThisBuilder> This;
15059
0
  std::optional<DerefBuilder> DerefThis;
15060
0
  std::optional<RefBuilder> ExplicitObject;
15061
0
  bool IsArrow = false;
15062
0
  QualType ObjectType;
15063
0
  if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15064
0
    ObjectType = CopyAssignOperator->getParamDecl(0)->getType();
15065
0
    if (ObjectType->isReferenceType())
15066
0
      ObjectType = ObjectType->getPointeeType();
15067
0
    ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType);
15068
0
  } else {
15069
0
    ObjectType = getCurrentThisType();
15070
0
    This.emplace();
15071
0
    DerefThis.emplace(*This);
15072
0
    IsArrow = !LangOpts.HLSL;
15073
0
  }
15074
0
  ExprBuilder &ObjectParameter =
15075
0
      ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15076
0
                     : static_cast<ExprBuilder &>(*This);
15077
15078
  // Assign base classes.
15079
0
  bool Invalid = false;
15080
0
  for (auto &Base : ClassDecl->bases()) {
15081
    // Form the assignment:
15082
    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15083
0
    QualType BaseType = Base.getType().getUnqualifiedType();
15084
0
    if (!BaseType->isRecordType()) {
15085
0
      Invalid = true;
15086
0
      continue;
15087
0
    }
15088
15089
0
    CXXCastPath BasePath;
15090
0
    BasePath.push_back(&Base);
15091
15092
    // Construct the "from" expression, which is an implicit cast to the
15093
    // appropriately-qualified base type.
15094
0
    CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
15095
0
                     VK_LValue, BasePath);
15096
15097
    // Dereference "this".
15098
0
    CastBuilder To(
15099
0
        ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15100
0
                       : static_cast<ExprBuilder &>(*DerefThis),
15101
0
        Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15102
0
        VK_LValue, BasePath);
15103
15104
    // Build the copy.
15105
0
    StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
15106
0
                                            To, From,
15107
0
                                            /*CopyingBaseSubobject=*/true,
15108
0
                                            /*Copying=*/true);
15109
0
    if (Copy.isInvalid()) {
15110
0
      CopyAssignOperator->setInvalidDecl();
15111
0
      return;
15112
0
    }
15113
15114
    // Success! Record the copy.
15115
0
    Statements.push_back(Copy.getAs<Expr>());
15116
0
  }
15117
15118
  // Assign non-static members.
15119
0
  for (auto *Field : ClassDecl->fields()) {
15120
    // FIXME: We should form some kind of AST representation for the implied
15121
    // memcpy in a union copy operation.
15122
0
    if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
15123
0
      continue;
15124
15125
0
    if (Field->isInvalidDecl()) {
15126
0
      Invalid = true;
15127
0
      continue;
15128
0
    }
15129
15130
    // Check for members of reference type; we can't copy those.
15131
0
    if (Field->getType()->isReferenceType()) {
15132
0
      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15133
0
        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15134
0
      Diag(Field->getLocation(), diag::note_declared_at);
15135
0
      Invalid = true;
15136
0
      continue;
15137
0
    }
15138
15139
    // Check for members of const-qualified, non-class type.
15140
0
    QualType BaseType = Context.getBaseElementType(Field->getType());
15141
0
    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15142
0
      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15143
0
        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15144
0
      Diag(Field->getLocation(), diag::note_declared_at);
15145
0
      Invalid = true;
15146
0
      continue;
15147
0
    }
15148
15149
    // Suppress assigning zero-width bitfields.
15150
0
    if (Field->isZeroLengthBitField(Context))
15151
0
      continue;
15152
15153
0
    QualType FieldType = Field->getType().getNonReferenceType();
15154
0
    if (FieldType->isIncompleteArrayType()) {
15155
0
      assert(ClassDecl->hasFlexibleArrayMember() &&
15156
0
             "Incomplete array type is not valid");
15157
0
      continue;
15158
0
    }
15159
15160
    // Build references to the field in the object we're copying from and to.
15161
0
    CXXScopeSpec SS; // Intentionally empty
15162
0
    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15163
0
                              LookupMemberName);
15164
0
    MemberLookup.addDecl(Field);
15165
0
    MemberLookup.resolveKind();
15166
15167
0
    MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15168
0
    MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15169
    // Build the copy of this field.
15170
0
    StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
15171
0
                                            To, From,
15172
0
                                            /*CopyingBaseSubobject=*/false,
15173
0
                                            /*Copying=*/true);
15174
0
    if (Copy.isInvalid()) {
15175
0
      CopyAssignOperator->setInvalidDecl();
15176
0
      return;
15177
0
    }
15178
15179
    // Success! Record the copy.
15180
0
    Statements.push_back(Copy.getAs<Stmt>());
15181
0
  }
15182
15183
0
  if (!Invalid) {
15184
    // Add a "return *this;"
15185
0
    Expr *ThisExpr =
15186
0
        (ExplicitObject  ? static_cast<ExprBuilder &>(*ExplicitObject)
15187
0
         : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15188
0
                         : static_cast<ExprBuilder &>(*DerefThis))
15189
0
            .build(*this, Loc);
15190
0
    StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15191
0
    if (Return.isInvalid())
15192
0
      Invalid = true;
15193
0
    else
15194
0
      Statements.push_back(Return.getAs<Stmt>());
15195
0
  }
15196
15197
0
  if (Invalid) {
15198
0
    CopyAssignOperator->setInvalidDecl();
15199
0
    return;
15200
0
  }
15201
15202
0
  StmtResult Body;
15203
0
  {
15204
0
    CompoundScopeRAII CompoundScope(*this);
15205
0
    Body = ActOnCompoundStmt(Loc, Loc, Statements,
15206
0
                             /*isStmtExpr=*/false);
15207
0
    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15208
0
  }
15209
0
  CopyAssignOperator->setBody(Body.getAs<Stmt>());
15210
0
  CopyAssignOperator->markUsed(Context);
15211
15212
0
  if (ASTMutationListener *L = getASTMutationListener()) {
15213
0
    L->CompletedImplicitDefinition(CopyAssignOperator);
15214
0
  }
15215
0
}
15216
15217
0
CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
15218
0
  assert(ClassDecl->needsImplicitMoveAssignment());
15219
15220
0
  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
15221
0
  if (DSM.isAlreadyBeingDeclared())
15222
0
    return nullptr;
15223
15224
  // Note: The following rules are largely analoguous to the move
15225
  // constructor rules.
15226
15227
0
  QualType ArgType = Context.getTypeDeclType(ClassDecl);
15228
0
  ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
15229
0
                                      ArgType, nullptr);
15230
0
  LangAS AS = getDefaultCXXMethodAddrSpace();
15231
0
  if (AS != LangAS::Default)
15232
0
    ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15233
0
  QualType RetType = Context.getLValueReferenceType(ArgType);
15234
0
  ArgType = Context.getRValueReferenceType(ArgType);
15235
15236
0
  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15237
0
                                                     CXXMoveAssignment,
15238
0
                                                     false);
15239
15240
  //   An implicitly-declared move assignment operator is an inline public
15241
  //   member of its class.
15242
0
  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
15243
0
  SourceLocation ClassLoc = ClassDecl->getLocation();
15244
0
  DeclarationNameInfo NameInfo(Name, ClassLoc);
15245
0
  CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15246
0
      Context, ClassDecl, ClassLoc, NameInfo, QualType(),
15247
0
      /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
15248
0
      getCurFPFeatures().isFPConstrained(),
15249
0
      /*isInline=*/true,
15250
0
      Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15251
0
      SourceLocation());
15252
0
  MoveAssignment->setAccess(AS_public);
15253
0
  MoveAssignment->setDefaulted();
15254
0
  MoveAssignment->setImplicit();
15255
15256
0
  setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
15257
15258
0
  if (getLangOpts().CUDA)
15259
0
    inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
15260
0
                                            MoveAssignment,
15261
0
                                            /* ConstRHS */ false,
15262
0
                                            /* Diagnose */ false);
15263
15264
  // Add the parameter to the operator.
15265
0
  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
15266
0
                                               ClassLoc, ClassLoc,
15267
0
                                               /*Id=*/nullptr, ArgType,
15268
0
                                               /*TInfo=*/nullptr, SC_None,
15269
0
                                               nullptr);
15270
0
  MoveAssignment->setParams(FromParam);
15271
15272
0
  MoveAssignment->setTrivial(
15273
0
    ClassDecl->needsOverloadResolutionForMoveAssignment()
15274
0
      ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
15275
0
      : ClassDecl->hasTrivialMoveAssignment());
15276
15277
  // Note that we have added this copy-assignment operator.
15278
0
  ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15279
15280
0
  Scope *S = getScopeForContext(ClassDecl);
15281
0
  CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
15282
15283
0
  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
15284
0
    ClassDecl->setImplicitMoveAssignmentIsDeleted();
15285
0
    SetDeclDeleted(MoveAssignment, ClassLoc);
15286
0
  }
15287
15288
0
  if (S)
15289
0
    PushOnScopeChains(MoveAssignment, S, false);
15290
0
  ClassDecl->addDecl(MoveAssignment);
15291
15292
0
  return MoveAssignment;
15293
0
}
15294
15295
/// Check if we're implicitly defining a move assignment operator for a class
15296
/// with virtual bases. Such a move assignment might move-assign the virtual
15297
/// base multiple times.
15298
static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15299
0
                                               SourceLocation CurrentLocation) {
15300
0
  assert(!Class->isDependentContext() && "should not define dependent move");
15301
15302
  // Only a virtual base could get implicitly move-assigned multiple times.
15303
  // Only a non-trivial move assignment can observe this. We only want to
15304
  // diagnose if we implicitly define an assignment operator that assigns
15305
  // two base classes, both of which move-assign the same virtual base.
15306
0
  if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15307
0
      Class->getNumBases() < 2)
15308
0
    return;
15309
15310
0
  llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15311
0
  typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15312
0
  VBaseMap VBases;
15313
15314
0
  for (auto &BI : Class->bases()) {
15315
0
    Worklist.push_back(&BI);
15316
0
    while (!Worklist.empty()) {
15317
0
      CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15318
0
      CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15319
15320
      // If the base has no non-trivial move assignment operators,
15321
      // we don't care about moves from it.
15322
0
      if (!Base->hasNonTrivialMoveAssignment())
15323
0
        continue;
15324
15325
      // If there's nothing virtual here, skip it.
15326
0
      if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15327
0
        continue;
15328
15329
      // If we're not actually going to call a move assignment for this base,
15330
      // or the selected move assignment is trivial, skip it.
15331
0
      Sema::SpecialMemberOverloadResult SMOR =
15332
0
        S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
15333
0
                              /*ConstArg*/false, /*VolatileArg*/false,
15334
0
                              /*RValueThis*/true, /*ConstThis*/false,
15335
0
                              /*VolatileThis*/false);
15336
0
      if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15337
0
          !SMOR.getMethod()->isMoveAssignmentOperator())
15338
0
        continue;
15339
15340
0
      if (BaseSpec->isVirtual()) {
15341
        // We're going to move-assign this virtual base, and its move
15342
        // assignment operator is not trivial. If this can happen for
15343
        // multiple distinct direct bases of Class, diagnose it. (If it
15344
        // only happens in one base, we'll diagnose it when synthesizing
15345
        // that base class's move assignment operator.)
15346
0
        CXXBaseSpecifier *&Existing =
15347
0
            VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
15348
0
                .first->second;
15349
0
        if (Existing && Existing != &BI) {
15350
0
          S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
15351
0
            << Class << Base;
15352
0
          S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
15353
0
              << (Base->getCanonicalDecl() ==
15354
0
                  Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15355
0
              << Base << Existing->getType() << Existing->getSourceRange();
15356
0
          S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
15357
0
              << (Base->getCanonicalDecl() ==
15358
0
                  BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15359
0
              << Base << BI.getType() << BaseSpec->getSourceRange();
15360
15361
          // Only diagnose each vbase once.
15362
0
          Existing = nullptr;
15363
0
        }
15364
0
      } else {
15365
        // Only walk over bases that have defaulted move assignment operators.
15366
        // We assume that any user-provided move assignment operator handles
15367
        // the multiple-moves-of-vbase case itself somehow.
15368
0
        if (!SMOR.getMethod()->isDefaulted())
15369
0
          continue;
15370
15371
        // We're going to move the base classes of Base. Add them to the list.
15372
0
        llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
15373
0
      }
15374
0
    }
15375
0
  }
15376
0
}
15377
15378
void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15379
0
                                        CXXMethodDecl *MoveAssignOperator) {
15380
0
  assert((MoveAssignOperator->isDefaulted() &&
15381
0
          MoveAssignOperator->isOverloadedOperator() &&
15382
0
          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15383
0
          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15384
0
          !MoveAssignOperator->isDeleted()) &&
15385
0
         "DefineImplicitMoveAssignment called for wrong function");
15386
0
  if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15387
0
    return;
15388
15389
0
  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15390
0
  if (ClassDecl->isInvalidDecl()) {
15391
0
    MoveAssignOperator->setInvalidDecl();
15392
0
    return;
15393
0
  }
15394
15395
  // C++0x [class.copy]p28:
15396
  //   The implicitly-defined or move assignment operator for a non-union class
15397
  //   X performs memberwise move assignment of its subobjects. The direct base
15398
  //   classes of X are assigned first, in the order of their declaration in the
15399
  //   base-specifier-list, and then the immediate non-static data members of X
15400
  //   are assigned, in the order in which they were declared in the class
15401
  //   definition.
15402
15403
  // Issue a warning if our implicit move assignment operator will move
15404
  // from a virtual base more than once.
15405
0
  checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
15406
15407
0
  SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15408
15409
  // The exception specification is needed because we are defining the
15410
  // function.
15411
0
  ResolveExceptionSpec(CurrentLocation,
15412
0
                       MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15413
15414
  // Add a context note for diagnostics produced after this point.
15415
0
  Scope.addContextNote(CurrentLocation);
15416
15417
  // The statements that form the synthesized function body.
15418
0
  SmallVector<Stmt*, 8> Statements;
15419
15420
  // The parameter for the "other" object, which we are move from.
15421
0
  ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0);
15422
0
  QualType OtherRefType =
15423
0
      Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15424
15425
  // Our location for everything implicitly-generated.
15426
0
  SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15427
0
                           ? MoveAssignOperator->getEndLoc()
15428
0
                           : MoveAssignOperator->getLocation();
15429
15430
  // Builds a reference to the "other" object.
15431
0
  RefBuilder OtherRef(Other, OtherRefType);
15432
  // Cast to rvalue.
15433
0
  MoveCastBuilder MoveOther(OtherRef);
15434
15435
  // Builds the function object parameter.
15436
0
  std::optional<ThisBuilder> This;
15437
0
  std::optional<DerefBuilder> DerefThis;
15438
0
  std::optional<RefBuilder> ExplicitObject;
15439
0
  QualType ObjectType;
15440
0
  if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15441
0
    ObjectType = MoveAssignOperator->getParamDecl(0)->getType();
15442
0
    if (ObjectType->isReferenceType())
15443
0
      ObjectType = ObjectType->getPointeeType();
15444
0
    ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType);
15445
0
  } else {
15446
0
    ObjectType = getCurrentThisType();
15447
0
    This.emplace();
15448
0
    DerefThis.emplace(*This);
15449
0
  }
15450
0
  ExprBuilder &ObjectParameter =
15451
0
      ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15452
15453
  // Assign base classes.
15454
0
  bool Invalid = false;
15455
0
  for (auto &Base : ClassDecl->bases()) {
15456
    // C++11 [class.copy]p28:
15457
    //   It is unspecified whether subobjects representing virtual base classes
15458
    //   are assigned more than once by the implicitly-defined copy assignment
15459
    //   operator.
15460
    // FIXME: Do not assign to a vbase that will be assigned by some other base
15461
    // class. For a move-assignment, this can result in the vbase being moved
15462
    // multiple times.
15463
15464
    // Form the assignment:
15465
    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15466
0
    QualType BaseType = Base.getType().getUnqualifiedType();
15467
0
    if (!BaseType->isRecordType()) {
15468
0
      Invalid = true;
15469
0
      continue;
15470
0
    }
15471
15472
0
    CXXCastPath BasePath;
15473
0
    BasePath.push_back(&Base);
15474
15475
    // Construct the "from" expression, which is an implicit cast to the
15476
    // appropriately-qualified base type.
15477
0
    CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15478
15479
    // Implicitly cast "this" to the appropriately-qualified base type.
15480
    // Dereference "this".
15481
0
    CastBuilder To(
15482
0
        ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15483
0
                       : static_cast<ExprBuilder &>(*DerefThis),
15484
0
        Context.getQualifiedType(BaseType, ObjectType.getQualifiers()),
15485
0
        VK_LValue, BasePath);
15486
15487
    // Build the move.
15488
0
    StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15489
0
                                            To, From,
15490
0
                                            /*CopyingBaseSubobject=*/true,
15491
0
                                            /*Copying=*/false);
15492
0
    if (Move.isInvalid()) {
15493
0
      MoveAssignOperator->setInvalidDecl();
15494
0
      return;
15495
0
    }
15496
15497
    // Success! Record the move.
15498
0
    Statements.push_back(Move.getAs<Expr>());
15499
0
  }
15500
15501
  // Assign non-static members.
15502
0
  for (auto *Field : ClassDecl->fields()) {
15503
    // FIXME: We should form some kind of AST representation for the implied
15504
    // memcpy in a union copy operation.
15505
0
    if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
15506
0
      continue;
15507
15508
0
    if (Field->isInvalidDecl()) {
15509
0
      Invalid = true;
15510
0
      continue;
15511
0
    }
15512
15513
    // Check for members of reference type; we can't move those.
15514
0
    if (Field->getType()->isReferenceType()) {
15515
0
      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15516
0
        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15517
0
      Diag(Field->getLocation(), diag::note_declared_at);
15518
0
      Invalid = true;
15519
0
      continue;
15520
0
    }
15521
15522
    // Check for members of const-qualified, non-class type.
15523
0
    QualType BaseType = Context.getBaseElementType(Field->getType());
15524
0
    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15525
0
      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15526
0
        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15527
0
      Diag(Field->getLocation(), diag::note_declared_at);
15528
0
      Invalid = true;
15529
0
      continue;
15530
0
    }
15531
15532
    // Suppress assigning zero-width bitfields.
15533
0
    if (Field->isZeroLengthBitField(Context))
15534
0
      continue;
15535
15536
0
    QualType FieldType = Field->getType().getNonReferenceType();
15537
0
    if (FieldType->isIncompleteArrayType()) {
15538
0
      assert(ClassDecl->hasFlexibleArrayMember() &&
15539
0
             "Incomplete array type is not valid");
15540
0
      continue;
15541
0
    }
15542
15543
    // Build references to the field in the object we're copying from and to.
15544
0
    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15545
0
                              LookupMemberName);
15546
0
    MemberLookup.addDecl(Field);
15547
0
    MemberLookup.resolveKind();
15548
0
    MemberBuilder From(MoveOther, OtherRefType,
15549
0
                       /*IsArrow=*/false, MemberLookup);
15550
0
    MemberBuilder To(ObjectParameter, ObjectType, /*IsArrow=*/!ExplicitObject,
15551
0
                     MemberLookup);
15552
15553
0
    assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15554
0
        "Member reference with rvalue base must be rvalue except for reference "
15555
0
        "members, which aren't allowed for move assignment.");
15556
15557
    // Build the move of this field.
15558
0
    StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15559
0
                                            To, From,
15560
0
                                            /*CopyingBaseSubobject=*/false,
15561
0
                                            /*Copying=*/false);
15562
0
    if (Move.isInvalid()) {
15563
0
      MoveAssignOperator->setInvalidDecl();
15564
0
      return;
15565
0
    }
15566
15567
    // Success! Record the copy.
15568
0
    Statements.push_back(Move.getAs<Stmt>());
15569
0
  }
15570
15571
0
  if (!Invalid) {
15572
    // Add a "return *this;"
15573
0
    Expr *ThisExpr =
15574
0
        (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15575
0
                        : static_cast<ExprBuilder &>(*DerefThis))
15576
0
            .build(*this, Loc);
15577
15578
0
    StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
15579
0
    if (Return.isInvalid())
15580
0
      Invalid = true;
15581
0
    else
15582
0
      Statements.push_back(Return.getAs<Stmt>());
15583
0
  }
15584
15585
0
  if (Invalid) {
15586
0
    MoveAssignOperator->setInvalidDecl();
15587
0
    return;
15588
0
  }
15589
15590
0
  StmtResult Body;
15591
0
  {
15592
0
    CompoundScopeRAII CompoundScope(*this);
15593
0
    Body = ActOnCompoundStmt(Loc, Loc, Statements,
15594
0
                             /*isStmtExpr=*/false);
15595
0
    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15596
0
  }
15597
0
  MoveAssignOperator->setBody(Body.getAs<Stmt>());
15598
0
  MoveAssignOperator->markUsed(Context);
15599
15600
0
  if (ASTMutationListener *L = getASTMutationListener()) {
15601
0
    L->CompletedImplicitDefinition(MoveAssignOperator);
15602
0
  }
15603
0
}
15604
15605
CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15606
0
                                                    CXXRecordDecl *ClassDecl) {
15607
  // C++ [class.copy]p4:
15608
  //   If the class definition does not explicitly declare a copy
15609
  //   constructor, one is declared implicitly.
15610
0
  assert(ClassDecl->needsImplicitCopyConstructor());
15611
15612
0
  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15613
0
  if (DSM.isAlreadyBeingDeclared())
15614
0
    return nullptr;
15615
15616
0
  QualType ClassType = Context.getTypeDeclType(ClassDecl);
15617
0
  QualType ArgType = ClassType;
15618
0
  ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
15619
0
                                      ArgType, nullptr);
15620
0
  bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15621
0
  if (Const)
15622
0
    ArgType = ArgType.withConst();
15623
15624
0
  LangAS AS = getDefaultCXXMethodAddrSpace();
15625
0
  if (AS != LangAS::Default)
15626
0
    ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15627
15628
0
  ArgType = Context.getLValueReferenceType(ArgType);
15629
15630
0
  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15631
0
                                                     CXXCopyConstructor,
15632
0
                                                     Const);
15633
15634
0
  DeclarationName Name
15635
0
    = Context.DeclarationNames.getCXXConstructorName(
15636
0
                                           Context.getCanonicalType(ClassType));
15637
0
  SourceLocation ClassLoc = ClassDecl->getLocation();
15638
0
  DeclarationNameInfo NameInfo(Name, ClassLoc);
15639
15640
  //   An implicitly-declared copy constructor is an inline public
15641
  //   member of its class.
15642
0
  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15643
0
      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15644
0
      ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15645
0
      /*isInline=*/true,
15646
0
      /*isImplicitlyDeclared=*/true,
15647
0
      Constexpr ? ConstexprSpecKind::Constexpr
15648
0
                : ConstexprSpecKind::Unspecified);
15649
0
  CopyConstructor->setAccess(AS_public);
15650
0
  CopyConstructor->setDefaulted();
15651
15652
0
  setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15653
15654
0
  if (getLangOpts().CUDA)
15655
0
    inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15656
0
                                            CopyConstructor,
15657
0
                                            /* ConstRHS */ Const,
15658
0
                                            /* Diagnose */ false);
15659
15660
  // During template instantiation of special member functions we need a
15661
  // reliable TypeSourceInfo for the parameter types in order to allow functions
15662
  // to be substituted.
15663
0
  TypeSourceInfo *TSI = nullptr;
15664
0
  if (inTemplateInstantiation() && ClassDecl->isLambda())
15665
0
    TSI = Context.getTrivialTypeSourceInfo(ArgType);
15666
15667
  // Add the parameter to the constructor.
15668
0
  ParmVarDecl *FromParam =
15669
0
      ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15670
0
                          /*IdentifierInfo=*/nullptr, ArgType,
15671
0
                          /*TInfo=*/TSI, SC_None, nullptr);
15672
0
  CopyConstructor->setParams(FromParam);
15673
15674
0
  CopyConstructor->setTrivial(
15675
0
      ClassDecl->needsOverloadResolutionForCopyConstructor()
15676
0
          ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15677
0
          : ClassDecl->hasTrivialCopyConstructor());
15678
15679
0
  CopyConstructor->setTrivialForCall(
15680
0
      ClassDecl->hasAttr<TrivialABIAttr>() ||
15681
0
      (ClassDecl->needsOverloadResolutionForCopyConstructor()
15682
0
           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15683
0
             TAH_ConsiderTrivialABI)
15684
0
           : ClassDecl->hasTrivialCopyConstructorForCall()));
15685
15686
  // Note that we have declared this constructor.
15687
0
  ++getASTContext().NumImplicitCopyConstructorsDeclared;
15688
15689
0
  Scope *S = getScopeForContext(ClassDecl);
15690
0
  CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15691
15692
0
  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15693
0
    ClassDecl->setImplicitCopyConstructorIsDeleted();
15694
0
    SetDeclDeleted(CopyConstructor, ClassLoc);
15695
0
  }
15696
15697
0
  if (S)
15698
0
    PushOnScopeChains(CopyConstructor, S, false);
15699
0
  ClassDecl->addDecl(CopyConstructor);
15700
15701
0
  return CopyConstructor;
15702
0
}
15703
15704
void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15705
0
                                         CXXConstructorDecl *CopyConstructor) {
15706
0
  assert((CopyConstructor->isDefaulted() &&
15707
0
          CopyConstructor->isCopyConstructor() &&
15708
0
          !CopyConstructor->doesThisDeclarationHaveABody() &&
15709
0
          !CopyConstructor->isDeleted()) &&
15710
0
         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15711
0
  if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15712
0
    return;
15713
15714
0
  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15715
0
  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15716
15717
0
  SynthesizedFunctionScope Scope(*this, CopyConstructor);
15718
15719
  // The exception specification is needed because we are defining the
15720
  // function.
15721
0
  ResolveExceptionSpec(CurrentLocation,
15722
0
                       CopyConstructor->getType()->castAs<FunctionProtoType>());
15723
0
  MarkVTableUsed(CurrentLocation, ClassDecl);
15724
15725
  // Add a context note for diagnostics produced after this point.
15726
0
  Scope.addContextNote(CurrentLocation);
15727
15728
  // C++11 [class.copy]p7:
15729
  //   The [definition of an implicitly declared copy constructor] is
15730
  //   deprecated if the class has a user-declared copy assignment operator
15731
  //   or a user-declared destructor.
15732
0
  if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15733
0
    diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15734
15735
0
  if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15736
0
    CopyConstructor->setInvalidDecl();
15737
0
  }  else {
15738
0
    SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15739
0
                             ? CopyConstructor->getEndLoc()
15740
0
                             : CopyConstructor->getLocation();
15741
0
    Sema::CompoundScopeRAII CompoundScope(*this);
15742
0
    CopyConstructor->setBody(
15743
0
        ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15744
0
            .getAs<Stmt>());
15745
0
    CopyConstructor->markUsed(Context);
15746
0
  }
15747
15748
0
  if (ASTMutationListener *L = getASTMutationListener()) {
15749
0
    L->CompletedImplicitDefinition(CopyConstructor);
15750
0
  }
15751
0
}
15752
15753
CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15754
0
                                                    CXXRecordDecl *ClassDecl) {
15755
0
  assert(ClassDecl->needsImplicitMoveConstructor());
15756
15757
0
  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15758
0
  if (DSM.isAlreadyBeingDeclared())
15759
0
    return nullptr;
15760
15761
0
  QualType ClassType = Context.getTypeDeclType(ClassDecl);
15762
15763
0
  QualType ArgType = ClassType;
15764
0
  ArgType = Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr,
15765
0
                                      ArgType, nullptr);
15766
0
  LangAS AS = getDefaultCXXMethodAddrSpace();
15767
0
  if (AS != LangAS::Default)
15768
0
    ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15769
0
  ArgType = Context.getRValueReferenceType(ArgType);
15770
15771
0
  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15772
0
                                                     CXXMoveConstructor,
15773
0
                                                     false);
15774
15775
0
  DeclarationName Name
15776
0
    = Context.DeclarationNames.getCXXConstructorName(
15777
0
                                           Context.getCanonicalType(ClassType));
15778
0
  SourceLocation ClassLoc = ClassDecl->getLocation();
15779
0
  DeclarationNameInfo NameInfo(Name, ClassLoc);
15780
15781
  // C++11 [class.copy]p11:
15782
  //   An implicitly-declared copy/move constructor is an inline public
15783
  //   member of its class.
15784
0
  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15785
0
      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15786
0
      ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15787
0
      /*isInline=*/true,
15788
0
      /*isImplicitlyDeclared=*/true,
15789
0
      Constexpr ? ConstexprSpecKind::Constexpr
15790
0
                : ConstexprSpecKind::Unspecified);
15791
0
  MoveConstructor->setAccess(AS_public);
15792
0
  MoveConstructor->setDefaulted();
15793
15794
0
  setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15795
15796
0
  if (getLangOpts().CUDA)
15797
0
    inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15798
0
                                            MoveConstructor,
15799
0
                                            /* ConstRHS */ false,
15800
0
                                            /* Diagnose */ false);
15801
15802
  // Add the parameter to the constructor.
15803
0
  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15804
0
                                               ClassLoc, ClassLoc,
15805
0
                                               /*IdentifierInfo=*/nullptr,
15806
0
                                               ArgType, /*TInfo=*/nullptr,
15807
0
                                               SC_None, nullptr);
15808
0
  MoveConstructor->setParams(FromParam);
15809
15810
0
  MoveConstructor->setTrivial(
15811
0
      ClassDecl->needsOverloadResolutionForMoveConstructor()
15812
0
          ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15813
0
          : ClassDecl->hasTrivialMoveConstructor());
15814
15815
0
  MoveConstructor->setTrivialForCall(
15816
0
      ClassDecl->hasAttr<TrivialABIAttr>() ||
15817
0
      (ClassDecl->needsOverloadResolutionForMoveConstructor()
15818
0
           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15819
0
                                    TAH_ConsiderTrivialABI)
15820
0
           : ClassDecl->hasTrivialMoveConstructorForCall()));
15821
15822
  // Note that we have declared this constructor.
15823
0
  ++getASTContext().NumImplicitMoveConstructorsDeclared;
15824
15825
0
  Scope *S = getScopeForContext(ClassDecl);
15826
0
  CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15827
15828
0
  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15829
0
    ClassDecl->setImplicitMoveConstructorIsDeleted();
15830
0
    SetDeclDeleted(MoveConstructor, ClassLoc);
15831
0
  }
15832
15833
0
  if (S)
15834
0
    PushOnScopeChains(MoveConstructor, S, false);
15835
0
  ClassDecl->addDecl(MoveConstructor);
15836
15837
0
  return MoveConstructor;
15838
0
}
15839
15840
void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15841
0
                                         CXXConstructorDecl *MoveConstructor) {
15842
0
  assert((MoveConstructor->isDefaulted() &&
15843
0
          MoveConstructor->isMoveConstructor() &&
15844
0
          !MoveConstructor->doesThisDeclarationHaveABody() &&
15845
0
          !MoveConstructor->isDeleted()) &&
15846
0
         "DefineImplicitMoveConstructor - call it for implicit move ctor");
15847
0
  if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15848
0
    return;
15849
15850
0
  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15851
0
  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15852
15853
0
  SynthesizedFunctionScope Scope(*this, MoveConstructor);
15854
15855
  // The exception specification is needed because we are defining the
15856
  // function.
15857
0
  ResolveExceptionSpec(CurrentLocation,
15858
0
                       MoveConstructor->getType()->castAs<FunctionProtoType>());
15859
0
  MarkVTableUsed(CurrentLocation, ClassDecl);
15860
15861
  // Add a context note for diagnostics produced after this point.
15862
0
  Scope.addContextNote(CurrentLocation);
15863
15864
0
  if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15865
0
    MoveConstructor->setInvalidDecl();
15866
0
  } else {
15867
0
    SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15868
0
                             ? MoveConstructor->getEndLoc()
15869
0
                             : MoveConstructor->getLocation();
15870
0
    Sema::CompoundScopeRAII CompoundScope(*this);
15871
0
    MoveConstructor->setBody(
15872
0
        ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15873
0
            .getAs<Stmt>());
15874
0
    MoveConstructor->markUsed(Context);
15875
0
  }
15876
15877
0
  if (ASTMutationListener *L = getASTMutationListener()) {
15878
0
    L->CompletedImplicitDefinition(MoveConstructor);
15879
0
  }
15880
0
}
15881
15882
0
bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15883
0
  return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15884
0
}
15885
15886
void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15887
                            SourceLocation CurrentLocation,
15888
0
                            CXXConversionDecl *Conv) {
15889
0
  SynthesizedFunctionScope Scope(*this, Conv);
15890
0
  assert(!Conv->getReturnType()->isUndeducedType());
15891
15892
0
  QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15893
0
  CallingConv CC =
15894
0
      ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15895
15896
0
  CXXRecordDecl *Lambda = Conv->getParent();
15897
0
  FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15898
0
  FunctionDecl *Invoker =
15899
0
      CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
15900
0
          ? CallOp
15901
0
          : Lambda->getLambdaStaticInvoker(CC);
15902
15903
0
  if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15904
0
    CallOp = InstantiateFunctionDeclaration(
15905
0
        CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15906
0
    if (!CallOp)
15907
0
      return;
15908
15909
0
    if (CallOp != Invoker) {
15910
0
      Invoker = InstantiateFunctionDeclaration(
15911
0
          Invoker->getDescribedFunctionTemplate(), TemplateArgs,
15912
0
          CurrentLocation);
15913
0
      if (!Invoker)
15914
0
        return;
15915
0
    }
15916
0
  }
15917
15918
0
  if (CallOp->isInvalidDecl())
15919
0
    return;
15920
15921
  // Mark the call operator referenced (and add to pending instantiations
15922
  // if necessary).
15923
  // For both the conversion and static-invoker template specializations
15924
  // we construct their body's in this function, so no need to add them
15925
  // to the PendingInstantiations.
15926
0
  MarkFunctionReferenced(CurrentLocation, CallOp);
15927
15928
0
  if (Invoker != CallOp) {
15929
    // Fill in the __invoke function with a dummy implementation. IR generation
15930
    // will fill in the actual details. Update its type in case it contained
15931
    // an 'auto'.
15932
0
    Invoker->markUsed(Context);
15933
0
    Invoker->setReferenced();
15934
0
    Invoker->setType(Conv->getReturnType()->getPointeeType());
15935
0
    Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15936
0
  }
15937
15938
  // Construct the body of the conversion function { return __invoke; }.
15939
0
  Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
15940
0
                                       Conv->getLocation());
15941
0
  assert(FunctionRef && "Can't refer to __invoke function?");
15942
0
  Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15943
0
  Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(),
15944
0
                                     Conv->getLocation(), Conv->getLocation()));
15945
0
  Conv->markUsed(Context);
15946
0
  Conv->setReferenced();
15947
15948
0
  if (ASTMutationListener *L = getASTMutationListener()) {
15949
0
    L->CompletedImplicitDefinition(Conv);
15950
0
    if (Invoker != CallOp)
15951
0
      L->CompletedImplicitDefinition(Invoker);
15952
0
  }
15953
0
}
15954
15955
void Sema::DefineImplicitLambdaToBlockPointerConversion(
15956
0
    SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
15957
0
  assert(!Conv->getParent()->isGenericLambda());
15958
15959
0
  SynthesizedFunctionScope Scope(*this, Conv);
15960
15961
  // Copy-initialize the lambda object as needed to capture it.
15962
0
  Expr *This = ActOnCXXThis(CurrentLocation).get();
15963
0
  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15964
15965
0
  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15966
0
                                                        Conv->getLocation(),
15967
0
                                                        Conv, DerefThis);
15968
15969
  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15970
  // behavior.  Note that only the general conversion function does this
15971
  // (since it's unusable otherwise); in the case where we inline the
15972
  // block literal, it has block literal lifetime semantics.
15973
0
  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15974
0
    BuildBlock = ImplicitCastExpr::Create(
15975
0
        Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15976
0
        BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15977
15978
0
  if (BuildBlock.isInvalid()) {
15979
0
    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15980
0
    Conv->setInvalidDecl();
15981
0
    return;
15982
0
  }
15983
15984
  // Create the return statement that returns the block from the conversion
15985
  // function.
15986
0
  StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15987
0
  if (Return.isInvalid()) {
15988
0
    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15989
0
    Conv->setInvalidDecl();
15990
0
    return;
15991
0
  }
15992
15993
  // Set the body of the conversion function.
15994
0
  Stmt *ReturnS = Return.get();
15995
0
  Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(),
15996
0
                                     Conv->getLocation(), Conv->getLocation()));
15997
0
  Conv->markUsed(Context);
15998
15999
  // We're done; notify the mutation listener, if any.
16000
0
  if (ASTMutationListener *L = getASTMutationListener()) {
16001
0
    L->CompletedImplicitDefinition(Conv);
16002
0
  }
16003
0
}
16004
16005
/// Determine whether the given list arguments contains exactly one
16006
/// "real" (non-default) argument.
16007
0
static bool hasOneRealArgument(MultiExprArg Args) {
16008
0
  switch (Args.size()) {
16009
0
  case 0:
16010
0
    return false;
16011
16012
0
  default:
16013
0
    if (!Args[1]->isDefaultArgument())
16014
0
      return false;
16015
16016
0
    [[fallthrough]];
16017
0
  case 1:
16018
0
    return !Args[0]->isDefaultArgument();
16019
0
  }
16020
16021
0
  return false;
16022
0
}
16023
16024
ExprResult Sema::BuildCXXConstructExpr(
16025
    SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16026
    CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16027
    bool HadMultipleCandidates, bool IsListInitialization,
16028
    bool IsStdInitListInitialization, bool RequiresZeroInit,
16029
0
    CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16030
0
  bool Elidable = false;
16031
16032
  // C++0x [class.copy]p34:
16033
  //   When certain criteria are met, an implementation is allowed to
16034
  //   omit the copy/move construction of a class object, even if the
16035
  //   copy/move constructor and/or destructor for the object have
16036
  //   side effects. [...]
16037
  //     - when a temporary class object that has not been bound to a
16038
  //       reference (12.2) would be copied/moved to a class object
16039
  //       with the same cv-unqualified type, the copy/move operation
16040
  //       can be omitted by constructing the temporary object
16041
  //       directly into the target of the omitted copy/move
16042
0
  if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16043
      // FIXME: Converting constructors should also be accepted.
16044
      // But to fix this, the logic that digs down into a CXXConstructExpr
16045
      // to find the source object needs to handle it.
16046
      // Right now it assumes the source object is passed directly as the
16047
      // first argument.
16048
0
      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
16049
0
    Expr *SubExpr = ExprArgs[0];
16050
    // FIXME: Per above, this is also incorrect if we want to accept
16051
    //        converting constructors, as isTemporaryObject will
16052
    //        reject temporaries with different type from the
16053
    //        CXXRecord itself.
16054
0
    Elidable = SubExpr->isTemporaryObject(
16055
0
        Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
16056
0
  }
16057
16058
0
  return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16059
0
                               FoundDecl, Constructor,
16060
0
                               Elidable, ExprArgs, HadMultipleCandidates,
16061
0
                               IsListInitialization,
16062
0
                               IsStdInitListInitialization, RequiresZeroInit,
16063
0
                               ConstructKind, ParenRange);
16064
0
}
16065
16066
ExprResult Sema::BuildCXXConstructExpr(
16067
    SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16068
    CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16069
    bool HadMultipleCandidates, bool IsListInitialization,
16070
    bool IsStdInitListInitialization, bool RequiresZeroInit,
16071
0
    CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16072
0
  if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
16073
0
    Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
16074
    // The only way to get here is if we did overlaod resolution to find the
16075
    // shadow decl, so we don't need to worry about re-checking the trailing
16076
    // requires clause.
16077
0
    if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
16078
0
      return ExprError();
16079
0
  }
16080
16081
0
  return BuildCXXConstructExpr(
16082
0
      ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
16083
0
      HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16084
0
      RequiresZeroInit, ConstructKind, ParenRange);
16085
0
}
16086
16087
/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16088
/// including handling of its default argument expressions.
16089
ExprResult Sema::BuildCXXConstructExpr(
16090
    SourceLocation ConstructLoc, QualType DeclInitType,
16091
    CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16092
    bool HadMultipleCandidates, bool IsListInitialization,
16093
    bool IsStdInitListInitialization, bool RequiresZeroInit,
16094
0
    CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16095
0
  assert(declaresSameEntity(
16096
0
             Constructor->getParent(),
16097
0
             DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16098
0
         "given constructor for wrong type");
16099
0
  MarkFunctionReferenced(ConstructLoc, Constructor);
16100
0
  if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
16101
0
    return ExprError();
16102
16103
0
  return CheckForImmediateInvocation(
16104
0
      CXXConstructExpr::Create(
16105
0
          Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
16106
0
          HadMultipleCandidates, IsListInitialization,
16107
0
          IsStdInitListInitialization, RequiresZeroInit,
16108
0
          static_cast<CXXConstructionKind>(ConstructKind), ParenRange),
16109
0
      Constructor);
16110
0
}
16111
16112
0
void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
16113
0
  if (VD->isInvalidDecl()) return;
16114
  // If initializing the variable failed, don't also diagnose problems with
16115
  // the destructor, they're likely related.
16116
0
  if (VD->getInit() && VD->getInit()->containsErrors())
16117
0
    return;
16118
16119
0
  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
16120
0
  if (ClassDecl->isInvalidDecl()) return;
16121
0
  if (ClassDecl->hasIrrelevantDestructor()) return;
16122
0
  if (ClassDecl->isDependentContext()) return;
16123
16124
0
  if (VD->isNoDestroy(getASTContext()))
16125
0
    return;
16126
16127
0
  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
16128
  // The result of `LookupDestructor` might be nullptr if the destructor is
16129
  // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16130
  // will not be selected by `CXXRecordDecl::getDestructor()`.
16131
0
  if (!Destructor)
16132
0
    return;
16133
  // If this is an array, we'll require the destructor during initialization, so
16134
  // we can skip over this. We still want to emit exit-time destructor warnings
16135
  // though.
16136
0
  if (!VD->getType()->isArrayType()) {
16137
0
    MarkFunctionReferenced(VD->getLocation(), Destructor);
16138
0
    CheckDestructorAccess(VD->getLocation(), Destructor,
16139
0
                          PDiag(diag::err_access_dtor_var)
16140
0
                              << VD->getDeclName() << VD->getType());
16141
0
    DiagnoseUseOfDecl(Destructor, VD->getLocation());
16142
0
  }
16143
16144
0
  if (Destructor->isTrivial()) return;
16145
16146
  // If the destructor is constexpr, check whether the variable has constant
16147
  // destruction now.
16148
0
  if (Destructor->isConstexpr()) {
16149
0
    bool HasConstantInit = false;
16150
0
    if (VD->getInit() && !VD->getInit()->isValueDependent())
16151
0
      HasConstantInit = VD->evaluateValue();
16152
0
    SmallVector<PartialDiagnosticAt, 8> Notes;
16153
0
    if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16154
0
        HasConstantInit) {
16155
0
      Diag(VD->getLocation(),
16156
0
           diag::err_constexpr_var_requires_const_destruction) << VD;
16157
0
      for (unsigned I = 0, N = Notes.size(); I != N; ++I)
16158
0
        Diag(Notes[I].first, Notes[I].second);
16159
0
    }
16160
0
  }
16161
16162
0
  if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context))
16163
0
    return;
16164
16165
  // Emit warning for non-trivial dtor in global scope (a real global,
16166
  // class-static, function-static).
16167
0
  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
16168
16169
  // TODO: this should be re-enabled for static locals by !CXAAtExit
16170
0
  if (!VD->isStaticLocal())
16171
0
    Diag(VD->getLocation(), diag::warn_global_destructor);
16172
0
}
16173
16174
/// Given a constructor and the set of arguments provided for the
16175
/// constructor, convert the arguments and add any required default arguments
16176
/// to form a proper call to this constructor.
16177
///
16178
/// \returns true if an error occurred, false otherwise.
16179
bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
16180
                                   QualType DeclInitType, MultiExprArg ArgsPtr,
16181
                                   SourceLocation Loc,
16182
                                   SmallVectorImpl<Expr *> &ConvertedArgs,
16183
                                   bool AllowExplicit,
16184
0
                                   bool IsListInitialization) {
16185
  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16186
0
  unsigned NumArgs = ArgsPtr.size();
16187
0
  Expr **Args = ArgsPtr.data();
16188
16189
0
  const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16190
0
  unsigned NumParams = Proto->getNumParams();
16191
16192
  // If too few arguments are available, we'll fill in the rest with defaults.
16193
0
  if (NumArgs < NumParams)
16194
0
    ConvertedArgs.reserve(NumParams);
16195
0
  else
16196
0
    ConvertedArgs.reserve(NumArgs);
16197
16198
0
  VariadicCallType CallType =
16199
0
    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
16200
0
  SmallVector<Expr *, 8> AllArgs;
16201
0
  bool Invalid = GatherArgumentsForCall(
16202
0
      Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
16203
0
      CallType, AllowExplicit, IsListInitialization);
16204
0
  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
16205
16206
0
  DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
16207
16208
0
  CheckConstructorCall(Constructor, DeclInitType,
16209
0
                       llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
16210
0
                       Loc);
16211
16212
0
  return Invalid;
16213
0
}
16214
16215
static inline bool
16216
CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
16217
0
                                       const FunctionDecl *FnDecl) {
16218
0
  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16219
0
  if (isa<NamespaceDecl>(DC)) {
16220
0
    return SemaRef.Diag(FnDecl->getLocation(),
16221
0
                        diag::err_operator_new_delete_declared_in_namespace)
16222
0
      << FnDecl->getDeclName();
16223
0
  }
16224
16225
0
  if (isa<TranslationUnitDecl>(DC) &&
16226
0
      FnDecl->getStorageClass() == SC_Static) {
16227
0
    return SemaRef.Diag(FnDecl->getLocation(),
16228
0
                        diag::err_operator_new_delete_declared_static)
16229
0
      << FnDecl->getDeclName();
16230
0
  }
16231
16232
0
  return false;
16233
0
}
16234
16235
static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
16236
0
                                             const PointerType *PtrTy) {
16237
0
  auto &Ctx = SemaRef.Context;
16238
0
  Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16239
0
  PtrQuals.removeAddressSpace();
16240
0
  return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
16241
0
      PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
16242
0
}
16243
16244
static inline bool
16245
CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
16246
                            CanQualType ExpectedResultType,
16247
                            CanQualType ExpectedFirstParamType,
16248
                            unsigned DependentParamTypeDiag,
16249
0
                            unsigned InvalidParamTypeDiag) {
16250
0
  QualType ResultType =
16251
0
      FnDecl->getType()->castAs<FunctionType>()->getReturnType();
16252
16253
0
  if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16254
    // The operator is valid on any address space for OpenCL.
16255
    // Drop address space from actual and expected result types.
16256
0
    if (const auto *PtrTy = ResultType->getAs<PointerType>())
16257
0
      ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16258
16259
0
    if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
16260
0
      ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16261
0
  }
16262
16263
  // Check that the result type is what we expect.
16264
0
  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
16265
    // Reject even if the type is dependent; an operator delete function is
16266
    // required to have a non-dependent result type.
16267
0
    return SemaRef.Diag(
16268
0
               FnDecl->getLocation(),
16269
0
               ResultType->isDependentType()
16270
0
                   ? diag::err_operator_new_delete_dependent_result_type
16271
0
                   : diag::err_operator_new_delete_invalid_result_type)
16272
0
           << FnDecl->getDeclName() << ExpectedResultType;
16273
0
  }
16274
16275
  // A function template must have at least 2 parameters.
16276
0
  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
16277
0
    return SemaRef.Diag(FnDecl->getLocation(),
16278
0
                      diag::err_operator_new_delete_template_too_few_parameters)
16279
0
        << FnDecl->getDeclName();
16280
16281
  // The function decl must have at least 1 parameter.
16282
0
  if (FnDecl->getNumParams() == 0)
16283
0
    return SemaRef.Diag(FnDecl->getLocation(),
16284
0
                        diag::err_operator_new_delete_too_few_parameters)
16285
0
      << FnDecl->getDeclName();
16286
16287
0
  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
16288
0
  if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16289
    // The operator is valid on any address space for OpenCL.
16290
    // Drop address space from actual and expected first parameter types.
16291
0
    if (const auto *PtrTy =
16292
0
            FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
16293
0
      FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16294
16295
0
    if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
16296
0
      ExpectedFirstParamType =
16297
0
          RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
16298
0
  }
16299
16300
  // Check that the first parameter type is what we expect.
16301
0
  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
16302
0
      ExpectedFirstParamType) {
16303
    // The first parameter type is not allowed to be dependent. As a tentative
16304
    // DR resolution, we allow a dependent parameter type if it is the right
16305
    // type anyway, to allow destroying operator delete in class templates.
16306
0
    return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
16307
0
                                                   ? DependentParamTypeDiag
16308
0
                                                   : InvalidParamTypeDiag)
16309
0
           << FnDecl->getDeclName() << ExpectedFirstParamType;
16310
0
  }
16311
16312
0
  return false;
16313
0
}
16314
16315
static bool
16316
0
CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
16317
  // C++ [basic.stc.dynamic.allocation]p1:
16318
  //   A program is ill-formed if an allocation function is declared in a
16319
  //   namespace scope other than global scope or declared static in global
16320
  //   scope.
16321
0
  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16322
0
    return true;
16323
16324
0
  CanQualType SizeTy =
16325
0
    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
16326
16327
  // C++ [basic.stc.dynamic.allocation]p1:
16328
  //  The return type shall be void*. The first parameter shall have type
16329
  //  std::size_t.
16330
0
  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
16331
0
                                  SizeTy,
16332
0
                                  diag::err_operator_new_dependent_param_type,
16333
0
                                  diag::err_operator_new_param_type))
16334
0
    return true;
16335
16336
  // C++ [basic.stc.dynamic.allocation]p1:
16337
  //  The first parameter shall not have an associated default argument.
16338
0
  if (FnDecl->getParamDecl(0)->hasDefaultArg())
16339
0
    return SemaRef.Diag(FnDecl->getLocation(),
16340
0
                        diag::err_operator_new_default_arg)
16341
0
      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
16342
16343
0
  return false;
16344
0
}
16345
16346
static bool
16347
0
CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16348
  // C++ [basic.stc.dynamic.deallocation]p1:
16349
  //   A program is ill-formed if deallocation functions are declared in a
16350
  //   namespace scope other than global scope or declared static in global
16351
  //   scope.
16352
0
  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16353
0
    return true;
16354
16355
0
  auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
16356
16357
  // C++ P0722:
16358
  //   Within a class C, the first parameter of a destroying operator delete
16359
  //   shall be of type C *. The first parameter of any other deallocation
16360
  //   function shall be of type void *.
16361
0
  CanQualType ExpectedFirstParamType =
16362
0
      MD && MD->isDestroyingOperatorDelete()
16363
0
          ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
16364
0
                SemaRef.Context.getRecordType(MD->getParent())))
16365
0
          : SemaRef.Context.VoidPtrTy;
16366
16367
  // C++ [basic.stc.dynamic.deallocation]p2:
16368
  //   Each deallocation function shall return void
16369
0
  if (CheckOperatorNewDeleteTypes(
16370
0
          SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
16371
0
          diag::err_operator_delete_dependent_param_type,
16372
0
          diag::err_operator_delete_param_type))
16373
0
    return true;
16374
16375
  // C++ P0722:
16376
  //   A destroying operator delete shall be a usual deallocation function.
16377
0
  if (MD && !MD->getParent()->isDependentContext() &&
16378
0
      MD->isDestroyingOperatorDelete() &&
16379
0
      !SemaRef.isUsualDeallocationFunction(MD)) {
16380
0
    SemaRef.Diag(MD->getLocation(),
16381
0
                 diag::err_destroying_operator_delete_not_usual);
16382
0
    return true;
16383
0
  }
16384
16385
0
  return false;
16386
0
}
16387
16388
/// CheckOverloadedOperatorDeclaration - Check whether the declaration
16389
/// of this overloaded operator is well-formed. If so, returns false;
16390
/// otherwise, emits appropriate diagnostics and returns true.
16391
0
bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
16392
0
  assert(FnDecl && FnDecl->isOverloadedOperator() &&
16393
0
         "Expected an overloaded operator declaration");
16394
16395
0
  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
16396
16397
  // C++ [over.oper]p5:
16398
  //   The allocation and deallocation functions, operator new,
16399
  //   operator new[], operator delete and operator delete[], are
16400
  //   described completely in 3.7.3. The attributes and restrictions
16401
  //   found in the rest of this subclause do not apply to them unless
16402
  //   explicitly stated in 3.7.3.
16403
0
  if (Op == OO_Delete || Op == OO_Array_Delete)
16404
0
    return CheckOperatorDeleteDeclaration(*this, FnDecl);
16405
16406
0
  if (Op == OO_New || Op == OO_Array_New)
16407
0
    return CheckOperatorNewDeclaration(*this, FnDecl);
16408
16409
  // C++ [over.oper]p7:
16410
  //   An operator function shall either be a member function or
16411
  //   be a non-member function and have at least one parameter
16412
  //   whose type is a class, a reference to a class, an enumeration,
16413
  //   or a reference to an enumeration.
16414
  // Note: Before C++23, a member function could not be static. The only member
16415
  //       function allowed to be static is the call operator function.
16416
0
  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
16417
0
    if (MethodDecl->isStatic()) {
16418
0
      if (Op == OO_Call || Op == OO_Subscript)
16419
0
        Diag(FnDecl->getLocation(),
16420
0
             (LangOpts.CPlusPlus23
16421
0
                  ? diag::warn_cxx20_compat_operator_overload_static
16422
0
                  : diag::ext_operator_overload_static))
16423
0
            << FnDecl;
16424
0
      else
16425
0
        return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
16426
0
               << FnDecl;
16427
0
    }
16428
0
  } else {
16429
0
    bool ClassOrEnumParam = false;
16430
0
    for (auto *Param : FnDecl->parameters()) {
16431
0
      QualType ParamType = Param->getType().getNonReferenceType();
16432
0
      if (ParamType->isDependentType() || ParamType->isRecordType() ||
16433
0
          ParamType->isEnumeralType()) {
16434
0
        ClassOrEnumParam = true;
16435
0
        break;
16436
0
      }
16437
0
    }
16438
16439
0
    if (!ClassOrEnumParam)
16440
0
      return Diag(FnDecl->getLocation(),
16441
0
                  diag::err_operator_overload_needs_class_or_enum)
16442
0
        << FnDecl->getDeclName();
16443
0
  }
16444
16445
  // C++ [over.oper]p8:
16446
  //   An operator function cannot have default arguments (8.3.6),
16447
  //   except where explicitly stated below.
16448
  //
16449
  // Only the function-call operator (C++ [over.call]p1) and the subscript
16450
  // operator (CWG2507) allow default arguments.
16451
0
  if (Op != OO_Call) {
16452
0
    ParmVarDecl *FirstDefaultedParam = nullptr;
16453
0
    for (auto *Param : FnDecl->parameters()) {
16454
0
      if (Param->hasDefaultArg()) {
16455
0
        FirstDefaultedParam = Param;
16456
0
        break;
16457
0
      }
16458
0
    }
16459
0
    if (FirstDefaultedParam) {
16460
0
      if (Op == OO_Subscript) {
16461
0
        Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16462
0
                                        ? diag::ext_subscript_overload
16463
0
                                        : diag::error_subscript_overload)
16464
0
            << FnDecl->getDeclName() << 1
16465
0
            << FirstDefaultedParam->getDefaultArgRange();
16466
0
      } else {
16467
0
        return Diag(FirstDefaultedParam->getLocation(),
16468
0
                    diag::err_operator_overload_default_arg)
16469
0
               << FnDecl->getDeclName()
16470
0
               << FirstDefaultedParam->getDefaultArgRange();
16471
0
      }
16472
0
    }
16473
0
  }
16474
16475
0
  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16476
0
    { false, false, false }
16477
0
#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16478
0
    , { Unary, Binary, MemberOnly }
16479
0
#include "clang/Basic/OperatorKinds.def"
16480
0
  };
16481
16482
0
  bool CanBeUnaryOperator = OperatorUses[Op][0];
16483
0
  bool CanBeBinaryOperator = OperatorUses[Op][1];
16484
0
  bool MustBeMemberOperator = OperatorUses[Op][2];
16485
16486
  // C++ [over.oper]p8:
16487
  //   [...] Operator functions cannot have more or fewer parameters
16488
  //   than the number required for the corresponding operator, as
16489
  //   described in the rest of this subclause.
16490
0
  unsigned NumParams = FnDecl->getNumParams() +
16491
0
                       (isa<CXXMethodDecl>(FnDecl) &&
16492
0
                                !FnDecl->hasCXXExplicitFunctionObjectParameter()
16493
0
                            ? 1
16494
0
                            : 0);
16495
0
  if (Op != OO_Call && Op != OO_Subscript &&
16496
0
      ((NumParams == 1 && !CanBeUnaryOperator) ||
16497
0
       (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16498
0
       (NumParams > 2))) {
16499
    // We have the wrong number of parameters.
16500
0
    unsigned ErrorKind;
16501
0
    if (CanBeUnaryOperator && CanBeBinaryOperator) {
16502
0
      ErrorKind = 2;  // 2 -> unary or binary.
16503
0
    } else if (CanBeUnaryOperator) {
16504
0
      ErrorKind = 0;  // 0 -> unary
16505
0
    } else {
16506
0
      assert(CanBeBinaryOperator &&
16507
0
             "All non-call overloaded operators are unary or binary!");
16508
0
      ErrorKind = 1;  // 1 -> binary
16509
0
    }
16510
0
    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16511
0
      << FnDecl->getDeclName() << NumParams << ErrorKind;
16512
0
  }
16513
16514
0
  if (Op == OO_Subscript && NumParams != 2) {
16515
0
    Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23
16516
0
                                    ? diag::ext_subscript_overload
16517
0
                                    : diag::error_subscript_overload)
16518
0
        << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16519
0
  }
16520
16521
  // Overloaded operators other than operator() and operator[] cannot be
16522
  // variadic.
16523
0
  if (Op != OO_Call &&
16524
0
      FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16525
0
    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16526
0
           << FnDecl->getDeclName();
16527
0
  }
16528
16529
  // Some operators must be member functions.
16530
0
  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16531
0
    return Diag(FnDecl->getLocation(),
16532
0
                diag::err_operator_overload_must_be_member)
16533
0
      << FnDecl->getDeclName();
16534
0
  }
16535
16536
  // C++ [over.inc]p1:
16537
  //   The user-defined function called operator++ implements the
16538
  //   prefix and postfix ++ operator. If this function is a member
16539
  //   function with no parameters, or a non-member function with one
16540
  //   parameter of class or enumeration type, it defines the prefix
16541
  //   increment operator ++ for objects of that type. If the function
16542
  //   is a member function with one parameter (which shall be of type
16543
  //   int) or a non-member function with two parameters (the second
16544
  //   of which shall be of type int), it defines the postfix
16545
  //   increment operator ++ for objects of that type.
16546
0
  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16547
0
    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16548
0
    QualType ParamType = LastParam->getType();
16549
16550
0
    if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16551
0
        !ParamType->isDependentType())
16552
0
      return Diag(LastParam->getLocation(),
16553
0
                  diag::err_operator_overload_post_incdec_must_be_int)
16554
0
        << LastParam->getType() << (Op == OO_MinusMinus);
16555
0
  }
16556
16557
0
  return false;
16558
0
}
16559
16560
static bool
16561
checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16562
0
                                          FunctionTemplateDecl *TpDecl) {
16563
0
  TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16564
16565
  // Must have one or two template parameters.
16566
0
  if (TemplateParams->size() == 1) {
16567
0
    NonTypeTemplateParmDecl *PmDecl =
16568
0
        dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16569
16570
    // The template parameter must be a char parameter pack.
16571
0
    if (PmDecl && PmDecl->isTemplateParameterPack() &&
16572
0
        SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16573
0
      return false;
16574
16575
    // C++20 [over.literal]p5:
16576
    //   A string literal operator template is a literal operator template
16577
    //   whose template-parameter-list comprises a single non-type
16578
    //   template-parameter of class type.
16579
    //
16580
    // As a DR resolution, we also allow placeholders for deduced class
16581
    // template specializations.
16582
0
    if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16583
0
        !PmDecl->isTemplateParameterPack() &&
16584
0
        (PmDecl->getType()->isRecordType() ||
16585
0
         PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16586
0
      return false;
16587
0
  } else if (TemplateParams->size() == 2) {
16588
0
    TemplateTypeParmDecl *PmType =
16589
0
        dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16590
0
    NonTypeTemplateParmDecl *PmArgs =
16591
0
        dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16592
16593
    // The second template parameter must be a parameter pack with the
16594
    // first template parameter as its type.
16595
0
    if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16596
0
        PmArgs->isTemplateParameterPack()) {
16597
0
      const TemplateTypeParmType *TArgs =
16598
0
          PmArgs->getType()->getAs<TemplateTypeParmType>();
16599
0
      if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16600
0
          TArgs->getIndex() == PmType->getIndex()) {
16601
0
        if (!SemaRef.inTemplateInstantiation())
16602
0
          SemaRef.Diag(TpDecl->getLocation(),
16603
0
                       diag::ext_string_literal_operator_template);
16604
0
        return false;
16605
0
      }
16606
0
    }
16607
0
  }
16608
16609
0
  SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16610
0
               diag::err_literal_operator_template)
16611
0
      << TpDecl->getTemplateParameters()->getSourceRange();
16612
0
  return true;
16613
0
}
16614
16615
/// CheckLiteralOperatorDeclaration - Check whether the declaration
16616
/// of this literal operator function is well-formed. If so, returns
16617
/// false; otherwise, emits appropriate diagnostics and returns true.
16618
0
bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16619
0
  if (isa<CXXMethodDecl>(FnDecl)) {
16620
0
    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16621
0
      << FnDecl->getDeclName();
16622
0
    return true;
16623
0
  }
16624
16625
0
  if (FnDecl->isExternC()) {
16626
0
    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16627
0
    if (const LinkageSpecDecl *LSD =
16628
0
            FnDecl->getDeclContext()->getExternCContext())
16629
0
      Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16630
0
    return true;
16631
0
  }
16632
16633
  // This might be the definition of a literal operator template.
16634
0
  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16635
16636
  // This might be a specialization of a literal operator template.
16637
0
  if (!TpDecl)
16638
0
    TpDecl = FnDecl->getPrimaryTemplate();
16639
16640
  // template <char...> type operator "" name() and
16641
  // template <class T, T...> type operator "" name() are the only valid
16642
  // template signatures, and the only valid signatures with no parameters.
16643
  //
16644
  // C++20 also allows template <SomeClass T> type operator "" name().
16645
0
  if (TpDecl) {
16646
0
    if (FnDecl->param_size() != 0) {
16647
0
      Diag(FnDecl->getLocation(),
16648
0
           diag::err_literal_operator_template_with_params);
16649
0
      return true;
16650
0
    }
16651
16652
0
    if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16653
0
      return true;
16654
16655
0
  } else if (FnDecl->param_size() == 1) {
16656
0
    const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16657
16658
0
    QualType ParamType = Param->getType().getUnqualifiedType();
16659
16660
    // Only unsigned long long int, long double, any character type, and const
16661
    // char * are allowed as the only parameters.
16662
0
    if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16663
0
        ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16664
0
        Context.hasSameType(ParamType, Context.CharTy) ||
16665
0
        Context.hasSameType(ParamType, Context.WideCharTy) ||
16666
0
        Context.hasSameType(ParamType, Context.Char8Ty) ||
16667
0
        Context.hasSameType(ParamType, Context.Char16Ty) ||
16668
0
        Context.hasSameType(ParamType, Context.Char32Ty)) {
16669
0
    } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16670
0
      QualType InnerType = Ptr->getPointeeType();
16671
16672
      // Pointer parameter must be a const char *.
16673
0
      if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16674
0
                                Context.CharTy) &&
16675
0
            InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16676
0
        Diag(Param->getSourceRange().getBegin(),
16677
0
             diag::err_literal_operator_param)
16678
0
            << ParamType << "'const char *'" << Param->getSourceRange();
16679
0
        return true;
16680
0
      }
16681
16682
0
    } else if (ParamType->isRealFloatingType()) {
16683
0
      Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16684
0
          << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16685
0
      return true;
16686
16687
0
    } else if (ParamType->isIntegerType()) {
16688
0
      Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16689
0
          << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16690
0
      return true;
16691
16692
0
    } else {
16693
0
      Diag(Param->getSourceRange().getBegin(),
16694
0
           diag::err_literal_operator_invalid_param)
16695
0
          << ParamType << Param->getSourceRange();
16696
0
      return true;
16697
0
    }
16698
16699
0
  } else if (FnDecl->param_size() == 2) {
16700
0
    FunctionDecl::param_iterator Param = FnDecl->param_begin();
16701
16702
    // First, verify that the first parameter is correct.
16703
16704
0
    QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16705
16706
    // Two parameter function must have a pointer to const as a
16707
    // first parameter; let's strip those qualifiers.
16708
0
    const PointerType *PT = FirstParamType->getAs<PointerType>();
16709
16710
0
    if (!PT) {
16711
0
      Diag((*Param)->getSourceRange().getBegin(),
16712
0
           diag::err_literal_operator_param)
16713
0
          << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16714
0
      return true;
16715
0
    }
16716
16717
0
    QualType PointeeType = PT->getPointeeType();
16718
    // First parameter must be const
16719
0
    if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16720
0
      Diag((*Param)->getSourceRange().getBegin(),
16721
0
           diag::err_literal_operator_param)
16722
0
          << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16723
0
      return true;
16724
0
    }
16725
16726
0
    QualType InnerType = PointeeType.getUnqualifiedType();
16727
    // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16728
    // const char32_t* are allowed as the first parameter to a two-parameter
16729
    // function
16730
0
    if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16731
0
          Context.hasSameType(InnerType, Context.WideCharTy) ||
16732
0
          Context.hasSameType(InnerType, Context.Char8Ty) ||
16733
0
          Context.hasSameType(InnerType, Context.Char16Ty) ||
16734
0
          Context.hasSameType(InnerType, Context.Char32Ty))) {
16735
0
      Diag((*Param)->getSourceRange().getBegin(),
16736
0
           diag::err_literal_operator_param)
16737
0
          << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16738
0
      return true;
16739
0
    }
16740
16741
    // Move on to the second and final parameter.
16742
0
    ++Param;
16743
16744
    // The second parameter must be a std::size_t.
16745
0
    QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16746
0
    if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16747
0
      Diag((*Param)->getSourceRange().getBegin(),
16748
0
           diag::err_literal_operator_param)
16749
0
          << SecondParamType << Context.getSizeType()
16750
0
          << (*Param)->getSourceRange();
16751
0
      return true;
16752
0
    }
16753
0
  } else {
16754
0
    Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16755
0
    return true;
16756
0
  }
16757
16758
  // Parameters are good.
16759
16760
  // A parameter-declaration-clause containing a default argument is not
16761
  // equivalent to any of the permitted forms.
16762
0
  for (auto *Param : FnDecl->parameters()) {
16763
0
    if (Param->hasDefaultArg()) {
16764
0
      Diag(Param->getDefaultArgRange().getBegin(),
16765
0
           diag::err_literal_operator_default_argument)
16766
0
        << Param->getDefaultArgRange();
16767
0
      break;
16768
0
    }
16769
0
  }
16770
16771
0
  const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
16772
0
  ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
16773
0
  if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
16774
0
      !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16775
    // C++23 [usrlit.suffix]p1:
16776
    //   Literal suffix identifiers that do not start with an underscore are
16777
    //   reserved for future standardization. Literal suffix identifiers that
16778
    //   contain a double underscore __ are reserved for use by C++
16779
    //   implementations.
16780
0
    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16781
0
        << static_cast<int>(Status)
16782
0
        << StringLiteralParser::isValidUDSuffix(getLangOpts(), II->getName());
16783
0
  }
16784
16785
0
  return false;
16786
0
}
16787
16788
/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16789
/// linkage specification, including the language and (if present)
16790
/// the '{'. ExternLoc is the location of the 'extern', Lang is the
16791
/// language string literal. LBraceLoc, if valid, provides the location of
16792
/// the '{' brace. Otherwise, this linkage specification does not
16793
/// have any braces.
16794
Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16795
                                           Expr *LangStr,
16796
0
                                           SourceLocation LBraceLoc) {
16797
0
  StringLiteral *Lit = cast<StringLiteral>(LangStr);
16798
0
  assert(Lit->isUnevaluated() && "Unexpected string literal kind");
16799
16800
0
  StringRef Lang = Lit->getString();
16801
0
  LinkageSpecLanguageIDs Language;
16802
0
  if (Lang == "C")
16803
0
    Language = LinkageSpecLanguageIDs::C;
16804
0
  else if (Lang == "C++")
16805
0
    Language = LinkageSpecLanguageIDs::CXX;
16806
0
  else {
16807
0
    Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16808
0
      << LangStr->getSourceRange();
16809
0
    return nullptr;
16810
0
  }
16811
16812
  // FIXME: Add all the various semantics of linkage specifications
16813
16814
0
  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16815
0
                                               LangStr->getExprLoc(), Language,
16816
0
                                               LBraceLoc.isValid());
16817
16818
  /// C++ [module.unit]p7.2.3
16819
  /// - Otherwise, if the declaration
16820
  ///   - ...
16821
  ///   - ...
16822
  ///   - appears within a linkage-specification,
16823
  ///   it is attached to the global module.
16824
  ///
16825
  /// If the declaration is already in global module fragment, we don't
16826
  /// need to attach it again.
16827
0
  if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16828
0
    Module *GlobalModule = PushImplicitGlobalModuleFragment(ExternLoc);
16829
0
    D->setLocalOwningModule(GlobalModule);
16830
0
  }
16831
16832
0
  CurContext->addDecl(D);
16833
0
  PushDeclContext(S, D);
16834
0
  return D;
16835
0
}
16836
16837
/// ActOnFinishLinkageSpecification - Complete the definition of
16838
/// the C++ linkage specification LinkageSpec. If RBraceLoc is
16839
/// valid, it's the position of the closing '}' brace in a linkage
16840
/// specification that uses braces.
16841
Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16842
                                            Decl *LinkageSpec,
16843
0
                                            SourceLocation RBraceLoc) {
16844
0
  if (RBraceLoc.isValid()) {
16845
0
    LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16846
0
    LSDecl->setRBraceLoc(RBraceLoc);
16847
0
  }
16848
16849
  // If the current module doesn't has Parent, it implies that the
16850
  // LinkageSpec isn't in the module created by itself. So we don't
16851
  // need to pop it.
16852
0
  if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16853
0
      getCurrentModule()->isImplicitGlobalModule() &&
16854
0
      getCurrentModule()->Parent)
16855
0
    PopImplicitGlobalModuleFragment();
16856
16857
0
  PopDeclContext();
16858
0
  return LinkageSpec;
16859
0
}
16860
16861
Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16862
                                  const ParsedAttributesView &AttrList,
16863
439
                                  SourceLocation SemiLoc) {
16864
439
  Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16865
  // Attribute declarations appertain to empty declaration so we handle
16866
  // them here.
16867
439
  ProcessDeclAttributeList(S, ED, AttrList);
16868
16869
439
  CurContext->addDecl(ED);
16870
439
  return ED;
16871
439
}
16872
16873
/// Perform semantic analysis for the variable declaration that
16874
/// occurs within a C++ catch clause, returning the newly-created
16875
/// variable.
16876
VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16877
                                         TypeSourceInfo *TInfo,
16878
                                         SourceLocation StartLoc,
16879
                                         SourceLocation Loc,
16880
0
                                         IdentifierInfo *Name) {
16881
0
  bool Invalid = false;
16882
0
  QualType ExDeclType = TInfo->getType();
16883
16884
  // Arrays and functions decay.
16885
0
  if (ExDeclType->isArrayType())
16886
0
    ExDeclType = Context.getArrayDecayedType(ExDeclType);
16887
0
  else if (ExDeclType->isFunctionType())
16888
0
    ExDeclType = Context.getPointerType(ExDeclType);
16889
16890
  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16891
  // The exception-declaration shall not denote a pointer or reference to an
16892
  // incomplete type, other than [cv] void*.
16893
  // N2844 forbids rvalue references.
16894
0
  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16895
0
    Diag(Loc, diag::err_catch_rvalue_ref);
16896
0
    Invalid = true;
16897
0
  }
16898
16899
0
  if (ExDeclType->isVariablyModifiedType()) {
16900
0
    Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16901
0
    Invalid = true;
16902
0
  }
16903
16904
0
  QualType BaseType = ExDeclType;
16905
0
  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16906
0
  unsigned DK = diag::err_catch_incomplete;
16907
0
  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16908
0
    BaseType = Ptr->getPointeeType();
16909
0
    Mode = 1;
16910
0
    DK = diag::err_catch_incomplete_ptr;
16911
0
  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16912
    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16913
0
    BaseType = Ref->getPointeeType();
16914
0
    Mode = 2;
16915
0
    DK = diag::err_catch_incomplete_ref;
16916
0
  }
16917
0
  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16918
0
      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16919
0
    Invalid = true;
16920
16921
0
  if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
16922
0
    Diag(Loc, diag::err_wasm_reftype_tc) << 1;
16923
0
    Invalid = true;
16924
0
  }
16925
16926
0
  if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16927
0
    Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16928
0
    Invalid = true;
16929
0
  }
16930
16931
0
  if (!Invalid && !ExDeclType->isDependentType() &&
16932
0
      RequireNonAbstractType(Loc, ExDeclType,
16933
0
                             diag::err_abstract_type_in_decl,
16934
0
                             AbstractVariableType))
16935
0
    Invalid = true;
16936
16937
  // Only the non-fragile NeXT runtime currently supports C++ catches
16938
  // of ObjC types, and no runtime supports catching ObjC types by value.
16939
0
  if (!Invalid && getLangOpts().ObjC) {
16940
0
    QualType T = ExDeclType;
16941
0
    if (const ReferenceType *RT = T->getAs<ReferenceType>())
16942
0
      T = RT->getPointeeType();
16943
16944
0
    if (T->isObjCObjectType()) {
16945
0
      Diag(Loc, diag::err_objc_object_catch);
16946
0
      Invalid = true;
16947
0
    } else if (T->isObjCObjectPointerType()) {
16948
      // FIXME: should this be a test for macosx-fragile specifically?
16949
0
      if (getLangOpts().ObjCRuntime.isFragile())
16950
0
        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16951
0
    }
16952
0
  }
16953
16954
0
  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16955
0
                                    ExDeclType, TInfo, SC_None);
16956
0
  ExDecl->setExceptionVariable(true);
16957
16958
  // In ARC, infer 'retaining' for variables of retainable type.
16959
0
  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16960
0
    Invalid = true;
16961
16962
0
  if (!Invalid && !ExDeclType->isDependentType()) {
16963
0
    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16964
      // Insulate this from anything else we might currently be parsing.
16965
0
      EnterExpressionEvaluationContext scope(
16966
0
          *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16967
16968
      // C++ [except.handle]p16:
16969
      //   The object declared in an exception-declaration or, if the
16970
      //   exception-declaration does not specify a name, a temporary (12.2) is
16971
      //   copy-initialized (8.5) from the exception object. [...]
16972
      //   The object is destroyed when the handler exits, after the destruction
16973
      //   of any automatic objects initialized within the handler.
16974
      //
16975
      // We just pretend to initialize the object with itself, then make sure
16976
      // it can be destroyed later.
16977
0
      QualType initType = Context.getExceptionObjectType(ExDeclType);
16978
16979
0
      InitializedEntity entity =
16980
0
        InitializedEntity::InitializeVariable(ExDecl);
16981
0
      InitializationKind initKind =
16982
0
        InitializationKind::CreateCopy(Loc, SourceLocation());
16983
16984
0
      Expr *opaqueValue =
16985
0
        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16986
0
      InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16987
0
      ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16988
0
      if (result.isInvalid())
16989
0
        Invalid = true;
16990
0
      else {
16991
        // If the constructor used was non-trivial, set this as the
16992
        // "initializer".
16993
0
        CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16994
0
        if (!construct->getConstructor()->isTrivial()) {
16995
0
          Expr *init = MaybeCreateExprWithCleanups(construct);
16996
0
          ExDecl->setInit(init);
16997
0
        }
16998
16999
        // And make sure it's destructable.
17000
0
        FinalizeVarWithDestructor(ExDecl, recordType);
17001
0
      }
17002
0
    }
17003
0
  }
17004
17005
0
  if (Invalid)
17006
0
    ExDecl->setInvalidDecl();
17007
17008
0
  return ExDecl;
17009
0
}
17010
17011
/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
17012
/// handler.
17013
0
Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
17014
0
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17015
0
  bool Invalid = D.isInvalidType();
17016
17017
  // Check for unexpanded parameter packs.
17018
0
  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17019
0
                                      UPPC_ExceptionType)) {
17020
0
    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
17021
0
                                             D.getIdentifierLoc());
17022
0
    Invalid = true;
17023
0
  }
17024
17025
0
  IdentifierInfo *II = D.getIdentifier();
17026
0
  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
17027
0
                                             LookupOrdinaryName,
17028
0
                                             ForVisibleRedeclaration)) {
17029
    // The scope should be freshly made just for us. There is just no way
17030
    // it contains any previous declaration, except for function parameters in
17031
    // a function-try-block's catch statement.
17032
0
    assert(!S->isDeclScope(PrevDecl));
17033
0
    if (isDeclInScope(PrevDecl, CurContext, S)) {
17034
0
      Diag(D.getIdentifierLoc(), diag::err_redefinition)
17035
0
        << D.getIdentifier();
17036
0
      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
17037
0
      Invalid = true;
17038
0
    } else if (PrevDecl->isTemplateParameter())
17039
      // Maybe we will complain about the shadowed template parameter.
17040
0
      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17041
0
  }
17042
17043
0
  if (D.getCXXScopeSpec().isSet() && !Invalid) {
17044
0
    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
17045
0
      << D.getCXXScopeSpec().getRange();
17046
0
    Invalid = true;
17047
0
  }
17048
17049
0
  VarDecl *ExDecl = BuildExceptionDeclaration(
17050
0
      S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
17051
0
  if (Invalid)
17052
0
    ExDecl->setInvalidDecl();
17053
17054
  // Add the exception declaration into this scope.
17055
0
  if (II)
17056
0
    PushOnScopeChains(ExDecl, S);
17057
0
  else
17058
0
    CurContext->addDecl(ExDecl);
17059
17060
0
  ProcessDeclAttributes(S, ExDecl, D);
17061
0
  return ExDecl;
17062
0
}
17063
17064
Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17065
                                         Expr *AssertExpr,
17066
                                         Expr *AssertMessageExpr,
17067
0
                                         SourceLocation RParenLoc) {
17068
0
  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
17069
0
    return nullptr;
17070
17071
0
  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17072
0
                                      AssertMessageExpr, RParenLoc, false);
17073
0
}
17074
17075
0
static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17076
0
  switch (BTK) {
17077
0
  case BuiltinType::Char_S:
17078
0
  case BuiltinType::Char_U:
17079
0
    break;
17080
0
  case BuiltinType::Char8:
17081
0
    OS << "u8";
17082
0
    break;
17083
0
  case BuiltinType::Char16:
17084
0
    OS << 'u';
17085
0
    break;
17086
0
  case BuiltinType::Char32:
17087
0
    OS << 'U';
17088
0
    break;
17089
0
  case BuiltinType::WChar_S:
17090
0
  case BuiltinType::WChar_U:
17091
0
    OS << 'L';
17092
0
    break;
17093
0
  default:
17094
0
    llvm_unreachable("Non-character type");
17095
0
  }
17096
0
}
17097
17098
/// Convert character's value, interpreted as a code unit, to a string.
17099
/// The value needs to be zero-extended to 32-bits.
17100
/// FIXME: This assumes Unicode literal encodings
17101
static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17102
                                        unsigned TyWidth,
17103
0
                                        SmallVectorImpl<char> &Str) {
17104
0
  char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17105
0
  char *Ptr = Arr;
17106
0
  BuiltinType::Kind K = BTy->getKind();
17107
0
  llvm::raw_svector_ostream OS(Str);
17108
17109
  // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17110
  // other types.
17111
0
  if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17112
0
      K == BuiltinType::Char8 || Value <= 0x7F) {
17113
0
    StringRef Escaped = escapeCStyle<EscapeChar::Single>(Value);
17114
0
    if (!Escaped.empty())
17115
0
      EscapeStringForDiagnostic(Escaped, Str);
17116
0
    else
17117
0
      OS << static_cast<char>(Value);
17118
0
    return;
17119
0
  }
17120
17121
0
  switch (K) {
17122
0
  case BuiltinType::Char16:
17123
0
  case BuiltinType::Char32:
17124
0
  case BuiltinType::WChar_S:
17125
0
  case BuiltinType::WChar_U: {
17126
0
    if (llvm::ConvertCodePointToUTF8(Value, Ptr))
17127
0
      EscapeStringForDiagnostic(StringRef(Arr, Ptr - Arr), Str);
17128
0
    else
17129
0
      OS << "\\x"
17130
0
         << llvm::format_hex_no_prefix(Value, TyWidth / 4, /*Upper=*/true);
17131
0
    break;
17132
0
  }
17133
0
  default:
17134
0
    llvm_unreachable("Non-character type is passed");
17135
0
  }
17136
0
}
17137
17138
/// Convert \V to a string we can present to the user in a diagnostic
17139
/// \T is the type of the expression that has been evaluated into \V
17140
static bool ConvertAPValueToString(const APValue &V, QualType T,
17141
                                   SmallVectorImpl<char> &Str,
17142
0
                                   ASTContext &Context) {
17143
0
  if (!V.hasValue())
17144
0
    return false;
17145
17146
0
  switch (V.getKind()) {
17147
0
  case APValue::ValueKind::Int:
17148
0
    if (T->isBooleanType()) {
17149
      // Bools are reduced to ints during evaluation, but for
17150
      // diagnostic purposes we want to print them as
17151
      // true or false.
17152
0
      int64_t BoolValue = V.getInt().getExtValue();
17153
0
      assert((BoolValue == 0 || BoolValue == 1) &&
17154
0
             "Bool type, but value is not 0 or 1");
17155
0
      llvm::raw_svector_ostream OS(Str);
17156
0
      OS << (BoolValue ? "true" : "false");
17157
0
    } else {
17158
0
      llvm::raw_svector_ostream OS(Str);
17159
      // Same is true for chars.
17160
      // We want to print the character representation for textual types
17161
0
      const auto *BTy = T->getAs<BuiltinType>();
17162
0
      if (BTy) {
17163
0
        switch (BTy->getKind()) {
17164
0
        case BuiltinType::Char_S:
17165
0
        case BuiltinType::Char_U:
17166
0
        case BuiltinType::Char8:
17167
0
        case BuiltinType::Char16:
17168
0
        case BuiltinType::Char32:
17169
0
        case BuiltinType::WChar_S:
17170
0
        case BuiltinType::WChar_U: {
17171
0
          unsigned TyWidth = Context.getIntWidth(T);
17172
0
          assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17173
0
          uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17174
0
          WriteCharTypePrefix(BTy->getKind(), OS);
17175
0
          OS << '\'';
17176
0
          WriteCharValueForDiagnostic(CodeUnit, BTy, TyWidth, Str);
17177
0
          OS << "' (0x"
17178
0
             << llvm::format_hex_no_prefix(CodeUnit, /*Width=*/2,
17179
0
                                           /*Upper=*/true)
17180
0
             << ", " << V.getInt() << ')';
17181
0
          return true;
17182
0
        }
17183
0
        default:
17184
0
          break;
17185
0
        }
17186
0
      }
17187
0
      V.getInt().toString(Str);
17188
0
    }
17189
17190
0
    break;
17191
17192
0
  case APValue::ValueKind::Float:
17193
0
    V.getFloat().toString(Str);
17194
0
    break;
17195
17196
0
  case APValue::ValueKind::LValue:
17197
0
    if (V.isNullPointer()) {
17198
0
      llvm::raw_svector_ostream OS(Str);
17199
0
      OS << "nullptr";
17200
0
    } else
17201
0
      return false;
17202
0
    break;
17203
17204
0
  case APValue::ValueKind::ComplexFloat: {
17205
0
    llvm::raw_svector_ostream OS(Str);
17206
0
    OS << '(';
17207
0
    V.getComplexFloatReal().toString(Str);
17208
0
    OS << " + ";
17209
0
    V.getComplexFloatImag().toString(Str);
17210
0
    OS << "i)";
17211
0
  } break;
17212
17213
0
  case APValue::ValueKind::ComplexInt: {
17214
0
    llvm::raw_svector_ostream OS(Str);
17215
0
    OS << '(';
17216
0
    V.getComplexIntReal().toString(Str);
17217
0
    OS << " + ";
17218
0
    V.getComplexIntImag().toString(Str);
17219
0
    OS << "i)";
17220
0
  } break;
17221
17222
0
  default:
17223
0
    return false;
17224
0
  }
17225
17226
0
  return true;
17227
0
}
17228
17229
/// Some Expression types are not useful to print notes about,
17230
/// e.g. literals and values that have already been expanded
17231
/// before such as int-valued template parameters.
17232
0
static bool UsefulToPrintExpr(const Expr *E) {
17233
0
  E = E->IgnoreParenImpCasts();
17234
  // Literals are pretty easy for humans to understand.
17235
0
  if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
17236
0
          CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(E))
17237
0
    return false;
17238
17239
  // These have been substituted from template parameters
17240
  // and appear as literals in the static assert error.
17241
0
  if (isa<SubstNonTypeTemplateParmExpr>(E))
17242
0
    return false;
17243
17244
  // -5 is also simple to understand.
17245
0
  if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
17246
0
    return UsefulToPrintExpr(UnaryOp->getSubExpr());
17247
17248
  // Only print nested arithmetic operators.
17249
0
  if (const auto *BO = dyn_cast<BinaryOperator>(E))
17250
0
    return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17251
0
            BO->isBitwiseOp());
17252
17253
0
  return true;
17254
0
}
17255
17256
/// Try to print more useful information about a failed static_assert
17257
/// with expression \E
17258
0
void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
17259
0
  if (const auto *Op = dyn_cast<BinaryOperator>(E);
17260
0
      Op && Op->getOpcode() != BO_LOr) {
17261
0
    const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17262
0
    const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17263
17264
    // Ignore comparisons of boolean expressions with a boolean literal.
17265
0
    if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
17266
0
        (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
17267
0
      return;
17268
17269
    // Don't print obvious expressions.
17270
0
    if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
17271
0
      return;
17272
17273
0
    struct {
17274
0
      const clang::Expr *Cond;
17275
0
      Expr::EvalResult Result;
17276
0
      SmallString<12> ValueString;
17277
0
      bool Print;
17278
0
    } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
17279
0
                     {RHS, Expr::EvalResult(), {}, false}};
17280
0
    for (unsigned I = 0; I < 2; I++) {
17281
0
      const Expr *Side = DiagSide[I].Cond;
17282
17283
0
      Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
17284
17285
0
      DiagSide[I].Print =
17286
0
          ConvertAPValueToString(DiagSide[I].Result.Val, Side->getType(),
17287
0
                                 DiagSide[I].ValueString, Context);
17288
0
    }
17289
0
    if (DiagSide[0].Print && DiagSide[1].Print) {
17290
0
      Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
17291
0
          << DiagSide[0].ValueString << Op->getOpcodeStr()
17292
0
          << DiagSide[1].ValueString << Op->getSourceRange();
17293
0
    }
17294
0
  }
17295
0
}
17296
17297
bool Sema::EvaluateStaticAssertMessageAsString(Expr *Message,
17298
                                               std::string &Result,
17299
                                               ASTContext &Ctx,
17300
0
                                               bool ErrorOnInvalidMessage) {
17301
0
  assert(Message);
17302
0
  assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17303
0
         "can't evaluate a dependant static assert message");
17304
17305
0
  if (const auto *SL = dyn_cast<StringLiteral>(Message)) {
17306
0
    assert(SL->isUnevaluated() && "expected an unevaluated string");
17307
0
    Result.assign(SL->getString().begin(), SL->getString().end());
17308
0
    return true;
17309
0
  }
17310
17311
0
  SourceLocation Loc = Message->getBeginLoc();
17312
0
  QualType T = Message->getType().getNonReferenceType();
17313
0
  auto *RD = T->getAsCXXRecordDecl();
17314
0
  if (!RD) {
17315
0
    Diag(Loc, diag::err_static_assert_invalid_message);
17316
0
    return false;
17317
0
  }
17318
17319
0
  auto FindMember = [&](StringRef Member, bool &Empty,
17320
0
                        bool Diag = false) -> std::optional<LookupResult> {
17321
0
    DeclarationName DN = PP.getIdentifierInfo(Member);
17322
0
    LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
17323
0
    LookupQualifiedName(MemberLookup, RD);
17324
0
    Empty = MemberLookup.empty();
17325
0
    OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17326
0
                                    OverloadCandidateSet::CSK_Normal);
17327
0
    if (MemberLookup.empty())
17328
0
      return std::nullopt;
17329
0
    return std::move(MemberLookup);
17330
0
  };
17331
17332
0
  bool SizeNotFound, DataNotFound;
17333
0
  std::optional<LookupResult> SizeMember = FindMember("size", SizeNotFound);
17334
0
  std::optional<LookupResult> DataMember = FindMember("data", DataNotFound);
17335
0
  if (SizeNotFound || DataNotFound) {
17336
0
    Diag(Loc, diag::err_static_assert_missing_member_function)
17337
0
        << ((SizeNotFound && DataNotFound) ? 2
17338
0
            : SizeNotFound                 ? 0
17339
0
                                           : 1);
17340
0
    return false;
17341
0
  }
17342
17343
0
  if (!SizeMember || !DataMember) {
17344
0
    if (!SizeMember)
17345
0
      FindMember("size", SizeNotFound, /*Diag=*/true);
17346
0
    if (!DataMember)
17347
0
      FindMember("data", DataNotFound, /*Diag=*/true);
17348
0
    return false;
17349
0
  }
17350
17351
0
  auto BuildExpr = [&](LookupResult &LR) {
17352
0
    ExprResult Res = BuildMemberReferenceExpr(
17353
0
        Message, Message->getType(), Message->getBeginLoc(), false,
17354
0
        CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr);
17355
0
    if (Res.isInvalid())
17356
0
      return ExprError();
17357
0
    Res = BuildCallExpr(nullptr, Res.get(), Loc, std::nullopt, Loc, nullptr,
17358
0
                        false, true);
17359
0
    if (Res.isInvalid())
17360
0
      return ExprError();
17361
0
    if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17362
0
      return ExprError();
17363
0
    return TemporaryMaterializationConversion(Res.get());
17364
0
  };
17365
17366
0
  ExprResult SizeE = BuildExpr(*SizeMember);
17367
0
  ExprResult DataE = BuildExpr(*DataMember);
17368
17369
0
  QualType SizeT = Context.getSizeType();
17370
0
  QualType ConstCharPtr =
17371
0
      Context.getPointerType(Context.getConstType(Context.CharTy));
17372
17373
0
  ExprResult EvaluatedSize =
17374
0
      SizeE.isInvalid() ? ExprError()
17375
0
                        : BuildConvertedConstantExpression(
17376
0
                              SizeE.get(), SizeT, CCEK_StaticAssertMessageSize);
17377
0
  if (EvaluatedSize.isInvalid()) {
17378
0
    Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0;
17379
0
    return false;
17380
0
  }
17381
17382
0
  ExprResult EvaluatedData =
17383
0
      DataE.isInvalid()
17384
0
          ? ExprError()
17385
0
          : BuildConvertedConstantExpression(DataE.get(), ConstCharPtr,
17386
0
                                             CCEK_StaticAssertMessageData);
17387
0
  if (EvaluatedData.isInvalid()) {
17388
0
    Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1;
17389
0
    return false;
17390
0
  }
17391
17392
0
  if (!ErrorOnInvalidMessage &&
17393
0
      Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc))
17394
0
    return true;
17395
17396
0
  Expr::EvalResult Status;
17397
0
  SmallVector<PartialDiagnosticAt, 8> Notes;
17398
0
  Status.Diag = &Notes;
17399
0
  if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17400
0
                                          EvaluatedData.get(), Ctx, Status) ||
17401
0
      !Notes.empty()) {
17402
0
    Diag(Message->getBeginLoc(),
17403
0
         ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr
17404
0
                               : diag::warn_static_assert_message_constexpr);
17405
0
    for (const auto &Note : Notes)
17406
0
      Diag(Note.first, Note.second);
17407
0
    return !ErrorOnInvalidMessage;
17408
0
  }
17409
0
  return true;
17410
0
}
17411
17412
Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17413
                                         Expr *AssertExpr, Expr *AssertMessage,
17414
                                         SourceLocation RParenLoc,
17415
0
                                         bool Failed) {
17416
0
  assert(AssertExpr != nullptr && "Expected non-null condition");
17417
0
  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17418
0
      (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17419
0
                          !AssertMessage->isValueDependent())) &&
17420
0
      !Failed) {
17421
    // In a static_assert-declaration, the constant-expression shall be a
17422
    // constant expression that can be contextually converted to bool.
17423
0
    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
17424
0
    if (Converted.isInvalid())
17425
0
      Failed = true;
17426
17427
0
    ExprResult FullAssertExpr =
17428
0
        ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
17429
0
                            /*DiscardedValue*/ false,
17430
0
                            /*IsConstexpr*/ true);
17431
0
    if (FullAssertExpr.isInvalid())
17432
0
      Failed = true;
17433
0
    else
17434
0
      AssertExpr = FullAssertExpr.get();
17435
17436
0
    llvm::APSInt Cond;
17437
0
    Expr *BaseExpr = AssertExpr;
17438
0
    AllowFoldKind FoldKind = NoFold;
17439
17440
0
    if (!getLangOpts().CPlusPlus) {
17441
      // In C mode, allow folding as an extension for better compatibility with
17442
      // C++ in terms of expressions like static_assert("test") or
17443
      // static_assert(nullptr).
17444
0
      FoldKind = AllowFold;
17445
0
    }
17446
17447
0
    if (!Failed && VerifyIntegerConstantExpression(
17448
0
                       BaseExpr, &Cond,
17449
0
                       diag::err_static_assert_expression_is_not_constant,
17450
0
                       FoldKind).isInvalid())
17451
0
      Failed = true;
17452
17453
    // If the static_assert passes, only verify that
17454
    // the message is grammatically valid without evaluating it.
17455
0
    if (!Failed && AssertMessage && Cond.getBoolValue()) {
17456
0
      std::string Str;
17457
0
      EvaluateStaticAssertMessageAsString(AssertMessage, Str, Context,
17458
0
                                          /*ErrorOnInvalidMessage=*/false);
17459
0
    }
17460
17461
    // CWG2518
17462
    // [dcl.pre]/p10  If [...] the expression is evaluated in the context of a
17463
    // template definition, the declaration has no effect.
17464
0
    bool InTemplateDefinition =
17465
0
        getLangOpts().CPlusPlus && CurContext->isDependentContext();
17466
17467
0
    if (!Failed && !Cond && !InTemplateDefinition) {
17468
0
      SmallString<256> MsgBuffer;
17469
0
      llvm::raw_svector_ostream Msg(MsgBuffer);
17470
0
      bool HasMessage = AssertMessage;
17471
0
      if (AssertMessage) {
17472
0
        std::string Str;
17473
0
        HasMessage =
17474
0
            EvaluateStaticAssertMessageAsString(
17475
0
                AssertMessage, Str, Context, /*ErrorOnInvalidMessage=*/true) ||
17476
0
            !Str.empty();
17477
0
        Msg << Str;
17478
0
      }
17479
0
      Expr *InnerCond = nullptr;
17480
0
      std::string InnerCondDescription;
17481
0
      std::tie(InnerCond, InnerCondDescription) =
17482
0
        findFailedBooleanCondition(Converted.get());
17483
0
      if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
17484
        // Drill down into concept specialization expressions to see why they
17485
        // weren't satisfied.
17486
0
        Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17487
0
            << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17488
0
        ConstraintSatisfaction Satisfaction;
17489
0
        if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
17490
0
          DiagnoseUnsatisfiedConstraint(Satisfaction);
17491
0
      } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
17492
0
                           && !isa<IntegerLiteral>(InnerCond)) {
17493
0
        Diag(InnerCond->getBeginLoc(),
17494
0
             diag::err_static_assert_requirement_failed)
17495
0
            << InnerCondDescription << !HasMessage << Msg.str()
17496
0
            << InnerCond->getSourceRange();
17497
0
        DiagnoseStaticAssertDetails(InnerCond);
17498
0
      } else {
17499
0
        Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed)
17500
0
            << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
17501
0
        PrintContextStack();
17502
0
      }
17503
0
      Failed = true;
17504
0
    }
17505
0
  } else {
17506
0
    ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
17507
0
                                                    /*DiscardedValue*/false,
17508
0
                                                    /*IsConstexpr*/true);
17509
0
    if (FullAssertExpr.isInvalid())
17510
0
      Failed = true;
17511
0
    else
17512
0
      AssertExpr = FullAssertExpr.get();
17513
0
  }
17514
17515
0
  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
17516
0
                                        AssertExpr, AssertMessage, RParenLoc,
17517
0
                                        Failed);
17518
17519
0
  CurContext->addDecl(Decl);
17520
0
  return Decl;
17521
0
}
17522
17523
/// Perform semantic analysis of the given friend type declaration.
17524
///
17525
/// \returns A friend declaration that.
17526
FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
17527
                                      SourceLocation FriendLoc,
17528
0
                                      TypeSourceInfo *TSInfo) {
17529
0
  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
17530
17531
0
  QualType T = TSInfo->getType();
17532
0
  SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
17533
17534
  // C++03 [class.friend]p2:
17535
  //   An elaborated-type-specifier shall be used in a friend declaration
17536
  //   for a class.*
17537
  //
17538
  //   * The class-key of the elaborated-type-specifier is required.
17539
0
  if (!CodeSynthesisContexts.empty()) {
17540
    // Do not complain about the form of friend template types during any kind
17541
    // of code synthesis. For template instantiation, we will have complained
17542
    // when the template was defined.
17543
0
  } else {
17544
0
    if (!T->isElaboratedTypeSpecifier()) {
17545
      // If we evaluated the type to a record type, suggest putting
17546
      // a tag in front.
17547
0
      if (const RecordType *RT = T->getAs<RecordType>()) {
17548
0
        RecordDecl *RD = RT->getDecl();
17549
17550
0
        SmallString<16> InsertionText(" ");
17551
0
        InsertionText += RD->getKindName();
17552
17553
0
        Diag(TypeRange.getBegin(),
17554
0
             getLangOpts().CPlusPlus11 ?
17555
0
               diag::warn_cxx98_compat_unelaborated_friend_type :
17556
0
               diag::ext_unelaborated_friend_type)
17557
0
          << (unsigned) RD->getTagKind()
17558
0
          << T
17559
0
          << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
17560
0
                                        InsertionText);
17561
0
      } else {
17562
0
        Diag(FriendLoc,
17563
0
             getLangOpts().CPlusPlus11 ?
17564
0
               diag::warn_cxx98_compat_nonclass_type_friend :
17565
0
               diag::ext_nonclass_type_friend)
17566
0
          << T
17567
0
          << TypeRange;
17568
0
      }
17569
0
    } else if (T->getAs<EnumType>()) {
17570
0
      Diag(FriendLoc,
17571
0
           getLangOpts().CPlusPlus11 ?
17572
0
             diag::warn_cxx98_compat_enum_friend :
17573
0
             diag::ext_enum_friend)
17574
0
        << T
17575
0
        << TypeRange;
17576
0
    }
17577
17578
    // C++11 [class.friend]p3:
17579
    //   A friend declaration that does not declare a function shall have one
17580
    //   of the following forms:
17581
    //     friend elaborated-type-specifier ;
17582
    //     friend simple-type-specifier ;
17583
    //     friend typename-specifier ;
17584
0
    if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
17585
0
      Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
17586
0
  }
17587
17588
  //   If the type specifier in a friend declaration designates a (possibly
17589
  //   cv-qualified) class type, that class is declared as a friend; otherwise,
17590
  //   the friend declaration is ignored.
17591
0
  return FriendDecl::Create(Context, CurContext,
17592
0
                            TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
17593
0
                            FriendLoc);
17594
0
}
17595
17596
/// Handle a friend tag declaration where the scope specifier was
17597
/// templated.
17598
DeclResult Sema::ActOnTemplatedFriendTag(
17599
    Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
17600
    CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
17601
0
    const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists) {
17602
0
  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
17603
17604
0
  bool IsMemberSpecialization = false;
17605
0
  bool Invalid = false;
17606
17607
0
  if (TemplateParameterList *TemplateParams =
17608
0
          MatchTemplateParametersToScopeSpecifier(
17609
0
              TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
17610
0
              IsMemberSpecialization, Invalid)) {
17611
0
    if (TemplateParams->size() > 0) {
17612
      // This is a declaration of a class template.
17613
0
      if (Invalid)
17614
0
        return true;
17615
17616
0
      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
17617
0
                                NameLoc, Attr, TemplateParams, AS_public,
17618
0
                                /*ModulePrivateLoc=*/SourceLocation(),
17619
0
                                FriendLoc, TempParamLists.size() - 1,
17620
0
                                TempParamLists.data()).get();
17621
0
    } else {
17622
      // The "template<>" header is extraneous.
17623
0
      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
17624
0
        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
17625
0
      IsMemberSpecialization = true;
17626
0
    }
17627
0
  }
17628
17629
0
  if (Invalid) return true;
17630
17631
0
  bool isAllExplicitSpecializations = true;
17632
0
  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
17633
0
    if (TempParamLists[I]->size()) {
17634
0
      isAllExplicitSpecializations = false;
17635
0
      break;
17636
0
    }
17637
0
  }
17638
17639
  // FIXME: don't ignore attributes.
17640
17641
  // If it's explicit specializations all the way down, just forget
17642
  // about the template header and build an appropriate non-templated
17643
  // friend.  TODO: for source fidelity, remember the headers.
17644
0
  if (isAllExplicitSpecializations) {
17645
0
    if (SS.isEmpty()) {
17646
0
      bool Owned = false;
17647
0
      bool IsDependent = false;
17648
0
      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, Attr,
17649
0
                      AS_public,
17650
0
                      /*ModulePrivateLoc=*/SourceLocation(),
17651
0
                      MultiTemplateParamsArg(), Owned, IsDependent,
17652
0
                      /*ScopedEnumKWLoc=*/SourceLocation(),
17653
0
                      /*ScopedEnumUsesClassTag=*/false,
17654
0
                      /*UnderlyingType=*/TypeResult(),
17655
0
                      /*IsTypeSpecifier=*/false,
17656
0
                      /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside);
17657
0
    }
17658
17659
0
    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
17660
0
    ElaboratedTypeKeyword Keyword
17661
0
      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
17662
0
    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
17663
0
                                   *Name, NameLoc);
17664
0
    if (T.isNull())
17665
0
      return true;
17666
17667
0
    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17668
0
    if (isa<DependentNameType>(T)) {
17669
0
      DependentNameTypeLoc TL =
17670
0
          TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17671
0
      TL.setElaboratedKeywordLoc(TagLoc);
17672
0
      TL.setQualifierLoc(QualifierLoc);
17673
0
      TL.setNameLoc(NameLoc);
17674
0
    } else {
17675
0
      ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
17676
0
      TL.setElaboratedKeywordLoc(TagLoc);
17677
0
      TL.setQualifierLoc(QualifierLoc);
17678
0
      TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
17679
0
    }
17680
17681
0
    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17682
0
                                            TSI, FriendLoc, TempParamLists);
17683
0
    Friend->setAccess(AS_public);
17684
0
    CurContext->addDecl(Friend);
17685
0
    return Friend;
17686
0
  }
17687
17688
0
  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
17689
17690
17691
17692
  // Handle the case of a templated-scope friend class.  e.g.
17693
  //   template <class T> class A<T>::B;
17694
  // FIXME: we don't support these right now.
17695
0
  Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17696
0
    << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17697
0
  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
17698
0
  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
17699
0
  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17700
0
  DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17701
0
  TL.setElaboratedKeywordLoc(TagLoc);
17702
0
  TL.setQualifierLoc(SS.getWithLocInContext(Context));
17703
0
  TL.setNameLoc(NameLoc);
17704
17705
0
  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17706
0
                                          TSI, FriendLoc, TempParamLists);
17707
0
  Friend->setAccess(AS_public);
17708
0
  Friend->setUnsupportedFriend(true);
17709
0
  CurContext->addDecl(Friend);
17710
0
  return Friend;
17711
0
}
17712
17713
/// Handle a friend type declaration.  This works in tandem with
17714
/// ActOnTag.
17715
///
17716
/// Notes on friend class templates:
17717
///
17718
/// We generally treat friend class declarations as if they were
17719
/// declaring a class.  So, for example, the elaborated type specifier
17720
/// in a friend declaration is required to obey the restrictions of a
17721
/// class-head (i.e. no typedefs in the scope chain), template
17722
/// parameters are required to match up with simple template-ids, &c.
17723
/// However, unlike when declaring a template specialization, it's
17724
/// okay to refer to a template specialization without an empty
17725
/// template parameter declaration, e.g.
17726
///   friend class A<T>::B<unsigned>;
17727
/// We permit this as a special case; if there are any template
17728
/// parameters present at all, require proper matching, i.e.
17729
///   template <> template \<class T> friend class A<int>::B;
17730
Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
17731
0
                                MultiTemplateParamsArg TempParams) {
17732
0
  SourceLocation Loc = DS.getBeginLoc();
17733
17734
0
  assert(DS.isFriendSpecified());
17735
0
  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
17736
17737
  // C++ [class.friend]p3:
17738
  // A friend declaration that does not declare a function shall have one of
17739
  // the following forms:
17740
  //     friend elaborated-type-specifier ;
17741
  //     friend simple-type-specifier ;
17742
  //     friend typename-specifier ;
17743
  //
17744
  // Any declaration with a type qualifier does not have that form. (It's
17745
  // legal to specify a qualified type as a friend, you just can't write the
17746
  // keywords.)
17747
0
  if (DS.getTypeQualifiers()) {
17748
0
    if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
17749
0
      Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17750
0
    if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
17751
0
      Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17752
0
    if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
17753
0
      Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17754
0
    if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
17755
0
      Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17756
0
    if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
17757
0
      Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17758
0
  }
17759
17760
  // Try to convert the decl specifier to a type.  This works for
17761
  // friend templates because ActOnTag never produces a ClassTemplateDecl
17762
  // for a TUK_Friend.
17763
0
  Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17764
0
                           DeclaratorContext::Member);
17765
0
  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
17766
0
  QualType T = TSI->getType();
17767
0
  if (TheDeclarator.isInvalidType())
17768
0
    return nullptr;
17769
17770
0
  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
17771
0
    return nullptr;
17772
17773
  // This is definitely an error in C++98.  It's probably meant to
17774
  // be forbidden in C++0x, too, but the specification is just
17775
  // poorly written.
17776
  //
17777
  // The problem is with declarations like the following:
17778
  //   template <T> friend A<T>::foo;
17779
  // where deciding whether a class C is a friend or not now hinges
17780
  // on whether there exists an instantiation of A that causes
17781
  // 'foo' to equal C.  There are restrictions on class-heads
17782
  // (which we declare (by fiat) elaborated friend declarations to
17783
  // be) that makes this tractable.
17784
  //
17785
  // FIXME: handle "template <> friend class A<T>;", which
17786
  // is possibly well-formed?  Who even knows?
17787
0
  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
17788
0
    Diag(Loc, diag::err_tagless_friend_type_template)
17789
0
      << DS.getSourceRange();
17790
0
    return nullptr;
17791
0
  }
17792
17793
  // C++98 [class.friend]p1: A friend of a class is a function
17794
  //   or class that is not a member of the class . . .
17795
  // This is fixed in DR77, which just barely didn't make the C++03
17796
  // deadline.  It's also a very silly restriction that seriously
17797
  // affects inner classes and which nobody else seems to implement;
17798
  // thus we never diagnose it, not even in -pedantic.
17799
  //
17800
  // But note that we could warn about it: it's always useless to
17801
  // friend one of your own members (it's not, however, worthless to
17802
  // friend a member of an arbitrary specialization of your template).
17803
17804
0
  Decl *D;
17805
0
  if (!TempParams.empty())
17806
0
    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
17807
0
                                   TempParams,
17808
0
                                   TSI,
17809
0
                                   DS.getFriendSpecLoc());
17810
0
  else
17811
0
    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
17812
17813
0
  if (!D)
17814
0
    return nullptr;
17815
17816
0
  D->setAccess(AS_public);
17817
0
  CurContext->addDecl(D);
17818
17819
0
  return D;
17820
0
}
17821
17822
NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
17823
0
                                        MultiTemplateParamsArg TemplateParams) {
17824
0
  const DeclSpec &DS = D.getDeclSpec();
17825
17826
0
  assert(DS.isFriendSpecified());
17827
0
  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
17828
17829
0
  SourceLocation Loc = D.getIdentifierLoc();
17830
0
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17831
17832
  // C++ [class.friend]p1
17833
  //   A friend of a class is a function or class....
17834
  // Note that this sees through typedefs, which is intended.
17835
  // It *doesn't* see through dependent types, which is correct
17836
  // according to [temp.arg.type]p3:
17837
  //   If a declaration acquires a function type through a
17838
  //   type dependent on a template-parameter and this causes
17839
  //   a declaration that does not use the syntactic form of a
17840
  //   function declarator to have a function type, the program
17841
  //   is ill-formed.
17842
0
  if (!TInfo->getType()->isFunctionType()) {
17843
0
    Diag(Loc, diag::err_unexpected_friend);
17844
17845
    // It might be worthwhile to try to recover by creating an
17846
    // appropriate declaration.
17847
0
    return nullptr;
17848
0
  }
17849
17850
  // C++ [namespace.memdef]p3
17851
  //  - If a friend declaration in a non-local class first declares a
17852
  //    class or function, the friend class or function is a member
17853
  //    of the innermost enclosing namespace.
17854
  //  - The name of the friend is not found by simple name lookup
17855
  //    until a matching declaration is provided in that namespace
17856
  //    scope (either before or after the class declaration granting
17857
  //    friendship).
17858
  //  - If a friend function is called, its name may be found by the
17859
  //    name lookup that considers functions from namespaces and
17860
  //    classes associated with the types of the function arguments.
17861
  //  - When looking for a prior declaration of a class or a function
17862
  //    declared as a friend, scopes outside the innermost enclosing
17863
  //    namespace scope are not considered.
17864
17865
0
  CXXScopeSpec &SS = D.getCXXScopeSpec();
17866
0
  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
17867
0
  assert(NameInfo.getName());
17868
17869
  // Check for unexpanded parameter packs.
17870
0
  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
17871
0
      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
17872
0
      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
17873
0
    return nullptr;
17874
17875
  // The context we found the declaration in, or in which we should
17876
  // create the declaration.
17877
0
  DeclContext *DC;
17878
0
  Scope *DCScope = S;
17879
0
  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17880
0
                        ForExternalRedeclaration);
17881
17882
0
  bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17883
17884
  // There are five cases here.
17885
  //   - There's no scope specifier and we're in a local class. Only look
17886
  //     for functions declared in the immediately-enclosing block scope.
17887
  // We recover from invalid scope qualifiers as if they just weren't there.
17888
0
  FunctionDecl *FunctionContainingLocalClass = nullptr;
17889
0
  if ((SS.isInvalid() || !SS.isSet()) &&
17890
0
      (FunctionContainingLocalClass =
17891
0
           cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17892
    // C++11 [class.friend]p11:
17893
    //   If a friend declaration appears in a local class and the name
17894
    //   specified is an unqualified name, a prior declaration is
17895
    //   looked up without considering scopes that are outside the
17896
    //   innermost enclosing non-class scope. For a friend function
17897
    //   declaration, if there is no prior declaration, the program is
17898
    //   ill-formed.
17899
17900
    // Find the innermost enclosing non-class scope. This is the block
17901
    // scope containing the local class definition (or for a nested class,
17902
    // the outer local class).
17903
0
    DCScope = S->getFnParent();
17904
17905
    // Look up the function name in the scope.
17906
0
    Previous.clear(LookupLocalFriendName);
17907
0
    LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17908
17909
0
    if (!Previous.empty()) {
17910
      // All possible previous declarations must have the same context:
17911
      // either they were declared at block scope or they are members of
17912
      // one of the enclosing local classes.
17913
0
      DC = Previous.getRepresentativeDecl()->getDeclContext();
17914
0
    } else {
17915
      // This is ill-formed, but provide the context that we would have
17916
      // declared the function in, if we were permitted to, for error recovery.
17917
0
      DC = FunctionContainingLocalClass;
17918
0
    }
17919
0
    adjustContextForLocalExternDecl(DC);
17920
17921
  //   - There's no scope specifier, in which case we just go to the
17922
  //     appropriate scope and look for a function or function template
17923
  //     there as appropriate.
17924
0
  } else if (SS.isInvalid() || !SS.isSet()) {
17925
    // C++11 [namespace.memdef]p3:
17926
    //   If the name in a friend declaration is neither qualified nor
17927
    //   a template-id and the declaration is a function or an
17928
    //   elaborated-type-specifier, the lookup to determine whether
17929
    //   the entity has been previously declared shall not consider
17930
    //   any scopes outside the innermost enclosing namespace.
17931
17932
    // Find the appropriate context according to the above.
17933
0
    DC = CurContext;
17934
17935
    // Skip class contexts.  If someone can cite chapter and verse
17936
    // for this behavior, that would be nice --- it's what GCC and
17937
    // EDG do, and it seems like a reasonable intent, but the spec
17938
    // really only says that checks for unqualified existing
17939
    // declarations should stop at the nearest enclosing namespace,
17940
    // not that they should only consider the nearest enclosing
17941
    // namespace.
17942
0
    while (DC->isRecord())
17943
0
      DC = DC->getParent();
17944
17945
0
    DeclContext *LookupDC = DC->getNonTransparentContext();
17946
0
    while (true) {
17947
0
      LookupQualifiedName(Previous, LookupDC);
17948
17949
0
      if (!Previous.empty()) {
17950
0
        DC = LookupDC;
17951
0
        break;
17952
0
      }
17953
17954
0
      if (isTemplateId) {
17955
0
        if (isa<TranslationUnitDecl>(LookupDC)) break;
17956
0
      } else {
17957
0
        if (LookupDC->isFileContext()) break;
17958
0
      }
17959
0
      LookupDC = LookupDC->getParent();
17960
0
    }
17961
17962
0
    DCScope = getScopeForDeclContext(S, DC);
17963
17964
  //   - There's a non-dependent scope specifier, in which case we
17965
  //     compute it and do a previous lookup there for a function
17966
  //     or function template.
17967
0
  } else if (!SS.getScopeRep()->isDependent()) {
17968
0
    DC = computeDeclContext(SS);
17969
0
    if (!DC) return nullptr;
17970
17971
0
    if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17972
17973
0
    LookupQualifiedName(Previous, DC);
17974
17975
    // C++ [class.friend]p1: A friend of a class is a function or
17976
    //   class that is not a member of the class . . .
17977
0
    if (DC->Equals(CurContext))
17978
0
      Diag(DS.getFriendSpecLoc(),
17979
0
           getLangOpts().CPlusPlus11 ?
17980
0
             diag::warn_cxx98_compat_friend_is_member :
17981
0
             diag::err_friend_is_member);
17982
17983
  //   - There's a scope specifier that does not match any template
17984
  //     parameter lists, in which case we use some arbitrary context,
17985
  //     create a method or method template, and wait for instantiation.
17986
  //   - There's a scope specifier that does match some template
17987
  //     parameter lists, which we don't handle right now.
17988
0
  } else {
17989
0
    DC = CurContext;
17990
0
    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17991
0
  }
17992
17993
0
  if (!DC->isRecord()) {
17994
0
    int DiagArg = -1;
17995
0
    switch (D.getName().getKind()) {
17996
0
    case UnqualifiedIdKind::IK_ConstructorTemplateId:
17997
0
    case UnqualifiedIdKind::IK_ConstructorName:
17998
0
      DiagArg = 0;
17999
0
      break;
18000
0
    case UnqualifiedIdKind::IK_DestructorName:
18001
0
      DiagArg = 1;
18002
0
      break;
18003
0
    case UnqualifiedIdKind::IK_ConversionFunctionId:
18004
0
      DiagArg = 2;
18005
0
      break;
18006
0
    case UnqualifiedIdKind::IK_DeductionGuideName:
18007
0
      DiagArg = 3;
18008
0
      break;
18009
0
    case UnqualifiedIdKind::IK_Identifier:
18010
0
    case UnqualifiedIdKind::IK_ImplicitSelfParam:
18011
0
    case UnqualifiedIdKind::IK_LiteralOperatorId:
18012
0
    case UnqualifiedIdKind::IK_OperatorFunctionId:
18013
0
    case UnqualifiedIdKind::IK_TemplateId:
18014
0
      break;
18015
0
    }
18016
    // This implies that it has to be an operator or function.
18017
0
    if (DiagArg >= 0) {
18018
0
      Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
18019
0
      return nullptr;
18020
0
    }
18021
0
  }
18022
18023
  // FIXME: This is an egregious hack to cope with cases where the scope stack
18024
  // does not contain the declaration context, i.e., in an out-of-line
18025
  // definition of a class.
18026
0
  Scope FakeDCScope(S, Scope::DeclScope, Diags);
18027
0
  if (!DCScope) {
18028
0
    FakeDCScope.setEntity(DC);
18029
0
    DCScope = &FakeDCScope;
18030
0
  }
18031
18032
0
  bool AddToScope = true;
18033
0
  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
18034
0
                                          TemplateParams, AddToScope);
18035
0
  if (!ND) return nullptr;
18036
18037
0
  assert(ND->getLexicalDeclContext() == CurContext);
18038
18039
  // If we performed typo correction, we might have added a scope specifier
18040
  // and changed the decl context.
18041
0
  DC = ND->getDeclContext();
18042
18043
  // Add the function declaration to the appropriate lookup tables,
18044
  // adjusting the redeclarations list as necessary.  We don't
18045
  // want to do this yet if the friending class is dependent.
18046
  //
18047
  // Also update the scope-based lookup if the target context's
18048
  // lookup context is in lexical scope.
18049
0
  if (!CurContext->isDependentContext()) {
18050
0
    DC = DC->getRedeclContext();
18051
0
    DC->makeDeclVisibleInContext(ND);
18052
0
    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18053
0
      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
18054
0
  }
18055
18056
0
  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
18057
0
                                       D.getIdentifierLoc(), ND,
18058
0
                                       DS.getFriendSpecLoc());
18059
0
  FrD->setAccess(AS_public);
18060
0
  CurContext->addDecl(FrD);
18061
18062
0
  if (ND->isInvalidDecl()) {
18063
0
    FrD->setInvalidDecl();
18064
0
  } else {
18065
0
    if (DC->isRecord()) CheckFriendAccess(ND);
18066
18067
0
    FunctionDecl *FD;
18068
0
    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
18069
0
      FD = FTD->getTemplatedDecl();
18070
0
    else
18071
0
      FD = cast<FunctionDecl>(ND);
18072
18073
    // C++ [class.friend]p6:
18074
    //   A function may be defined in a friend declaration of a class if and
18075
    //   only if the class is a non-local class, and the function name is
18076
    //   unqualified.
18077
0
    if (D.isFunctionDefinition()) {
18078
      // Qualified friend function definition.
18079
0
      if (SS.isNotEmpty()) {
18080
        // FIXME: We should only do this if the scope specifier names the
18081
        // innermost enclosing namespace; otherwise the fixit changes the
18082
        // meaning of the code.
18083
0
        SemaDiagnosticBuilder DB =
18084
0
            Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
18085
18086
0
        DB << SS.getScopeRep();
18087
0
        if (DC->isFileContext())
18088
0
          DB << FixItHint::CreateRemoval(SS.getRange());
18089
18090
        // Friend function defined in a local class.
18091
0
      } else if (FunctionContainingLocalClass) {
18092
0
        Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
18093
18094
        // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18095
        // a template-id, the function name is not unqualified because these is
18096
        // no name. While the wording requires some reading in-between the
18097
        // lines, GCC, MSVC, and EDG all consider a friend function
18098
        // specialization definitions // to be de facto explicit specialization
18099
        // and diagnose them as such.
18100
0
      } else if (isTemplateId) {
18101
0
        Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def);
18102
0
      }
18103
0
    }
18104
18105
    // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18106
    // default argument expression, that declaration shall be a definition
18107
    // and shall be the only declaration of the function or function
18108
    // template in the translation unit.
18109
0
    if (functionDeclHasDefaultArgument(FD)) {
18110
      // We can't look at FD->getPreviousDecl() because it may not have been set
18111
      // if we're in a dependent context. If the function is known to be a
18112
      // redeclaration, we will have narrowed Previous down to the right decl.
18113
0
      if (D.isRedeclaration()) {
18114
0
        Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
18115
0
        Diag(Previous.getRepresentativeDecl()->getLocation(),
18116
0
             diag::note_previous_declaration);
18117
0
      } else if (!D.isFunctionDefinition())
18118
0
        Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
18119
0
    }
18120
18121
    // Mark templated-scope function declarations as unsupported.
18122
0
    if (FD->getNumTemplateParameterLists() && SS.isValid()) {
18123
0
      Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
18124
0
        << SS.getScopeRep() << SS.getRange()
18125
0
        << cast<CXXRecordDecl>(CurContext);
18126
0
      FrD->setUnsupportedFriend(true);
18127
0
    }
18128
0
  }
18129
18130
0
  warnOnReservedIdentifier(ND);
18131
18132
0
  return ND;
18133
0
}
18134
18135
0
void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
18136
0
  AdjustDeclIfTemplate(Dcl);
18137
18138
0
  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
18139
0
  if (!Fn) {
18140
0
    Diag(DelLoc, diag::err_deleted_non_function);
18141
0
    return;
18142
0
  }
18143
18144
  // Deleted function does not have a body.
18145
0
  Fn->setWillHaveBody(false);
18146
18147
0
  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18148
    // Don't consider the implicit declaration we generate for explicit
18149
    // specializations. FIXME: Do not generate these implicit declarations.
18150
0
    if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18151
0
         Prev->getPreviousDecl()) &&
18152
0
        !Prev->isDefined()) {
18153
0
      Diag(DelLoc, diag::err_deleted_decl_not_first);
18154
0
      Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18155
0
           Prev->isImplicit() ? diag::note_previous_implicit_declaration
18156
0
                              : diag::note_previous_declaration);
18157
      // We can't recover from this; the declaration might have already
18158
      // been used.
18159
0
      Fn->setInvalidDecl();
18160
0
      return;
18161
0
    }
18162
18163
    // To maintain the invariant that functions are only deleted on their first
18164
    // declaration, mark the implicitly-instantiated declaration of the
18165
    // explicitly-specialized function as deleted instead of marking the
18166
    // instantiated redeclaration.
18167
0
    Fn = Fn->getCanonicalDecl();
18168
0
  }
18169
18170
  // dllimport/dllexport cannot be deleted.
18171
0
  if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
18172
0
    Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
18173
0
    Fn->setInvalidDecl();
18174
0
  }
18175
18176
  // C++11 [basic.start.main]p3:
18177
  //   A program that defines main as deleted [...] is ill-formed.
18178
0
  if (Fn->isMain())
18179
0
    Diag(DelLoc, diag::err_deleted_main);
18180
18181
  // C++11 [dcl.fct.def.delete]p4:
18182
  //  A deleted function is implicitly inline.
18183
0
  Fn->setImplicitlyInline();
18184
0
  Fn->setDeletedAsWritten();
18185
0
}
18186
18187
0
void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
18188
0
  if (!Dcl || Dcl->isInvalidDecl())
18189
0
    return;
18190
18191
0
  auto *FD = dyn_cast<FunctionDecl>(Dcl);
18192
0
  if (!FD) {
18193
0
    if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
18194
0
      if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
18195
0
        Diag(DefaultLoc, diag::err_defaulted_comparison_template);
18196
0
        return;
18197
0
      }
18198
0
    }
18199
18200
0
    Diag(DefaultLoc, diag::err_default_special_members)
18201
0
        << getLangOpts().CPlusPlus20;
18202
0
    return;
18203
0
  }
18204
18205
  // Reject if this can't possibly be a defaultable function.
18206
0
  DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
18207
0
  if (!DefKind &&
18208
      // A dependent function that doesn't locally look defaultable can
18209
      // still instantiate to a defaultable function if it's a constructor
18210
      // or assignment operator.
18211
0
      (!FD->isDependentContext() ||
18212
0
       (!isa<CXXConstructorDecl>(FD) &&
18213
0
        FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18214
0
    Diag(DefaultLoc, diag::err_default_special_members)
18215
0
        << getLangOpts().CPlusPlus20;
18216
0
    return;
18217
0
  }
18218
18219
  // Issue compatibility warning. We already warned if the operator is
18220
  // 'operator<=>' when parsing the '<=>' token.
18221
0
  if (DefKind.isComparison() &&
18222
0
      DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
18223
0
    Diag(DefaultLoc, getLangOpts().CPlusPlus20
18224
0
                         ? diag::warn_cxx17_compat_defaulted_comparison
18225
0
                         : diag::ext_defaulted_comparison);
18226
0
  }
18227
18228
0
  FD->setDefaulted();
18229
0
  FD->setExplicitlyDefaulted();
18230
0
  FD->setDefaultLoc(DefaultLoc);
18231
18232
  // Defer checking functions that are defaulted in a dependent context.
18233
0
  if (FD->isDependentContext())
18234
0
    return;
18235
18236
  // Unset that we will have a body for this function. We might not,
18237
  // if it turns out to be trivial, and we don't need this marking now
18238
  // that we've marked it as defaulted.
18239
0
  FD->setWillHaveBody(false);
18240
18241
0
  if (DefKind.isComparison()) {
18242
    // If this comparison's defaulting occurs within the definition of its
18243
    // lexical class context, we have to do the checking when complete.
18244
0
    if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
18245
0
      if (!RD->isCompleteDefinition())
18246
0
        return;
18247
0
  }
18248
18249
  // If this member fn was defaulted on its first declaration, we will have
18250
  // already performed the checking in CheckCompletedCXXClass. Such a
18251
  // declaration doesn't trigger an implicit definition.
18252
0
  if (isa<CXXMethodDecl>(FD)) {
18253
0
    const FunctionDecl *Primary = FD;
18254
0
    if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18255
      // Ask the template instantiation pattern that actually had the
18256
      // '= default' on it.
18257
0
      Primary = Pattern;
18258
0
    if (Primary->getCanonicalDecl()->isDefaulted())
18259
0
      return;
18260
0
  }
18261
18262
0
  if (DefKind.isComparison()) {
18263
0
    if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
18264
0
      FD->setInvalidDecl();
18265
0
    else
18266
0
      DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
18267
0
  } else {
18268
0
    auto *MD = cast<CXXMethodDecl>(FD);
18269
18270
0
    if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember(),
18271
0
                                              DefaultLoc))
18272
0
      MD->setInvalidDecl();
18273
0
    else
18274
0
      DefineDefaultedFunction(*this, MD, DefaultLoc);
18275
0
  }
18276
0
}
18277
18278
0
static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
18279
0
  for (Stmt *SubStmt : S->children()) {
18280
0
    if (!SubStmt)
18281
0
      continue;
18282
0
    if (isa<ReturnStmt>(SubStmt))
18283
0
      Self.Diag(SubStmt->getBeginLoc(),
18284
0
                diag::err_return_in_constructor_handler);
18285
0
    if (!isa<Expr>(SubStmt))
18286
0
      SearchForReturnInStmt(Self, SubStmt);
18287
0
  }
18288
0
}
18289
18290
0
void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
18291
0
  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18292
0
    CXXCatchStmt *Handler = TryBlock->getHandler(I);
18293
0
    SearchForReturnInStmt(*this, Handler);
18294
0
  }
18295
0
}
18296
18297
void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
18298
0
                               FnBodyKind BodyKind) {
18299
0
  switch (BodyKind) {
18300
0
  case FnBodyKind::Delete:
18301
0
    SetDeclDeleted(D, Loc);
18302
0
    break;
18303
0
  case FnBodyKind::Default:
18304
0
    SetDeclDefaulted(D, Loc);
18305
0
    break;
18306
0
  case FnBodyKind::Other:
18307
0
    llvm_unreachable(
18308
0
        "Parsed function body should be '= delete;' or '= default;'");
18309
0
  }
18310
0
}
18311
18312
bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
18313
0
                                             const CXXMethodDecl *Old) {
18314
0
  const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18315
0
  const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18316
18317
0
  if (OldFT->hasExtParameterInfos()) {
18318
0
    for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18319
      // A parameter of the overriding method should be annotated with noescape
18320
      // if the corresponding parameter of the overridden method is annotated.
18321
0
      if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18322
0
          !NewFT->getExtParameterInfo(I).isNoEscape()) {
18323
0
        Diag(New->getParamDecl(I)->getLocation(),
18324
0
             diag::warn_overriding_method_missing_noescape);
18325
0
        Diag(Old->getParamDecl(I)->getLocation(),
18326
0
             diag::note_overridden_marked_noescape);
18327
0
      }
18328
0
  }
18329
18330
  // SME attributes must match when overriding a function declaration.
18331
0
  if (IsInvalidSMECallConversion(Old->getType(), New->getType())) {
18332
0
    Diag(New->getLocation(), diag::err_conflicting_overriding_attributes)
18333
0
        << New << New->getType() << Old->getType();
18334
0
    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18335
0
    return true;
18336
0
  }
18337
18338
  // Virtual overrides must have the same code_seg.
18339
0
  const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18340
0
  const auto *NewCSA = New->getAttr<CodeSegAttr>();
18341
0
  if ((NewCSA || OldCSA) &&
18342
0
      (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18343
0
    Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
18344
0
    Diag(Old->getLocation(), diag::note_previous_declaration);
18345
0
    return true;
18346
0
  }
18347
18348
0
  CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18349
18350
  // If the calling conventions match, everything is fine
18351
0
  if (NewCC == OldCC)
18352
0
    return false;
18353
18354
  // If the calling conventions mismatch because the new function is static,
18355
  // suppress the calling convention mismatch error; the error about static
18356
  // function override (err_static_overrides_virtual from
18357
  // Sema::CheckFunctionDeclaration) is more clear.
18358
0
  if (New->getStorageClass() == SC_Static)
18359
0
    return false;
18360
18361
0
  Diag(New->getLocation(),
18362
0
       diag::err_conflicting_overriding_cc_attributes)
18363
0
    << New->getDeclName() << New->getType() << Old->getType();
18364
0
  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18365
0
  return true;
18366
0
}
18367
18368
bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,
18369
0
                                       const CXXMethodDecl *Old) {
18370
  // CWG2553
18371
  // A virtual function shall not be an explicit object member function.
18372
0
  if (!New->isExplicitObjectMemberFunction())
18373
0
    return true;
18374
0
  Diag(New->getParamDecl(0)->getBeginLoc(),
18375
0
       diag::err_explicit_object_parameter_nonmember)
18376
0
      << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18377
0
  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
18378
0
  New->setInvalidDecl();
18379
0
  return false;
18380
0
}
18381
18382
bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
18383
0
                                             const CXXMethodDecl *Old) {
18384
0
  QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18385
0
  QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18386
18387
0
  if (Context.hasSameType(NewTy, OldTy) ||
18388
0
      NewTy->isDependentType() || OldTy->isDependentType())
18389
0
    return false;
18390
18391
  // Check if the return types are covariant
18392
0
  QualType NewClassTy, OldClassTy;
18393
18394
  /// Both types must be pointers or references to classes.
18395
0
  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18396
0
    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18397
0
      NewClassTy = NewPT->getPointeeType();
18398
0
      OldClassTy = OldPT->getPointeeType();
18399
0
    }
18400
0
  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18401
0
    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18402
0
      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18403
0
        NewClassTy = NewRT->getPointeeType();
18404
0
        OldClassTy = OldRT->getPointeeType();
18405
0
      }
18406
0
    }
18407
0
  }
18408
18409
  // The return types aren't either both pointers or references to a class type.
18410
0
  if (NewClassTy.isNull()) {
18411
0
    Diag(New->getLocation(),
18412
0
         diag::err_different_return_type_for_overriding_virtual_function)
18413
0
        << New->getDeclName() << NewTy << OldTy
18414
0
        << New->getReturnTypeSourceRange();
18415
0
    Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18416
0
        << Old->getReturnTypeSourceRange();
18417
18418
0
    return true;
18419
0
  }
18420
18421
0
  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
18422
    // C++14 [class.virtual]p8:
18423
    //   If the class type in the covariant return type of D::f differs from
18424
    //   that of B::f, the class type in the return type of D::f shall be
18425
    //   complete at the point of declaration of D::f or shall be the class
18426
    //   type D.
18427
0
    if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
18428
0
      if (!RT->isBeingDefined() &&
18429
0
          RequireCompleteType(New->getLocation(), NewClassTy,
18430
0
                              diag::err_covariant_return_incomplete,
18431
0
                              New->getDeclName()))
18432
0
        return true;
18433
0
    }
18434
18435
    // Check if the new class derives from the old class.
18436
0
    if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
18437
0
      Diag(New->getLocation(), diag::err_covariant_return_not_derived)
18438
0
          << New->getDeclName() << NewTy << OldTy
18439
0
          << New->getReturnTypeSourceRange();
18440
0
      Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18441
0
          << Old->getReturnTypeSourceRange();
18442
0
      return true;
18443
0
    }
18444
18445
    // Check if we the conversion from derived to base is valid.
18446
0
    if (CheckDerivedToBaseConversion(
18447
0
            NewClassTy, OldClassTy,
18448
0
            diag::err_covariant_return_inaccessible_base,
18449
0
            diag::err_covariant_return_ambiguous_derived_to_base_conv,
18450
0
            New->getLocation(), New->getReturnTypeSourceRange(),
18451
0
            New->getDeclName(), nullptr)) {
18452
      // FIXME: this note won't trigger for delayed access control
18453
      // diagnostics, and it's impossible to get an undelayed error
18454
      // here from access control during the original parse because
18455
      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18456
0
      Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18457
0
          << Old->getReturnTypeSourceRange();
18458
0
      return true;
18459
0
    }
18460
0
  }
18461
18462
  // The qualifiers of the return types must be the same.
18463
0
  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18464
0
    Diag(New->getLocation(),
18465
0
         diag::err_covariant_return_type_different_qualifications)
18466
0
        << New->getDeclName() << NewTy << OldTy
18467
0
        << New->getReturnTypeSourceRange();
18468
0
    Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18469
0
        << Old->getReturnTypeSourceRange();
18470
0
    return true;
18471
0
  }
18472
18473
18474
  // The new class type must have the same or less qualifiers as the old type.
18475
0
  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
18476
0
    Diag(New->getLocation(),
18477
0
         diag::err_covariant_return_type_class_type_more_qualified)
18478
0
        << New->getDeclName() << NewTy << OldTy
18479
0
        << New->getReturnTypeSourceRange();
18480
0
    Diag(Old->getLocation(), diag::note_overridden_virtual_function)
18481
0
        << Old->getReturnTypeSourceRange();
18482
0
    return true;
18483
0
  }
18484
18485
0
  return false;
18486
0
}
18487
18488
/// Mark the given method pure.
18489
///
18490
/// \param Method the method to be marked pure.
18491
///
18492
/// \param InitRange the source range that covers the "0" initializer.
18493
0
bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
18494
0
  SourceLocation EndLoc = InitRange.getEnd();
18495
0
  if (EndLoc.isValid())
18496
0
    Method->setRangeEnd(EndLoc);
18497
18498
0
  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18499
0
    Method->setPure();
18500
0
    return false;
18501
0
  }
18502
18503
0
  if (!Method->isInvalidDecl())
18504
0
    Diag(Method->getLocation(), diag::err_non_virtual_pure)
18505
0
      << Method->getDeclName() << InitRange;
18506
0
  return true;
18507
0
}
18508
18509
0
void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
18510
0
  if (D->getFriendObjectKind())
18511
0
    Diag(D->getLocation(), diag::err_pure_friend);
18512
0
  else if (auto *M = dyn_cast<CXXMethodDecl>(D))
18513
0
    CheckPureMethod(M, ZeroLoc);
18514
0
  else
18515
0
    Diag(D->getLocation(), diag::err_illegal_initializer);
18516
0
}
18517
18518
/// Determine whether the given declaration is a global variable or
18519
/// static data member.
18520
0
static bool isNonlocalVariable(const Decl *D) {
18521
0
  if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
18522
0
    return Var->hasGlobalStorage();
18523
18524
0
  return false;
18525
0
}
18526
18527
/// Invoked when we are about to parse an initializer for the declaration
18528
/// 'Dcl'.
18529
///
18530
/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
18531
/// static data member of class X, names should be looked up in the scope of
18532
/// class X. If the declaration had a scope specifier, a scope will have
18533
/// been created and passed in for this purpose. Otherwise, S will be null.
18534
304
void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
18535
  // If there is no declaration, there was an error parsing it.
18536
304
  if (!D || D->isInvalidDecl())
18537
304
    return;
18538
18539
  // We will always have a nested name specifier here, but this declaration
18540
  // might not be out of line if the specifier names the current namespace:
18541
  //   extern int n;
18542
  //   int ::n = 0;
18543
0
  if (S && D->isOutOfLine())
18544
0
    EnterDeclaratorContext(S, D->getDeclContext());
18545
18546
  // If we are parsing the initializer for a static data member, push a
18547
  // new expression evaluation context that is associated with this static
18548
  // data member.
18549
0
  if (isNonlocalVariable(D))
18550
0
    PushExpressionEvaluationContext(
18551
0
        ExpressionEvaluationContext::PotentiallyEvaluated, D);
18552
0
}
18553
18554
/// Invoked after we are finished parsing an initializer for the declaration D.
18555
304
void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
18556
  // If there is no declaration, there was an error parsing it.
18557
304
  if (!D || D->isInvalidDecl())
18558
304
    return;
18559
18560
0
  if (isNonlocalVariable(D))
18561
0
    PopExpressionEvaluationContext();
18562
18563
0
  if (S && D->isOutOfLine())
18564
0
    ExitDeclaratorContext(S);
18565
0
}
18566
18567
/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
18568
/// C++ if/switch/while/for statement.
18569
/// e.g: "if (int x = f()) {...}"
18570
0
DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
18571
  // C++ 6.4p2:
18572
  // The declarator shall not specify a function or an array.
18573
  // The type-specifier-seq shall not contain typedef and shall not declare a
18574
  // new class or enumeration.
18575
0
  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
18576
0
         "Parser allowed 'typedef' as storage class of condition decl.");
18577
18578
0
  Decl *Dcl = ActOnDeclarator(S, D);
18579
0
  if (!Dcl)
18580
0
    return true;
18581
18582
0
  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
18583
0
    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
18584
0
      << D.getSourceRange();
18585
0
    return true;
18586
0
  }
18587
18588
0
  return Dcl;
18589
0
}
18590
18591
46
void Sema::LoadExternalVTableUses() {
18592
46
  if (!ExternalSource)
18593
46
    return;
18594
18595
0
  SmallVector<ExternalVTableUse, 4> VTables;
18596
0
  ExternalSource->ReadUsedVTables(VTables);
18597
0
  SmallVector<VTableUse, 4> NewUses;
18598
0
  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
18599
0
    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
18600
0
      = VTablesUsed.find(VTables[I].Record);
18601
    // Even if a definition wasn't required before, it may be required now.
18602
0
    if (Pos != VTablesUsed.end()) {
18603
0
      if (!Pos->second && VTables[I].DefinitionRequired)
18604
0
        Pos->second = true;
18605
0
      continue;
18606
0
    }
18607
18608
0
    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
18609
0
    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
18610
0
  }
18611
18612
0
  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
18613
0
}
18614
18615
void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
18616
0
                          bool DefinitionRequired) {
18617
  // Ignore any vtable uses in unevaluated operands or for classes that do
18618
  // not have a vtable.
18619
0
  if (!Class->isDynamicClass() || Class->isDependentContext() ||
18620
0
      CurContext->isDependentContext() || isUnevaluatedContext())
18621
0
    return;
18622
  // Do not mark as used if compiling for the device outside of the target
18623
  // region.
18624
0
  if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
18625
0
      !isInOpenMPDeclareTargetContext() &&
18626
0
      !isInOpenMPTargetExecutionDirective()) {
18627
0
    if (!DefinitionRequired)
18628
0
      MarkVirtualMembersReferenced(Loc, Class);
18629
0
    return;
18630
0
  }
18631
18632
  // Try to insert this class into the map.
18633
0
  LoadExternalVTableUses();
18634
0
  Class = Class->getCanonicalDecl();
18635
0
  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
18636
0
    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
18637
0
  if (!Pos.second) {
18638
    // If we already had an entry, check to see if we are promoting this vtable
18639
    // to require a definition. If so, we need to reappend to the VTableUses
18640
    // list, since we may have already processed the first entry.
18641
0
    if (DefinitionRequired && !Pos.first->second) {
18642
0
      Pos.first->second = true;
18643
0
    } else {
18644
      // Otherwise, we can early exit.
18645
0
      return;
18646
0
    }
18647
0
  } else {
18648
    // The Microsoft ABI requires that we perform the destructor body
18649
    // checks (i.e. operator delete() lookup) when the vtable is marked used, as
18650
    // the deleting destructor is emitted with the vtable, not with the
18651
    // destructor definition as in the Itanium ABI.
18652
0
    if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18653
0
      CXXDestructorDecl *DD = Class->getDestructor();
18654
0
      if (DD && DD->isVirtual() && !DD->isDeleted()) {
18655
0
        if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
18656
          // If this is an out-of-line declaration, marking it referenced will
18657
          // not do anything. Manually call CheckDestructor to look up operator
18658
          // delete().
18659
0
          ContextRAII SavedContext(*this, DD);
18660
0
          CheckDestructor(DD);
18661
0
        } else {
18662
0
          MarkFunctionReferenced(Loc, Class->getDestructor());
18663
0
        }
18664
0
      }
18665
0
    }
18666
0
  }
18667
18668
  // Local classes need to have their virtual members marked
18669
  // immediately. For all other classes, we mark their virtual members
18670
  // at the end of the translation unit.
18671
0
  if (Class->isLocalClass())
18672
0
    MarkVirtualMembersReferenced(Loc, Class->getDefinition());
18673
0
  else
18674
0
    VTableUses.push_back(std::make_pair(Class, Loc));
18675
0
}
18676
18677
46
bool Sema::DefineUsedVTables() {
18678
46
  LoadExternalVTableUses();
18679
46
  if (VTableUses.empty())
18680
46
    return false;
18681
18682
  // Note: The VTableUses vector could grow as a result of marking
18683
  // the members of a class as "used", so we check the size each
18684
  // time through the loop and prefer indices (which are stable) to
18685
  // iterators (which are not).
18686
0
  bool DefinedAnything = false;
18687
0
  for (unsigned I = 0; I != VTableUses.size(); ++I) {
18688
0
    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
18689
0
    if (!Class)
18690
0
      continue;
18691
0
    TemplateSpecializationKind ClassTSK =
18692
0
        Class->getTemplateSpecializationKind();
18693
18694
0
    SourceLocation Loc = VTableUses[I].second;
18695
18696
0
    bool DefineVTable = true;
18697
18698
    // If this class has a key function, but that key function is
18699
    // defined in another translation unit, we don't need to emit the
18700
    // vtable even though we're using it.
18701
0
    const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
18702
0
    if (KeyFunction && !KeyFunction->hasBody()) {
18703
      // The key function is in another translation unit.
18704
0
      DefineVTable = false;
18705
0
      TemplateSpecializationKind TSK =
18706
0
          KeyFunction->getTemplateSpecializationKind();
18707
0
      assert(TSK != TSK_ExplicitInstantiationDefinition &&
18708
0
             TSK != TSK_ImplicitInstantiation &&
18709
0
             "Instantiations don't have key functions");
18710
0
      (void)TSK;
18711
0
    } else if (!KeyFunction) {
18712
      // If we have a class with no key function that is the subject
18713
      // of an explicit instantiation declaration, suppress the
18714
      // vtable; it will live with the explicit instantiation
18715
      // definition.
18716
0
      bool IsExplicitInstantiationDeclaration =
18717
0
          ClassTSK == TSK_ExplicitInstantiationDeclaration;
18718
0
      for (auto *R : Class->redecls()) {
18719
0
        TemplateSpecializationKind TSK
18720
0
          = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18721
0
        if (TSK == TSK_ExplicitInstantiationDeclaration)
18722
0
          IsExplicitInstantiationDeclaration = true;
18723
0
        else if (TSK == TSK_ExplicitInstantiationDefinition) {
18724
0
          IsExplicitInstantiationDeclaration = false;
18725
0
          break;
18726
0
        }
18727
0
      }
18728
18729
0
      if (IsExplicitInstantiationDeclaration)
18730
0
        DefineVTable = false;
18731
0
    }
18732
18733
    // The exception specifications for all virtual members may be needed even
18734
    // if we are not providing an authoritative form of the vtable in this TU.
18735
    // We may choose to emit it available_externally anyway.
18736
0
    if (!DefineVTable) {
18737
0
      MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
18738
0
      continue;
18739
0
    }
18740
18741
    // Mark all of the virtual members of this class as referenced, so
18742
    // that we can build a vtable. Then, tell the AST consumer that a
18743
    // vtable for this class is required.
18744
0
    DefinedAnything = true;
18745
0
    MarkVirtualMembersReferenced(Loc, Class);
18746
0
    CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18747
0
    if (VTablesUsed[Canonical])
18748
0
      Consumer.HandleVTable(Class);
18749
18750
    // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18751
    // no key function or the key function is inlined. Don't warn in C++ ABIs
18752
    // that lack key functions, since the user won't be able to make one.
18753
0
    if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
18754
0
        Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18755
0
        ClassTSK != TSK_ExplicitInstantiationDefinition) {
18756
0
      const FunctionDecl *KeyFunctionDef = nullptr;
18757
0
      if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18758
0
                           KeyFunctionDef->isInlined()))
18759
0
        Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18760
0
    }
18761
0
  }
18762
0
  VTableUses.clear();
18763
18764
0
  return DefinedAnything;
18765
46
}
18766
18767
void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
18768
0
                                                 const CXXRecordDecl *RD) {
18769
0
  for (const auto *I : RD->methods())
18770
0
    if (I->isVirtual() && !I->isPure())
18771
0
      ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18772
0
}
18773
18774
void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
18775
                                        const CXXRecordDecl *RD,
18776
0
                                        bool ConstexprOnly) {
18777
  // Mark all functions which will appear in RD's vtable as used.
18778
0
  CXXFinalOverriderMap FinalOverriders;
18779
0
  RD->getFinalOverriders(FinalOverriders);
18780
0
  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18781
0
                                            E = FinalOverriders.end();
18782
0
       I != E; ++I) {
18783
0
    for (OverridingMethods::const_iterator OI = I->second.begin(),
18784
0
                                           OE = I->second.end();
18785
0
         OI != OE; ++OI) {
18786
0
      assert(OI->second.size() > 0 && "no final overrider");
18787
0
      CXXMethodDecl *Overrider = OI->second.front().Method;
18788
18789
      // C++ [basic.def.odr]p2:
18790
      //   [...] A virtual member function is used if it is not pure. [...]
18791
0
      if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
18792
0
        MarkFunctionReferenced(Loc, Overrider);
18793
0
    }
18794
0
  }
18795
18796
  // Only classes that have virtual bases need a VTT.
18797
0
  if (RD->getNumVBases() == 0)
18798
0
    return;
18799
18800
0
  for (const auto &I : RD->bases()) {
18801
0
    const auto *Base =
18802
0
        cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18803
0
    if (Base->getNumVBases() == 0)
18804
0
      continue;
18805
0
    MarkVirtualMembersReferenced(Loc, Base);
18806
0
  }
18807
0
}
18808
18809
/// SetIvarInitializers - This routine builds initialization ASTs for the
18810
/// Objective-C implementation whose ivars need be initialized.
18811
0
void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
18812
0
  if (!getLangOpts().CPlusPlus)
18813
0
    return;
18814
0
  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
18815
0
    SmallVector<ObjCIvarDecl*, 8> ivars;
18816
0
    CollectIvarsToConstructOrDestruct(OID, ivars);
18817
0
    if (ivars.empty())
18818
0
      return;
18819
0
    SmallVector<CXXCtorInitializer*, 32> AllToInit;
18820
0
    for (unsigned i = 0; i < ivars.size(); i++) {
18821
0
      FieldDecl *Field = ivars[i];
18822
0
      if (Field->isInvalidDecl())
18823
0
        continue;
18824
18825
0
      CXXCtorInitializer *Member;
18826
0
      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
18827
0
      InitializationKind InitKind =
18828
0
        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
18829
18830
0
      InitializationSequence InitSeq(*this, InitEntity, InitKind, std::nullopt);
18831
0
      ExprResult MemberInit =
18832
0
          InitSeq.Perform(*this, InitEntity, InitKind, std::nullopt);
18833
0
      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
18834
      // Note, MemberInit could actually come back empty if no initialization
18835
      // is required (e.g., because it would call a trivial default constructor)
18836
0
      if (!MemberInit.get() || MemberInit.isInvalid())
18837
0
        continue;
18838
18839
0
      Member =
18840
0
        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
18841
0
                                         SourceLocation(),
18842
0
                                         MemberInit.getAs<Expr>(),
18843
0
                                         SourceLocation());
18844
0
      AllToInit.push_back(Member);
18845
18846
      // Be sure that the destructor is accessible and is marked as referenced.
18847
0
      if (const RecordType *RecordTy =
18848
0
              Context.getBaseElementType(Field->getType())
18849
0
                  ->getAs<RecordType>()) {
18850
0
        CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
18851
0
        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
18852
0
          MarkFunctionReferenced(Field->getLocation(), Destructor);
18853
0
          CheckDestructorAccess(Field->getLocation(), Destructor,
18854
0
                            PDiag(diag::err_access_dtor_ivar)
18855
0
                              << Context.getBaseElementType(Field->getType()));
18856
0
        }
18857
0
      }
18858
0
    }
18859
0
    ObjCImplementation->setIvarInitializers(Context,
18860
0
                                            AllToInit.data(), AllToInit.size());
18861
0
  }
18862
0
}
18863
18864
static
18865
void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
18866
                           llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
18867
                           llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
18868
                           llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
18869
0
                           Sema &S) {
18870
0
  if (Ctor->isInvalidDecl())
18871
0
    return;
18872
18873
0
  CXXConstructorDecl *Target = Ctor->getTargetConstructor();
18874
18875
  // Target may not be determinable yet, for instance if this is a dependent
18876
  // call in an uninstantiated template.
18877
0
  if (Target) {
18878
0
    const FunctionDecl *FNTarget = nullptr;
18879
0
    (void)Target->hasBody(FNTarget);
18880
0
    Target = const_cast<CXXConstructorDecl*>(
18881
0
      cast_or_null<CXXConstructorDecl>(FNTarget));
18882
0
  }
18883
18884
0
  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18885
                     // Avoid dereferencing a null pointer here.
18886
0
                     *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18887
18888
0
  if (!Current.insert(Canonical).second)
18889
0
    return;
18890
18891
  // We know that beyond here, we aren't chaining into a cycle.
18892
0
  if (!Target || !Target->isDelegatingConstructor() ||
18893
0
      Target->isInvalidDecl() || Valid.count(TCanonical)) {
18894
0
    Valid.insert(Current.begin(), Current.end());
18895
0
    Current.clear();
18896
  // We've hit a cycle.
18897
0
  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18898
0
             Current.count(TCanonical)) {
18899
    // If we haven't diagnosed this cycle yet, do so now.
18900
0
    if (!Invalid.count(TCanonical)) {
18901
0
      S.Diag((*Ctor->init_begin())->getSourceLocation(),
18902
0
             diag::warn_delegating_ctor_cycle)
18903
0
        << Ctor;
18904
18905
      // Don't add a note for a function delegating directly to itself.
18906
0
      if (TCanonical != Canonical)
18907
0
        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18908
18909
0
      CXXConstructorDecl *C = Target;
18910
0
      while (C->getCanonicalDecl() != Canonical) {
18911
0
        const FunctionDecl *FNTarget = nullptr;
18912
0
        (void)C->getTargetConstructor()->hasBody(FNTarget);
18913
0
        assert(FNTarget && "Ctor cycle through bodiless function");
18914
18915
0
        C = const_cast<CXXConstructorDecl*>(
18916
0
          cast<CXXConstructorDecl>(FNTarget));
18917
0
        S.Diag(C->getLocation(), diag::note_which_delegates_to);
18918
0
      }
18919
0
    }
18920
18921
0
    Invalid.insert(Current.begin(), Current.end());
18922
0
    Current.clear();
18923
0
  } else {
18924
0
    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18925
0
  }
18926
0
}
18927
18928
18929
23
void Sema::CheckDelegatingCtorCycles() {
18930
23
  llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
18931
18932
23
  for (DelegatingCtorDeclsType::iterator
18933
23
           I = DelegatingCtorDecls.begin(ExternalSource.get()),
18934
23
           E = DelegatingCtorDecls.end();
18935
23
       I != E; ++I)
18936
0
    DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18937
18938
23
  for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18939
0
    (*CI)->setInvalidDecl();
18940
23
}
18941
18942
namespace {
18943
  /// AST visitor that finds references to the 'this' expression.
18944
  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18945
    Sema &S;
18946
18947
  public:
18948
0
    explicit FindCXXThisExpr(Sema &S) : S(S) { }
18949
18950
0
    bool VisitCXXThisExpr(CXXThisExpr *E) {
18951
0
      S.Diag(E->getLocation(), diag::err_this_static_member_func)
18952
0
        << E->isImplicit();
18953
0
      return false;
18954
0
    }
18955
  };
18956
}
18957
18958
0
bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
18959
0
  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18960
0
  if (!TSInfo)
18961
0
    return false;
18962
18963
0
  TypeLoc TL = TSInfo->getTypeLoc();
18964
0
  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18965
0
  if (!ProtoTL)
18966
0
    return false;
18967
18968
  // C++11 [expr.prim.general]p3:
18969
  //   [The expression this] shall not appear before the optional
18970
  //   cv-qualifier-seq and it shall not appear within the declaration of a
18971
  //   static member function (although its type and value category are defined
18972
  //   within a static member function as they are within a non-static member
18973
  //   function). [ Note: this is because declaration matching does not occur
18974
  //  until the complete declarator is known. - end note ]
18975
0
  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18976
0
  FindCXXThisExpr Finder(*this);
18977
18978
  // If the return type came after the cv-qualifier-seq, check it now.
18979
0
  if (Proto->hasTrailingReturn() &&
18980
0
      !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18981
0
    return true;
18982
18983
  // Check the exception specification.
18984
0
  if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18985
0
    return true;
18986
18987
  // Check the trailing requires clause
18988
0
  if (Expr *E = Method->getTrailingRequiresClause())
18989
0
    if (!Finder.TraverseStmt(E))
18990
0
      return true;
18991
18992
0
  return checkThisInStaticMemberFunctionAttributes(Method);
18993
0
}
18994
18995
0
bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
18996
0
  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18997
0
  if (!TSInfo)
18998
0
    return false;
18999
19000
0
  TypeLoc TL = TSInfo->getTypeLoc();
19001
0
  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19002
0
  if (!ProtoTL)
19003
0
    return false;
19004
19005
0
  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19006
0
  FindCXXThisExpr Finder(*this);
19007
19008
0
  switch (Proto->getExceptionSpecType()) {
19009
0
  case EST_Unparsed:
19010
0
  case EST_Uninstantiated:
19011
0
  case EST_Unevaluated:
19012
0
  case EST_BasicNoexcept:
19013
0
  case EST_NoThrow:
19014
0
  case EST_DynamicNone:
19015
0
  case EST_MSAny:
19016
0
  case EST_None:
19017
0
    break;
19018
19019
0
  case EST_DependentNoexcept:
19020
0
  case EST_NoexceptFalse:
19021
0
  case EST_NoexceptTrue:
19022
0
    if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
19023
0
      return true;
19024
0
    [[fallthrough]];
19025
19026
0
  case EST_Dynamic:
19027
0
    for (const auto &E : Proto->exceptions()) {
19028
0
      if (!Finder.TraverseType(E))
19029
0
        return true;
19030
0
    }
19031
0
    break;
19032
0
  }
19033
19034
0
  return false;
19035
0
}
19036
19037
0
bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
19038
0
  FindCXXThisExpr Finder(*this);
19039
19040
  // Check attributes.
19041
0
  for (const auto *A : Method->attrs()) {
19042
    // FIXME: This should be emitted by tblgen.
19043
0
    Expr *Arg = nullptr;
19044
0
    ArrayRef<Expr *> Args;
19045
0
    if (const auto *G = dyn_cast<GuardedByAttr>(A))
19046
0
      Arg = G->getArg();
19047
0
    else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
19048
0
      Arg = G->getArg();
19049
0
    else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
19050
0
      Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19051
0
    else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
19052
0
      Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19053
0
    else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
19054
0
      Arg = ETLF->getSuccessValue();
19055
0
      Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
19056
0
    } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
19057
0
      Arg = STLF->getSuccessValue();
19058
0
      Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
19059
0
    } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
19060
0
      Arg = LR->getArg();
19061
0
    else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
19062
0
      Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19063
0
    else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
19064
0
      Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19065
0
    else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
19066
0
      Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19067
0
    else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
19068
0
      Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19069
0
    else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
19070
0
      Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19071
19072
0
    if (Arg && !Finder.TraverseStmt(Arg))
19073
0
      return true;
19074
19075
0
    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
19076
0
      if (!Finder.TraverseStmt(Args[I]))
19077
0
        return true;
19078
0
    }
19079
0
  }
19080
19081
0
  return false;
19082
0
}
19083
19084
void Sema::checkExceptionSpecification(
19085
    bool IsTopLevel, ExceptionSpecificationType EST,
19086
    ArrayRef<ParsedType> DynamicExceptions,
19087
    ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19088
    SmallVectorImpl<QualType> &Exceptions,
19089
13
    FunctionProtoType::ExceptionSpecInfo &ESI) {
19090
13
  Exceptions.clear();
19091
13
  ESI.Type = EST;
19092
13
  if (EST == EST_Dynamic) {
19093
0
    Exceptions.reserve(DynamicExceptions.size());
19094
0
    for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19095
      // FIXME: Preserve type source info.
19096
0
      QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
19097
19098
0
      if (IsTopLevel) {
19099
0
        SmallVector<UnexpandedParameterPack, 2> Unexpanded;
19100
0
        collectUnexpandedParameterPacks(ET, Unexpanded);
19101
0
        if (!Unexpanded.empty()) {
19102
0
          DiagnoseUnexpandedParameterPacks(
19103
0
              DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
19104
0
              Unexpanded);
19105
0
          continue;
19106
0
        }
19107
0
      }
19108
19109
      // Check that the type is valid for an exception spec, and
19110
      // drop it if not.
19111
0
      if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
19112
0
        Exceptions.push_back(ET);
19113
0
    }
19114
0
    ESI.Exceptions = Exceptions;
19115
0
    return;
19116
0
  }
19117
19118
13
  if (isComputedNoexcept(EST)) {
19119
0
    assert((NoexceptExpr->isTypeDependent() ||
19120
0
            NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19121
0
            Context.BoolTy) &&
19122
0
           "Parser should have made sure that the expression is boolean");
19123
0
    if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
19124
0
      ESI.Type = EST_BasicNoexcept;
19125
0
      return;
19126
0
    }
19127
19128
0
    ESI.NoexceptExpr = NoexceptExpr;
19129
0
    return;
19130
0
  }
19131
13
}
19132
19133
void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
19134
             ExceptionSpecificationType EST,
19135
             SourceRange SpecificationRange,
19136
             ArrayRef<ParsedType> DynamicExceptions,
19137
             ArrayRef<SourceRange> DynamicExceptionRanges,
19138
0
             Expr *NoexceptExpr) {
19139
0
  if (!MethodD)
19140
0
    return;
19141
19142
  // Dig out the method we're referring to.
19143
0
  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
19144
0
    MethodD = FunTmpl->getTemplatedDecl();
19145
19146
0
  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
19147
0
  if (!Method)
19148
0
    return;
19149
19150
  // Check the exception specification.
19151
0
  llvm::SmallVector<QualType, 4> Exceptions;
19152
0
  FunctionProtoType::ExceptionSpecInfo ESI;
19153
0
  checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
19154
0
                              DynamicExceptionRanges, NoexceptExpr, Exceptions,
19155
0
                              ESI);
19156
19157
  // Update the exception specification on the function type.
19158
0
  Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
19159
19160
0
  if (Method->isStatic())
19161
0
    checkThisInStaticMemberFunctionExceptionSpec(Method);
19162
19163
0
  if (Method->isVirtual()) {
19164
    // Check overrides, which we previously had to delay.
19165
0
    for (const CXXMethodDecl *O : Method->overridden_methods())
19166
0
      CheckOverridingFunctionExceptionSpec(Method, O);
19167
0
  }
19168
0
}
19169
19170
/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19171
///
19172
MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
19173
                                       SourceLocation DeclStart, Declarator &D,
19174
                                       Expr *BitWidth,
19175
                                       InClassInitStyle InitStyle,
19176
                                       AccessSpecifier AS,
19177
0
                                       const ParsedAttr &MSPropertyAttr) {
19178
0
  IdentifierInfo *II = D.getIdentifier();
19179
0
  if (!II) {
19180
0
    Diag(DeclStart, diag::err_anonymous_property);
19181
0
    return nullptr;
19182
0
  }
19183
0
  SourceLocation Loc = D.getIdentifierLoc();
19184
19185
0
  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
19186
0
  QualType T = TInfo->getType();
19187
0
  if (getLangOpts().CPlusPlus) {
19188
0
    CheckExtraCXXDefaultArguments(D);
19189
19190
0
    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
19191
0
                                        UPPC_DataMemberType)) {
19192
0
      D.setInvalidType();
19193
0
      T = Context.IntTy;
19194
0
      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19195
0
    }
19196
0
  }
19197
19198
0
  DiagnoseFunctionSpecifiers(D.getDeclSpec());
19199
19200
0
  if (D.getDeclSpec().isInlineSpecified())
19201
0
    Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
19202
0
        << getLangOpts().CPlusPlus17;
19203
0
  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19204
0
    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
19205
0
         diag::err_invalid_thread)
19206
0
      << DeclSpec::getSpecifierName(TSCS);
19207
19208
  // Check to see if this name was declared as a member previously
19209
0
  NamedDecl *PrevDecl = nullptr;
19210
0
  LookupResult Previous(*this, II, Loc, LookupMemberName,
19211
0
                        ForVisibleRedeclaration);
19212
0
  LookupName(Previous, S);
19213
0
  switch (Previous.getResultKind()) {
19214
0
  case LookupResult::Found:
19215
0
  case LookupResult::FoundUnresolvedValue:
19216
0
    PrevDecl = Previous.getAsSingle<NamedDecl>();
19217
0
    break;
19218
19219
0
  case LookupResult::FoundOverloaded:
19220
0
    PrevDecl = Previous.getRepresentativeDecl();
19221
0
    break;
19222
19223
0
  case LookupResult::NotFound:
19224
0
  case LookupResult::NotFoundInCurrentInstantiation:
19225
0
  case LookupResult::Ambiguous:
19226
0
    break;
19227
0
  }
19228
19229
0
  if (PrevDecl && PrevDecl->isTemplateParameter()) {
19230
    // Maybe we will complain about the shadowed template parameter.
19231
0
    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
19232
    // Just pretend that we didn't see the previous declaration.
19233
0
    PrevDecl = nullptr;
19234
0
  }
19235
19236
0
  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
19237
0
    PrevDecl = nullptr;
19238
19239
0
  SourceLocation TSSL = D.getBeginLoc();
19240
0
  MSPropertyDecl *NewPD =
19241
0
      MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
19242
0
                             MSPropertyAttr.getPropertyDataGetter(),
19243
0
                             MSPropertyAttr.getPropertyDataSetter());
19244
0
  ProcessDeclAttributes(TUScope, NewPD, D);
19245
0
  NewPD->setAccess(AS);
19246
19247
0
  if (NewPD->isInvalidDecl())
19248
0
    Record->setInvalidDecl();
19249
19250
0
  if (D.getDeclSpec().isModulePrivateSpecified())
19251
0
    NewPD->setModulePrivate();
19252
19253
0
  if (NewPD->isInvalidDecl() && PrevDecl) {
19254
    // Don't introduce NewFD into scope; there's already something
19255
    // with the same name in the same scope.
19256
0
  } else if (II) {
19257
0
    PushOnScopeChains(NewPD, S);
19258
0
  } else
19259
0
    Record->addDecl(NewPD);
19260
19261
0
  return NewPD;
19262
0
}
19263
19264
void Sema::ActOnStartFunctionDeclarationDeclarator(
19265
79
    Declarator &Declarator, unsigned TemplateParameterDepth) {
19266
79
  auto &Info = InventedParameterInfos.emplace_back();
19267
79
  TemplateParameterList *ExplicitParams = nullptr;
19268
79
  ArrayRef<TemplateParameterList *> ExplicitLists =
19269
79
      Declarator.getTemplateParameterLists();
19270
79
  if (!ExplicitLists.empty()) {
19271
0
    bool IsMemberSpecialization, IsInvalid;
19272
0
    ExplicitParams = MatchTemplateParametersToScopeSpecifier(
19273
0
        Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
19274
0
        Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19275
0
        ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
19276
0
        /*SuppressDiagnostic=*/true);
19277
0
  }
19278
79
  if (ExplicitParams) {
19279
0
    Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19280
0
    llvm::append_range(Info.TemplateParams, *ExplicitParams);
19281
0
    Info.NumExplicitTemplateParams = ExplicitParams->size();
19282
79
  } else {
19283
79
    Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19284
79
    Info.NumExplicitTemplateParams = 0;
19285
79
  }
19286
79
}
19287
19288
79
void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
19289
79
  auto &FSI = InventedParameterInfos.back();
19290
79
  if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19291
0
    if (FSI.NumExplicitTemplateParams != 0) {
19292
0
      TemplateParameterList *ExplicitParams =
19293
0
          Declarator.getTemplateParameterLists().back();
19294
0
      Declarator.setInventedTemplateParameterList(
19295
0
          TemplateParameterList::Create(
19296
0
              Context, ExplicitParams->getTemplateLoc(),
19297
0
              ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
19298
0
              ExplicitParams->getRAngleLoc(),
19299
0
              ExplicitParams->getRequiresClause()));
19300
0
    } else {
19301
0
      Declarator.setInventedTemplateParameterList(
19302
0
          TemplateParameterList::Create(
19303
0
              Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
19304
0
              SourceLocation(), /*RequiresClause=*/nullptr));
19305
0
    }
19306
0
  }
19307
79
  InventedParameterInfos.pop_back();
19308
79
}