Bug Summary

File:build/source/clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 7550, column 39
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaDeclCXX.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16 -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1673561342 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-01-13-042150-16221-1 -x c++ /build/source/clang/lib/Sema/SemaDeclCXX.cpp
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/ExprCXX.h"
24#include "clang/AST/RecordLayout.h"
25#include "clang/AST/RecursiveASTVisitor.h"
26#include "clang/AST/StmtVisitor.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/AST/TypeOrdering.h"
29#include "clang/Basic/AttributeCommonInfo.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Basic/TargetInfo.h"
33#include "clang/Lex/LiteralSupport.h"
34#include "clang/Lex/Preprocessor.h"
35#include "clang/Sema/CXXFieldCollector.h"
36#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/Initialization.h"
38#include "clang/Sema/Lookup.h"
39#include "clang/Sema/ParsedTemplate.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/ScopeInfo.h"
42#include "clang/Sema/SemaInternal.h"
43#include "clang/Sema/Template.h"
44#include "llvm/ADT/ScopeExit.h"
45#include "llvm/ADT/SmallString.h"
46#include "llvm/ADT/STLExtras.h"
47#include "llvm/ADT/StringExtras.h"
48#include <map>
49#include <set>
50
51using namespace clang;
52
53//===----------------------------------------------------------------------===//
54// CheckDefaultArgumentVisitor
55//===----------------------------------------------------------------------===//
56
57namespace {
58/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
59/// the default argument of a parameter to determine whether it
60/// contains any ill-formed subexpressions. For example, this will
61/// diagnose the use of local variables or parameters within the
62/// default argument expression.
63class CheckDefaultArgumentVisitor
64 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
65 Sema &S;
66 const Expr *DefaultArg;
67
68public:
69 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
70 : S(S), DefaultArg(DefaultArg) {}
71
72 bool VisitExpr(const Expr *Node);
73 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
74 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
75 bool VisitLambdaExpr(const LambdaExpr *Lambda);
76 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
77};
78
79/// VisitExpr - Visit all of the children of this expression.
80bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
81 bool IsInvalid = false;
82 for (const Stmt *SubStmt : Node->children())
83 IsInvalid |= Visit(SubStmt);
84 return IsInvalid;
85}
86
87/// VisitDeclRefExpr - Visit a reference to a declaration, to
88/// determine whether this declaration can be used in the default
89/// argument expression.
90bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
91 const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
92
93 if (!isa<VarDecl, BindingDecl>(Decl))
94 return false;
95
96 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
97 // C++ [dcl.fct.default]p9:
98 // [...] parameters of a function shall not be used in default
99 // argument expressions, even if they are not evaluated. [...]
100 //
101 // C++17 [dcl.fct.default]p9 (by CWG 2082):
102 // [...] A parameter shall not appear as a potentially-evaluated
103 // expression in a default argument. [...]
104 //
105 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
106 return S.Diag(DRE->getBeginLoc(),
107 diag::err_param_default_argument_references_param)
108 << Param->getDeclName() << DefaultArg->getSourceRange();
109 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
110 // C++ [dcl.fct.default]p7:
111 // Local variables shall not be used in default argument
112 // expressions.
113 //
114 // C++17 [dcl.fct.default]p7 (by CWG 2082):
115 // A local variable shall not appear as a potentially-evaluated
116 // expression in a default argument.
117 //
118 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
119 // Note: A local variable cannot be odr-used (6.3) in a default
120 // argument.
121 //
122 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
123 return S.Diag(DRE->getBeginLoc(),
124 diag::err_param_default_argument_references_local)
125 << Decl << DefaultArg->getSourceRange();
126 }
127 return false;
128}
129
130/// VisitCXXThisExpr - Visit a C++ "this" expression.
131bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
132 // C++ [dcl.fct.default]p8:
133 // The keyword this shall not be used in a default argument of a
134 // member function.
135 return S.Diag(ThisE->getBeginLoc(),
136 diag::err_param_default_argument_references_this)
137 << ThisE->getSourceRange();
138}
139
140bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
141 const PseudoObjectExpr *POE) {
142 bool Invalid = false;
143 for (const Expr *E : POE->semantics()) {
144 // Look through bindings.
145 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
146 E = OVE->getSourceExpr();
147 assert(E && "pseudo-object binding without source expression?")(static_cast <bool> (E && "pseudo-object binding without source expression?"
) ? void (0) : __assert_fail ("E && \"pseudo-object binding without source expression?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 147, __extension__ __PRETTY_FUNCTION__
))
;
148 }
149
150 Invalid |= Visit(E);
151 }
152 return Invalid;
153}
154
155bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
156 // [expr.prim.lambda.capture]p9
157 // a lambda-expression appearing in a default argument cannot implicitly or
158 // explicitly capture any local entity. Such a lambda-expression can still
159 // have an init-capture if any full-expression in its initializer satisfies
160 // the constraints of an expression appearing in a default argument.
161 bool Invalid = false;
162 for (const LambdaCapture &LC : Lambda->captures()) {
163 if (!Lambda->isInitCapture(&LC))
164 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
165 // Init captures are always VarDecl.
166 auto *D = cast<VarDecl>(LC.getCapturedVar());
167 Invalid |= Visit(D->getInit());
168 }
169 return Invalid;
170}
171} // namespace
172
173void
174Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
175 const CXXMethodDecl *Method) {
176 // If we have an MSAny spec already, don't bother.
177 if (!Method || ComputedEST == EST_MSAny)
178 return;
179
180 const FunctionProtoType *Proto
181 = Method->getType()->getAs<FunctionProtoType>();
182 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
183 if (!Proto)
184 return;
185
186 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
187
188 // If we have a throw-all spec at this point, ignore the function.
189 if (ComputedEST == EST_None)
190 return;
191
192 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
193 EST = EST_BasicNoexcept;
194
195 switch (EST) {
196 case EST_Unparsed:
197 case EST_Uninstantiated:
198 case EST_Unevaluated:
199 llvm_unreachable("should not see unresolved exception specs here")::llvm::llvm_unreachable_internal("should not see unresolved exception specs here"
, "clang/lib/Sema/SemaDeclCXX.cpp", 199)
;
200
201 // If this function can throw any exceptions, make a note of that.
202 case EST_MSAny:
203 case EST_None:
204 // FIXME: Whichever we see last of MSAny and None determines our result.
205 // We should make a consistent, order-independent choice here.
206 ClearExceptions();
207 ComputedEST = EST;
208 return;
209 case EST_NoexceptFalse:
210 ClearExceptions();
211 ComputedEST = EST_None;
212 return;
213 // FIXME: If the call to this decl is using any of its default arguments, we
214 // need to search them for potentially-throwing calls.
215 // If this function has a basic noexcept, it doesn't affect the outcome.
216 case EST_BasicNoexcept:
217 case EST_NoexceptTrue:
218 case EST_NoThrow:
219 return;
220 // If we're still at noexcept(true) and there's a throw() callee,
221 // change to that specification.
222 case EST_DynamicNone:
223 if (ComputedEST == EST_BasicNoexcept)
224 ComputedEST = EST_DynamicNone;
225 return;
226 case EST_DependentNoexcept:
227 llvm_unreachable(::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "clang/lib/Sema/SemaDeclCXX.cpp", 228)
228 "should not generate implicit declarations for dependent cases")::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "clang/lib/Sema/SemaDeclCXX.cpp", 228)
;
229 case EST_Dynamic:
230 break;
231 }
232 assert(EST == EST_Dynamic && "EST case not considered earlier.")(static_cast <bool> (EST == EST_Dynamic && "EST case not considered earlier."
) ? void (0) : __assert_fail ("EST == EST_Dynamic && \"EST case not considered earlier.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 232, __extension__ __PRETTY_FUNCTION__
))
;
233 assert(ComputedEST != EST_None &&(static_cast <bool> (ComputedEST != EST_None &&
"Shouldn't collect exceptions when throw-all is guaranteed."
) ? void (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 234, __extension__ __PRETTY_FUNCTION__
))
234 "Shouldn't collect exceptions when throw-all is guaranteed.")(static_cast <bool> (ComputedEST != EST_None &&
"Shouldn't collect exceptions when throw-all is guaranteed."
) ? void (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 234, __extension__ __PRETTY_FUNCTION__
))
;
235 ComputedEST = EST_Dynamic;
236 // Record the exceptions in this function's exception specification.
237 for (const auto &E : Proto->exceptions())
238 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
239 Exceptions.push_back(E);
240}
241
242void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
243 if (!S || ComputedEST == EST_MSAny)
244 return;
245
246 // FIXME:
247 //
248 // C++0x [except.spec]p14:
249 // [An] implicit exception-specification specifies the type-id T if and
250 // only if T is allowed by the exception-specification of a function directly
251 // invoked by f's implicit definition; f shall allow all exceptions if any
252 // function it directly invokes allows all exceptions, and f shall allow no
253 // exceptions if every function it directly invokes allows no exceptions.
254 //
255 // Note in particular that if an implicit exception-specification is generated
256 // for a function containing a throw-expression, that specification can still
257 // be noexcept(true).
258 //
259 // Note also that 'directly invoked' is not defined in the standard, and there
260 // is no indication that we should only consider potentially-evaluated calls.
261 //
262 // Ultimately we should implement the intent of the standard: the exception
263 // specification should be the set of exceptions which can be thrown by the
264 // implicit definition. For now, we assume that any non-nothrow expression can
265 // throw any exception.
266
267 if (Self->canThrow(S))
268 ComputedEST = EST_None;
269}
270
271ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
272 SourceLocation EqualLoc) {
273 if (RequireCompleteType(Param->getLocation(), Param->getType(),
274 diag::err_typecheck_decl_incomplete_type))
275 return true;
276
277 // C++ [dcl.fct.default]p5
278 // A default argument expression is implicitly converted (clause
279 // 4) to the parameter type. The default argument expression has
280 // the same semantic constraints as the initializer expression in
281 // a declaration of a variable of the parameter type, using the
282 // copy-initialization semantics (8.5).
283 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
284 Param);
285 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
286 EqualLoc);
287 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
288 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
289 if (Result.isInvalid())
290 return true;
291 Arg = Result.getAs<Expr>();
292
293 CheckCompletedExpr(Arg, EqualLoc);
294 Arg = MaybeCreateExprWithCleanups(Arg);
295
296 return Arg;
297}
298
299void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
300 SourceLocation EqualLoc) {
301 // Add the default argument to the parameter
302 Param->setDefaultArg(Arg);
303
304 // We have already instantiated this parameter; provide each of the
305 // instantiations with the uninstantiated default argument.
306 UnparsedDefaultArgInstantiationsMap::iterator InstPos
307 = UnparsedDefaultArgInstantiations.find(Param);
308 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
309 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
310 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
311
312 // We're done tracking this parameter's instantiations.
313 UnparsedDefaultArgInstantiations.erase(InstPos);
314 }
315}
316
317/// ActOnParamDefaultArgument - Check whether the default argument
318/// provided for a function parameter is well-formed. If so, attach it
319/// to the parameter declaration.
320void
321Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
322 Expr *DefaultArg) {
323 if (!param || !DefaultArg)
324 return;
325
326 ParmVarDecl *Param = cast<ParmVarDecl>(param);
327 UnparsedDefaultArgLocs.erase(Param);
328
329 auto Fail = [&] {
330 Param->setInvalidDecl();
331 Param->setDefaultArg(new (Context) OpaqueValueExpr(
332 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
333 };
334
335 // Default arguments are only permitted in C++
336 if (!getLangOpts().CPlusPlus) {
337 Diag(EqualLoc, diag::err_param_default_argument)
338 << DefaultArg->getSourceRange();
339 return Fail();
340 }
341
342 // Check for unexpanded parameter packs.
343 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
344 return Fail();
345 }
346
347 // C++11 [dcl.fct.default]p3
348 // A default argument expression [...] shall not be specified for a
349 // parameter pack.
350 if (Param->isParameterPack()) {
351 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
352 << DefaultArg->getSourceRange();
353 // Recover by discarding the default argument.
354 Param->setDefaultArg(nullptr);
355 return;
356 }
357
358 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
359 if (Result.isInvalid())
360 return Fail();
361
362 DefaultArg = Result.getAs<Expr>();
363
364 // Check that the default argument is well-formed
365 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
366 if (DefaultArgChecker.Visit(DefaultArg))
367 return Fail();
368
369 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
370}
371
372/// ActOnParamUnparsedDefaultArgument - We've seen a default
373/// argument for a function parameter, but we can't parse it yet
374/// because we're inside a class definition. Note that this default
375/// argument will be parsed later.
376void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
377 SourceLocation EqualLoc,
378 SourceLocation ArgLoc) {
379 if (!param)
380 return;
381
382 ParmVarDecl *Param = cast<ParmVarDecl>(param);
383 Param->setUnparsedDefaultArg();
384 UnparsedDefaultArgLocs[Param] = ArgLoc;
385}
386
387/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
388/// the default argument for the parameter param failed.
389void Sema::ActOnParamDefaultArgumentError(Decl *param,
390 SourceLocation EqualLoc) {
391 if (!param)
392 return;
393
394 ParmVarDecl *Param = cast<ParmVarDecl>(param);
395 Param->setInvalidDecl();
396 UnparsedDefaultArgLocs.erase(Param);
397 Param->setDefaultArg(new (Context) OpaqueValueExpr(
398 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
399}
400
401/// CheckExtraCXXDefaultArguments - Check for any extra default
402/// arguments in the declarator, which is not a function declaration
403/// or definition and therefore is not permitted to have default
404/// arguments. This routine should be invoked for every declarator
405/// that is not a function declaration or definition.
406void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
407 // C++ [dcl.fct.default]p3
408 // A default argument expression shall be specified only in the
409 // parameter-declaration-clause of a function declaration or in a
410 // template-parameter (14.1). It shall not be specified for a
411 // parameter pack. If it is specified in a
412 // parameter-declaration-clause, it shall not occur within a
413 // declarator or abstract-declarator of a parameter-declaration.
414 bool MightBeFunction = D.isFunctionDeclarationContext();
415 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
416 DeclaratorChunk &chunk = D.getTypeObject(i);
417 if (chunk.Kind == DeclaratorChunk::Function) {
418 if (MightBeFunction) {
419 // This is a function declaration. It can have default arguments, but
420 // keep looking in case its return type is a function type with default
421 // arguments.
422 MightBeFunction = false;
423 continue;
424 }
425 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
426 ++argIdx) {
427 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
428 if (Param->hasUnparsedDefaultArg()) {
429 std::unique_ptr<CachedTokens> Toks =
430 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
431 SourceRange SR;
432 if (Toks->size() > 1)
433 SR = SourceRange((*Toks)[1].getLocation(),
434 Toks->back().getLocation());
435 else
436 SR = UnparsedDefaultArgLocs[Param];
437 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
438 << SR;
439 } else if (Param->getDefaultArg()) {
440 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
441 << Param->getDefaultArg()->getSourceRange();
442 Param->setDefaultArg(nullptr);
443 }
444 }
445 } else if (chunk.Kind != DeclaratorChunk::Paren) {
446 MightBeFunction = false;
447 }
448 }
449}
450
451static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
452 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
453 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
454 });
455}
456
457/// MergeCXXFunctionDecl - Merge two declarations of the same C++
458/// function, once we already know that they have the same
459/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
460/// error, false otherwise.
461bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
462 Scope *S) {
463 bool Invalid = false;
464
465 // The declaration context corresponding to the scope is the semantic
466 // parent, unless this is a local function declaration, in which case
467 // it is that surrounding function.
468 DeclContext *ScopeDC = New->isLocalExternDecl()
469 ? New->getLexicalDeclContext()
470 : New->getDeclContext();
471
472 // Find the previous declaration for the purpose of default arguments.
473 FunctionDecl *PrevForDefaultArgs = Old;
474 for (/**/; PrevForDefaultArgs;
475 // Don't bother looking back past the latest decl if this is a local
476 // extern declaration; nothing else could work.
477 PrevForDefaultArgs = New->isLocalExternDecl()
478 ? nullptr
479 : PrevForDefaultArgs->getPreviousDecl()) {
480 // Ignore hidden declarations.
481 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
482 continue;
483
484 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
485 !New->isCXXClassMember()) {
486 // Ignore default arguments of old decl if they are not in
487 // the same scope and this is not an out-of-line definition of
488 // a member function.
489 continue;
490 }
491
492 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
493 // If only one of these is a local function declaration, then they are
494 // declared in different scopes, even though isDeclInScope may think
495 // they're in the same scope. (If both are local, the scope check is
496 // sufficient, and if neither is local, then they are in the same scope.)
497 continue;
498 }
499
500 // We found the right previous declaration.
501 break;
502 }
503
504 // C++ [dcl.fct.default]p4:
505 // For non-template functions, default arguments can be added in
506 // later declarations of a function in the same
507 // scope. Declarations in different scopes have completely
508 // distinct sets of default arguments. That is, declarations in
509 // inner scopes do not acquire default arguments from
510 // declarations in outer scopes, and vice versa. In a given
511 // function declaration, all parameters subsequent to a
512 // parameter with a default argument shall have default
513 // arguments supplied in this or previous declarations. A
514 // default argument shall not be redefined by a later
515 // declaration (not even to the same value).
516 //
517 // C++ [dcl.fct.default]p6:
518 // Except for member functions of class templates, the default arguments
519 // in a member function definition that appears outside of the class
520 // definition are added to the set of default arguments provided by the
521 // member function declaration in the class definition.
522 for (unsigned p = 0, NumParams = PrevForDefaultArgs
523 ? PrevForDefaultArgs->getNumParams()
524 : 0;
525 p < NumParams; ++p) {
526 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
527 ParmVarDecl *NewParam = New->getParamDecl(p);
528
529 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
530 bool NewParamHasDfl = NewParam->hasDefaultArg();
531
532 if (OldParamHasDfl && NewParamHasDfl) {
533 unsigned DiagDefaultParamID =
534 diag::err_param_default_argument_redefinition;
535
536 // MSVC accepts that default parameters be redefined for member functions
537 // of template class. The new default parameter's value is ignored.
538 Invalid = true;
539 if (getLangOpts().MicrosoftExt) {
540 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
541 if (MD && MD->getParent()->getDescribedClassTemplate()) {
542 // Merge the old default argument into the new parameter.
543 NewParam->setHasInheritedDefaultArg();
544 if (OldParam->hasUninstantiatedDefaultArg())
545 NewParam->setUninstantiatedDefaultArg(
546 OldParam->getUninstantiatedDefaultArg());
547 else
548 NewParam->setDefaultArg(OldParam->getInit());
549 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
550 Invalid = false;
551 }
552 }
553
554 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
555 // hint here. Alternatively, we could walk the type-source information
556 // for NewParam to find the last source location in the type... but it
557 // isn't worth the effort right now. This is the kind of test case that
558 // is hard to get right:
559 // int f(int);
560 // void g(int (*fp)(int) = f);
561 // void g(int (*fp)(int) = &f);
562 Diag(NewParam->getLocation(), DiagDefaultParamID)
563 << NewParam->getDefaultArgRange();
564
565 // Look for the function declaration where the default argument was
566 // actually written, which may be a declaration prior to Old.
567 for (auto Older = PrevForDefaultArgs;
568 OldParam->hasInheritedDefaultArg(); /**/) {
569 Older = Older->getPreviousDecl();
570 OldParam = Older->getParamDecl(p);
571 }
572
573 Diag(OldParam->getLocation(), diag::note_previous_definition)
574 << OldParam->getDefaultArgRange();
575 } else if (OldParamHasDfl) {
576 // Merge the old default argument into the new parameter unless the new
577 // function is a friend declaration in a template class. In the latter
578 // case the default arguments will be inherited when the friend
579 // declaration will be instantiated.
580 if (New->getFriendObjectKind() == Decl::FOK_None ||
581 !New->getLexicalDeclContext()->isDependentContext()) {
582 // It's important to use getInit() here; getDefaultArg()
583 // strips off any top-level ExprWithCleanups.
584 NewParam->setHasInheritedDefaultArg();
585 if (OldParam->hasUnparsedDefaultArg())
586 NewParam->setUnparsedDefaultArg();
587 else if (OldParam->hasUninstantiatedDefaultArg())
588 NewParam->setUninstantiatedDefaultArg(
589 OldParam->getUninstantiatedDefaultArg());
590 else
591 NewParam->setDefaultArg(OldParam->getInit());
592 }
593 } else if (NewParamHasDfl) {
594 if (New->getDescribedFunctionTemplate()) {
595 // Paragraph 4, quoted above, only applies to non-template functions.
596 Diag(NewParam->getLocation(),
597 diag::err_param_default_argument_template_redecl)
598 << NewParam->getDefaultArgRange();
599 Diag(PrevForDefaultArgs->getLocation(),
600 diag::note_template_prev_declaration)
601 << false;
602 } else if (New->getTemplateSpecializationKind()
603 != TSK_ImplicitInstantiation &&
604 New->getTemplateSpecializationKind() != TSK_Undeclared) {
605 // C++ [temp.expr.spec]p21:
606 // Default function arguments shall not be specified in a declaration
607 // or a definition for one of the following explicit specializations:
608 // - the explicit specialization of a function template;
609 // - the explicit specialization of a member function template;
610 // - the explicit specialization of a member function of a class
611 // template where the class template specialization to which the
612 // member function specialization belongs is implicitly
613 // instantiated.
614 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
615 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
616 << New->getDeclName()
617 << NewParam->getDefaultArgRange();
618 } else if (New->getDeclContext()->isDependentContext()) {
619 // C++ [dcl.fct.default]p6 (DR217):
620 // Default arguments for a member function of a class template shall
621 // be specified on the initial declaration of the member function
622 // within the class template.
623 //
624 // Reading the tea leaves a bit in DR217 and its reference to DR205
625 // leads me to the conclusion that one cannot add default function
626 // arguments for an out-of-line definition of a member function of a
627 // dependent type.
628 int WhichKind = 2;
629 if (CXXRecordDecl *Record
630 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
631 if (Record->getDescribedClassTemplate())
632 WhichKind = 0;
633 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
634 WhichKind = 1;
635 else
636 WhichKind = 2;
637 }
638
639 Diag(NewParam->getLocation(),
640 diag::err_param_default_argument_member_template_redecl)
641 << WhichKind
642 << NewParam->getDefaultArgRange();
643 }
644 }
645 }
646
647 // DR1344: If a default argument is added outside a class definition and that
648 // default argument makes the function a special member function, the program
649 // is ill-formed. This can only happen for constructors.
650 if (isa<CXXConstructorDecl>(New) &&
651 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
652 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
653 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
654 if (NewSM != OldSM) {
655 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
656 assert(NewParam->hasDefaultArg())(static_cast <bool> (NewParam->hasDefaultArg()) ? void
(0) : __assert_fail ("NewParam->hasDefaultArg()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 656, __extension__ __PRETTY_FUNCTION__))
;
657 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
658 << NewParam->getDefaultArgRange() << NewSM;
659 Diag(Old->getLocation(), diag::note_previous_declaration);
660 }
661 }
662
663 const FunctionDecl *Def;
664 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
665 // template has a constexpr specifier then all its declarations shall
666 // contain the constexpr specifier.
667 if (New->getConstexprKind() != Old->getConstexprKind()) {
668 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
669 << New << static_cast<int>(New->getConstexprKind())
670 << static_cast<int>(Old->getConstexprKind());
671 Diag(Old->getLocation(), diag::note_previous_declaration);
672 Invalid = true;
673 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
674 Old->isDefined(Def) &&
675 // If a friend function is inlined but does not have 'inline'
676 // specifier, it is a definition. Do not report attribute conflict
677 // in this case, redefinition will be diagnosed later.
678 (New->isInlineSpecified() ||
679 New->getFriendObjectKind() == Decl::FOK_None)) {
680 // C++11 [dcl.fcn.spec]p4:
681 // If the definition of a function appears in a translation unit before its
682 // first declaration as inline, the program is ill-formed.
683 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
684 Diag(Def->getLocation(), diag::note_previous_definition);
685 Invalid = true;
686 }
687
688 // C++17 [temp.deduct.guide]p3:
689 // Two deduction guide declarations in the same translation unit
690 // for the same class template shall not have equivalent
691 // parameter-declaration-clauses.
692 if (isa<CXXDeductionGuideDecl>(New) &&
693 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
694 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
695 Diag(Old->getLocation(), diag::note_previous_declaration);
696 }
697
698 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
699 // argument expression, that declaration shall be a definition and shall be
700 // the only declaration of the function or function template in the
701 // translation unit.
702 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
703 functionDeclHasDefaultArgument(Old)) {
704 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
705 Diag(Old->getLocation(), diag::note_previous_declaration);
706 Invalid = true;
707 }
708
709 // C++11 [temp.friend]p4 (DR329):
710 // When a function is defined in a friend function declaration in a class
711 // template, the function is instantiated when the function is odr-used.
712 // The same restrictions on multiple declarations and definitions that
713 // apply to non-template function declarations and definitions also apply
714 // to these implicit definitions.
715 const FunctionDecl *OldDefinition = nullptr;
716 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
717 Old->isDefined(OldDefinition, true))
718 CheckForFunctionRedefinition(New, OldDefinition);
719
720 return Invalid;
721}
722
723NamedDecl *
724Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
725 MultiTemplateParamsArg TemplateParamLists) {
726 assert(D.isDecompositionDeclarator())(static_cast <bool> (D.isDecompositionDeclarator()) ? void
(0) : __assert_fail ("D.isDecompositionDeclarator()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 726, __extension__ __PRETTY_FUNCTION__))
;
727 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
728
729 // The syntax only allows a decomposition declarator as a simple-declaration,
730 // a for-range-declaration, or a condition in Clang, but we parse it in more
731 // cases than that.
732 if (!D.mayHaveDecompositionDeclarator()) {
733 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
734 << Decomp.getSourceRange();
735 return nullptr;
736 }
737
738 if (!TemplateParamLists.empty()) {
739 // FIXME: There's no rule against this, but there are also no rules that
740 // would actually make it usable, so we reject it for now.
741 Diag(TemplateParamLists.front()->getTemplateLoc(),
742 diag::err_decomp_decl_template);
743 return nullptr;
744 }
745
746 Diag(Decomp.getLSquareLoc(),
747 !getLangOpts().CPlusPlus17
748 ? diag::ext_decomp_decl
749 : D.getContext() == DeclaratorContext::Condition
750 ? diag::ext_decomp_decl_cond
751 : diag::warn_cxx14_compat_decomp_decl)
752 << Decomp.getSourceRange();
753
754 // The semantic context is always just the current context.
755 DeclContext *const DC = CurContext;
756
757 // C++17 [dcl.dcl]/8:
758 // The decl-specifier-seq shall contain only the type-specifier auto
759 // and cv-qualifiers.
760 // C++20 [dcl.dcl]/8:
761 // If decl-specifier-seq contains any decl-specifier other than static,
762 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
763 // C++2b [dcl.pre]/6:
764 // Each decl-specifier in the decl-specifier-seq shall be static,
765 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
766 auto &DS = D.getDeclSpec();
767 {
768 // Note: While constrained-auto needs to be checked, we do so separately so
769 // we can emit a better diagnostic.
770 SmallVector<StringRef, 8> BadSpecifiers;
771 SmallVector<SourceLocation, 8> BadSpecifierLocs;
772 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
773 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
774 if (auto SCS = DS.getStorageClassSpec()) {
775 if (SCS == DeclSpec::SCS_static) {
776 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
777 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
778 } else {
779 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
780 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
781 }
782 }
783 if (auto TSCS = DS.getThreadStorageClassSpec()) {
784 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
785 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
786 }
787 if (DS.hasConstexprSpecifier()) {
788 BadSpecifiers.push_back(
789 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
790 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
791 }
792 if (DS.isInlineSpecified()) {
793 BadSpecifiers.push_back("inline");
794 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
795 }
796
797 if (!BadSpecifiers.empty()) {
798 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
799 Err << (int)BadSpecifiers.size()
800 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
801 // Don't add FixItHints to remove the specifiers; we do still respect
802 // them when building the underlying variable.
803 for (auto Loc : BadSpecifierLocs)
804 Err << SourceRange(Loc, Loc);
805 } else if (!CPlusPlus20Specifiers.empty()) {
806 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
807 getLangOpts().CPlusPlus20
808 ? diag::warn_cxx17_compat_decomp_decl_spec
809 : diag::ext_decomp_decl_spec);
810 Warn << (int)CPlusPlus20Specifiers.size()
811 << llvm::join(CPlusPlus20Specifiers.begin(),
812 CPlusPlus20Specifiers.end(), " ");
813 for (auto Loc : CPlusPlus20SpecifierLocs)
814 Warn << SourceRange(Loc, Loc);
815 }
816 // We can't recover from it being declared as a typedef.
817 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
818 return nullptr;
819 }
820
821 // C++2a [dcl.struct.bind]p1:
822 // A cv that includes volatile is deprecated
823 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
824 getLangOpts().CPlusPlus20)
825 Diag(DS.getVolatileSpecLoc(),
826 diag::warn_deprecated_volatile_structured_binding);
827
828 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
829 QualType R = TInfo->getType();
830
831 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
832 UPPC_DeclarationType))
833 D.setInvalidType();
834
835 // The syntax only allows a single ref-qualifier prior to the decomposition
836 // declarator. No other declarator chunks are permitted. Also check the type
837 // specifier here.
838 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
839 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
840 (D.getNumTypeObjects() == 1 &&
841 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
842 Diag(Decomp.getLSquareLoc(),
843 (D.hasGroupingParens() ||
844 (D.getNumTypeObjects() &&
845 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
846 ? diag::err_decomp_decl_parens
847 : diag::err_decomp_decl_type)
848 << R;
849
850 // In most cases, there's no actual problem with an explicitly-specified
851 // type, but a function type won't work here, and ActOnVariableDeclarator
852 // shouldn't be called for such a type.
853 if (R->isFunctionType())
854 D.setInvalidType();
855 }
856
857 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
858 if (DS.isConstrainedAuto()) {
859 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
860 assert(TemplRep->Kind == TNK_Concept_template &&(static_cast <bool> (TemplRep->Kind == TNK_Concept_template
&& "No other template kind should be possible for a constrained auto"
) ? void (0) : __assert_fail ("TemplRep->Kind == TNK_Concept_template && \"No other template kind should be possible for a constrained auto\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 861, __extension__ __PRETTY_FUNCTION__
))
861 "No other template kind should be possible for a constrained auto")(static_cast <bool> (TemplRep->Kind == TNK_Concept_template
&& "No other template kind should be possible for a constrained auto"
) ? void (0) : __assert_fail ("TemplRep->Kind == TNK_Concept_template && \"No other template kind should be possible for a constrained auto\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 861, __extension__ __PRETTY_FUNCTION__
))
;
862
863 SourceRange TemplRange{TemplRep->TemplateNameLoc,
864 TemplRep->RAngleLoc.isValid()
865 ? TemplRep->RAngleLoc
866 : TemplRep->TemplateNameLoc};
867 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
868 << TemplRange << FixItHint::CreateRemoval(TemplRange);
869 }
870
871 // Build the BindingDecls.
872 SmallVector<BindingDecl*, 8> Bindings;
873
874 // Build the BindingDecls.
875 for (auto &B : D.getDecompositionDeclarator().bindings()) {
876 // Check for name conflicts.
877 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
878 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
879 ForVisibleRedeclaration);
880 LookupName(Previous, S,
881 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
882
883 // It's not permitted to shadow a template parameter name.
884 if (Previous.isSingleResult() &&
885 Previous.getFoundDecl()->isTemplateParameter()) {
886 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
887 Previous.getFoundDecl());
888 Previous.clear();
889 }
890
891 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
892
893 // Find the shadowed declaration before filtering for scope.
894 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
895 ? getShadowedDeclaration(BD, Previous)
896 : nullptr;
897
898 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
899 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
900 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
901 /*AllowInlineNamespace*/false);
902
903 if (!Previous.empty()) {
904 auto *Old = Previous.getRepresentativeDecl();
905 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
906 Diag(Old->getLocation(), diag::note_previous_definition);
907 } else if (ShadowedDecl && !D.isRedeclaration()) {
908 CheckShadow(BD, ShadowedDecl, Previous);
909 }
910 PushOnScopeChains(BD, S, true);
911 Bindings.push_back(BD);
912 ParsingInitForAutoVars.insert(BD);
913 }
914
915 // There are no prior lookup results for the variable itself, because it
916 // is unnamed.
917 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
918 Decomp.getLSquareLoc());
919 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
920 ForVisibleRedeclaration);
921
922 // Build the variable that holds the non-decomposed object.
923 bool AddToScope = true;
924 NamedDecl *New =
925 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
926 MultiTemplateParamsArg(), AddToScope, Bindings);
927 if (AddToScope) {
928 S->AddDecl(New);
929 CurContext->addHiddenDecl(New);
930 }
931
932 if (isInOpenMPDeclareTargetContext())
933 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
934
935 return New;
936}
937
938static bool checkSimpleDecomposition(
939 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
940 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
941 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
942 if ((int64_t)Bindings.size() != NumElems) {
943 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
944 << DecompType << (unsigned)Bindings.size()
945 << (unsigned)NumElems.getLimitedValue(UINT_MAX(2147483647 *2U +1U))
946 << toString(NumElems, 10) << (NumElems < Bindings.size());
947 return true;
948 }
949
950 unsigned I = 0;
951 for (auto *B : Bindings) {
952 SourceLocation Loc = B->getLocation();
953 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
954 if (E.isInvalid())
955 return true;
956 E = GetInit(Loc, E.get(), I++);
957 if (E.isInvalid())
958 return true;
959 B->setBinding(ElemType, E.get());
960 }
961
962 return false;
963}
964
965static bool checkArrayLikeDecomposition(Sema &S,
966 ArrayRef<BindingDecl *> Bindings,
967 ValueDecl *Src, QualType DecompType,
968 const llvm::APSInt &NumElems,
969 QualType ElemType) {
970 return checkSimpleDecomposition(
971 S, Bindings, Src, DecompType, NumElems, ElemType,
972 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
973 ExprResult E = S.ActOnIntegerConstant(Loc, I);
974 if (E.isInvalid())
975 return ExprError();
976 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
977 });
978}
979
980static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
981 ValueDecl *Src, QualType DecompType,
982 const ConstantArrayType *CAT) {
983 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
984 llvm::APSInt(CAT->getSize()),
985 CAT->getElementType());
986}
987
988static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
989 ValueDecl *Src, QualType DecompType,
990 const VectorType *VT) {
991 return checkArrayLikeDecomposition(
992 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
993 S.Context.getQualifiedType(VT->getElementType(),
994 DecompType.getQualifiers()));
995}
996
997static bool checkComplexDecomposition(Sema &S,
998 ArrayRef<BindingDecl *> Bindings,
999 ValueDecl *Src, QualType DecompType,
1000 const ComplexType *CT) {
1001 return checkSimpleDecomposition(
1002 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1003 S.Context.getQualifiedType(CT->getElementType(),
1004 DecompType.getQualifiers()),
1005 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1006 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1007 });
1008}
1009
1010static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1011 TemplateArgumentListInfo &Args,
1012 const TemplateParameterList *Params) {
1013 SmallString<128> SS;
1014 llvm::raw_svector_ostream OS(SS);
1015 bool First = true;
1016 unsigned I = 0;
1017 for (auto &Arg : Args.arguments()) {
1018 if (!First)
1019 OS << ", ";
1020 Arg.getArgument().print(PrintingPolicy, OS,
1021 TemplateParameterList::shouldIncludeTypeForArgument(
1022 PrintingPolicy, Params, I));
1023 First = false;
1024 I++;
1025 }
1026 return std::string(OS.str());
1027}
1028
1029static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1030 SourceLocation Loc, StringRef Trait,
1031 TemplateArgumentListInfo &Args,
1032 unsigned DiagID) {
1033 auto DiagnoseMissing = [&] {
1034 if (DiagID)
1035 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1036 Args, /*Params*/ nullptr);
1037 return true;
1038 };
1039
1040 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1041 NamespaceDecl *Std = S.getStdNamespace();
1042 if (!Std)
1043 return DiagnoseMissing();
1044
1045 // Look up the trait itself, within namespace std. We can diagnose various
1046 // problems with this lookup even if we've been asked to not diagnose a
1047 // missing specialization, because this can only fail if the user has been
1048 // declaring their own names in namespace std or we don't support the
1049 // standard library implementation in use.
1050 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1051 Loc, Sema::LookupOrdinaryName);
1052 if (!S.LookupQualifiedName(Result, Std))
1053 return DiagnoseMissing();
1054 if (Result.isAmbiguous())
1055 return true;
1056
1057 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1058 if (!TraitTD) {
1059 Result.suppressDiagnostics();
1060 NamedDecl *Found = *Result.begin();
1061 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1062 S.Diag(Found->getLocation(), diag::note_declared_at);
1063 return true;
1064 }
1065
1066 // Build the template-id.
1067 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1068 if (TraitTy.isNull())
1069 return true;
1070 if (!S.isCompleteType(Loc, TraitTy)) {
1071 if (DiagID)
1072 S.RequireCompleteType(
1073 Loc, TraitTy, DiagID,
1074 printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1075 TraitTD->getTemplateParameters()));
1076 return true;
1077 }
1078
1079 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1080 assert(RD && "specialization of class template is not a class?")(static_cast <bool> (RD && "specialization of class template is not a class?"
) ? void (0) : __assert_fail ("RD && \"specialization of class template is not a class?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 1080, __extension__ __PRETTY_FUNCTION__
))
;
1081
1082 // Look up the member of the trait type.
1083 S.LookupQualifiedName(TraitMemberLookup, RD);
1084 return TraitMemberLookup.isAmbiguous();
1085}
1086
1087static TemplateArgumentLoc
1088getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1089 uint64_t I) {
1090 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1091 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1092}
1093
1094static TemplateArgumentLoc
1095getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1096 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1097}
1098
1099namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1100
1101static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1102 llvm::APSInt &Size) {
1103 EnterExpressionEvaluationContext ContextRAII(
1104 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1105
1106 DeclarationName Value = S.PP.getIdentifierInfo("value");
1107 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1108
1109 // Form template argument list for tuple_size<T>.
1110 TemplateArgumentListInfo Args(Loc, Loc);
1111 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1112
1113 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1114 // it's not tuple-like.
1115 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1116 R.empty())
1117 return IsTupleLike::NotTupleLike;
1118
1119 // If we get this far, we've committed to the tuple interpretation, but
1120 // we can still fail if there actually isn't a usable ::value.
1121
1122 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1123 LookupResult &R;
1124 TemplateArgumentListInfo &Args;
1125 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1126 : R(R), Args(Args) {}
1127 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1128 SourceLocation Loc) override {
1129 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1130 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1131 /*Params*/ nullptr);
1132 }
1133 } Diagnoser(R, Args);
1134
1135 ExprResult E =
1136 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1137 if (E.isInvalid())
1138 return IsTupleLike::Error;
1139
1140 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1141 if (E.isInvalid())
1142 return IsTupleLike::Error;
1143
1144 return IsTupleLike::TupleLike;
1145}
1146
1147/// \return std::tuple_element<I, T>::type.
1148static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1149 unsigned I, QualType T) {
1150 // Form template argument list for tuple_element<I, T>.
1151 TemplateArgumentListInfo Args(Loc, Loc);
1152 Args.addArgument(
1153 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1154 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1155
1156 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1157 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1158 if (lookupStdTypeTraitMember(
1159 S, R, Loc, "tuple_element", Args,
1160 diag::err_decomp_decl_std_tuple_element_not_specialized))
1161 return QualType();
1162
1163 auto *TD = R.getAsSingle<TypeDecl>();
1164 if (!TD) {
1165 R.suppressDiagnostics();
1166 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1167 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1168 /*Params*/ nullptr);
1169 if (!R.empty())
1170 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1171 return QualType();
1172 }
1173
1174 return S.Context.getTypeDeclType(TD);
1175}
1176
1177namespace {
1178struct InitializingBinding {
1179 Sema &S;
1180 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1181 Sema::CodeSynthesisContext Ctx;
1182 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1183 Ctx.PointOfInstantiation = BD->getLocation();
1184 Ctx.Entity = BD;
1185 S.pushCodeSynthesisContext(Ctx);
1186 }
1187 ~InitializingBinding() {
1188 S.popCodeSynthesisContext();
1189 }
1190};
1191}
1192
1193static bool checkTupleLikeDecomposition(Sema &S,
1194 ArrayRef<BindingDecl *> Bindings,
1195 VarDecl *Src, QualType DecompType,
1196 const llvm::APSInt &TupleSize) {
1197 if ((int64_t)Bindings.size() != TupleSize) {
1198 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1199 << DecompType << (unsigned)Bindings.size()
1200 << (unsigned)TupleSize.getLimitedValue(UINT_MAX(2147483647 *2U +1U))
1201 << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1202 return true;
1203 }
1204
1205 if (Bindings.empty())
1206 return false;
1207
1208 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1209
1210 // [dcl.decomp]p3:
1211 // The unqualified-id get is looked up in the scope of E by class member
1212 // access lookup ...
1213 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1214 bool UseMemberGet = false;
1215 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1216 if (auto *RD = DecompType->getAsCXXRecordDecl())
1217 S.LookupQualifiedName(MemberGet, RD);
1218 if (MemberGet.isAmbiguous())
1219 return true;
1220 // ... and if that finds at least one declaration that is a function
1221 // template whose first template parameter is a non-type parameter ...
1222 for (NamedDecl *D : MemberGet) {
1223 if (FunctionTemplateDecl *FTD =
1224 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1225 TemplateParameterList *TPL = FTD->getTemplateParameters();
1226 if (TPL->size() != 0 &&
1227 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1228 // ... the initializer is e.get<i>().
1229 UseMemberGet = true;
1230 break;
1231 }
1232 }
1233 }
1234 }
1235
1236 unsigned I = 0;
1237 for (auto *B : Bindings) {
1238 InitializingBinding InitContext(S, B);
1239 SourceLocation Loc = B->getLocation();
1240
1241 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1242 if (E.isInvalid())
1243 return true;
1244
1245 // e is an lvalue if the type of the entity is an lvalue reference and
1246 // an xvalue otherwise
1247 if (!Src->getType()->isLValueReferenceType())
1248 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1249 E.get(), nullptr, VK_XValue,
1250 FPOptionsOverride());
1251
1252 TemplateArgumentListInfo Args(Loc, Loc);
1253 Args.addArgument(
1254 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1255
1256 if (UseMemberGet) {
1257 // if [lookup of member get] finds at least one declaration, the
1258 // initializer is e.get<i-1>().
1259 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1260 CXXScopeSpec(), SourceLocation(), nullptr,
1261 MemberGet, &Args, nullptr);
1262 if (E.isInvalid())
1263 return true;
1264
1265 E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);
1266 } else {
1267 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1268 // in the associated namespaces.
1269 Expr *Get = UnresolvedLookupExpr::Create(
1270 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1271 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1272 UnresolvedSetIterator(), UnresolvedSetIterator());
1273
1274 Expr *Arg = E.get();
1275 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1276 }
1277 if (E.isInvalid())
1278 return true;
1279 Expr *Init = E.get();
1280
1281 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1282 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1283 if (T.isNull())
1284 return true;
1285
1286 // each vi is a variable of type "reference to T" initialized with the
1287 // initializer, where the reference is an lvalue reference if the
1288 // initializer is an lvalue and an rvalue reference otherwise
1289 QualType RefType =
1290 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1291 if (RefType.isNull())
1292 return true;
1293 auto *RefVD = VarDecl::Create(
1294 S.Context, Src->getDeclContext(), Loc, Loc,
1295 B->getDeclName().getAsIdentifierInfo(), RefType,
1296 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1297 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1298 RefVD->setTSCSpec(Src->getTSCSpec());
1299 RefVD->setImplicit();
1300 if (Src->isInlineSpecified())
1301 RefVD->setInlineSpecified();
1302 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1303
1304 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1305 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1306 InitializationSequence Seq(S, Entity, Kind, Init);
1307 E = Seq.Perform(S, Entity, Kind, Init);
1308 if (E.isInvalid())
1309 return true;
1310 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1311 if (E.isInvalid())
1312 return true;
1313 RefVD->setInit(E.get());
1314 S.CheckCompleteVariableDeclaration(RefVD);
1315
1316 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1317 DeclarationNameInfo(B->getDeclName(), Loc),
1318 RefVD);
1319 if (E.isInvalid())
1320 return true;
1321
1322 B->setBinding(T, E.get());
1323 I++;
1324 }
1325
1326 return false;
1327}
1328
1329/// Find the base class to decompose in a built-in decomposition of a class type.
1330/// This base class search is, unfortunately, not quite like any other that we
1331/// perform anywhere else in C++.
1332static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1333 const CXXRecordDecl *RD,
1334 CXXCastPath &BasePath) {
1335 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1336 CXXBasePath &Path) {
1337 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1338 };
1339
1340 const CXXRecordDecl *ClassWithFields = nullptr;
1341 AccessSpecifier AS = AS_public;
1342 if (RD->hasDirectFields())
1343 // [dcl.decomp]p4:
1344 // Otherwise, all of E's non-static data members shall be public direct
1345 // members of E ...
1346 ClassWithFields = RD;
1347 else {
1348 // ... or of ...
1349 CXXBasePaths Paths;
1350 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1351 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1352 // If no classes have fields, just decompose RD itself. (This will work
1353 // if and only if zero bindings were provided.)
1354 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1355 }
1356
1357 CXXBasePath *BestPath = nullptr;
1358 for (auto &P : Paths) {
1359 if (!BestPath)
1360 BestPath = &P;
1361 else if (!S.Context.hasSameType(P.back().Base->getType(),
1362 BestPath->back().Base->getType())) {
1363 // ... the same ...
1364 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1365 << false << RD << BestPath->back().Base->getType()
1366 << P.back().Base->getType();
1367 return DeclAccessPair();
1368 } else if (P.Access < BestPath->Access) {
1369 BestPath = &P;
1370 }
1371 }
1372
1373 // ... unambiguous ...
1374 QualType BaseType = BestPath->back().Base->getType();
1375 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1376 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1377 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1378 return DeclAccessPair();
1379 }
1380
1381 // ... [accessible, implied by other rules] base class of E.
1382 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1383 *BestPath, diag::err_decomp_decl_inaccessible_base);
1384 AS = BestPath->Access;
1385
1386 ClassWithFields = BaseType->getAsCXXRecordDecl();
1387 S.BuildBasePathArray(Paths, BasePath);
1388 }
1389
1390 // The above search did not check whether the selected class itself has base
1391 // classes with fields, so check that now.
1392 CXXBasePaths Paths;
1393 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1394 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1395 << (ClassWithFields == RD) << RD << ClassWithFields
1396 << Paths.front().back().Base->getType();
1397 return DeclAccessPair();
1398 }
1399
1400 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1401}
1402
1403static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1404 ValueDecl *Src, QualType DecompType,
1405 const CXXRecordDecl *OrigRD) {
1406 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1407 diag::err_incomplete_type))
1408 return true;
1409
1410 CXXCastPath BasePath;
1411 DeclAccessPair BasePair =
1412 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1413 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1414 if (!RD)
1415 return true;
1416 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1417 DecompType.getQualifiers());
1418
1419 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1420 unsigned NumFields = llvm::count_if(
1421 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1422 assert(Bindings.size() != NumFields)(static_cast <bool> (Bindings.size() != NumFields) ? void
(0) : __assert_fail ("Bindings.size() != NumFields", "clang/lib/Sema/SemaDeclCXX.cpp"
, 1422, __extension__ __PRETTY_FUNCTION__))
;
1423 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1424 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1425 << (NumFields < Bindings.size());
1426 return true;
1427 };
1428
1429 // all of E's non-static data members shall be [...] well-formed
1430 // when named as e.name in the context of the structured binding,
1431 // E shall not have an anonymous union member, ...
1432 unsigned I = 0;
1433 for (auto *FD : RD->fields()) {
1434 if (FD->isUnnamedBitfield())
1435 continue;
1436
1437 // All the non-static data members are required to be nameable, so they
1438 // must all have names.
1439 if (!FD->getDeclName()) {
1440 if (RD->isLambda()) {
1441 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1442 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1443 return true;
1444 }
1445
1446 if (FD->isAnonymousStructOrUnion()) {
1447 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1448 << DecompType << FD->getType()->isUnionType();
1449 S.Diag(FD->getLocation(), diag::note_declared_at);
1450 return true;
1451 }
1452
1453 // FIXME: Are there any other ways we could have an anonymous member?
1454 }
1455
1456 // We have a real field to bind.
1457 if (I >= Bindings.size())
1458 return DiagnoseBadNumberOfBindings();
1459 auto *B = Bindings[I++];
1460 SourceLocation Loc = B->getLocation();
1461
1462 // The field must be accessible in the context of the structured binding.
1463 // We already checked that the base class is accessible.
1464 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1465 // const_cast here.
1466 S.CheckStructuredBindingMemberAccess(
1467 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1468 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1469 BasePair.getAccess(), FD->getAccess())));
1470
1471 // Initialize the binding to Src.FD.
1472 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1473 if (E.isInvalid())
1474 return true;
1475 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1476 VK_LValue, &BasePath);
1477 if (E.isInvalid())
1478 return true;
1479 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1480 CXXScopeSpec(), FD,
1481 DeclAccessPair::make(FD, FD->getAccess()),
1482 DeclarationNameInfo(FD->getDeclName(), Loc));
1483 if (E.isInvalid())
1484 return true;
1485
1486 // If the type of the member is T, the referenced type is cv T, where cv is
1487 // the cv-qualification of the decomposition expression.
1488 //
1489 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1490 // 'const' to the type of the field.
1491 Qualifiers Q = DecompType.getQualifiers();
1492 if (FD->isMutable())
1493 Q.removeConst();
1494 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1495 }
1496
1497 if (I != Bindings.size())
1498 return DiagnoseBadNumberOfBindings();
1499
1500 return false;
1501}
1502
1503void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1504 QualType DecompType = DD->getType();
1505
1506 // If the type of the decomposition is dependent, then so is the type of
1507 // each binding.
1508 if (DecompType->isDependentType()) {
1509 for (auto *B : DD->bindings())
1510 B->setType(Context.DependentTy);
1511 return;
1512 }
1513
1514 DecompType = DecompType.getNonReferenceType();
1515 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1516
1517 // C++1z [dcl.decomp]/2:
1518 // If E is an array type [...]
1519 // As an extension, we also support decomposition of built-in complex and
1520 // vector types.
1521 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1522 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1523 DD->setInvalidDecl();
1524 return;
1525 }
1526 if (auto *VT = DecompType->getAs<VectorType>()) {
1527 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1528 DD->setInvalidDecl();
1529 return;
1530 }
1531 if (auto *CT = DecompType->getAs<ComplexType>()) {
1532 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1533 DD->setInvalidDecl();
1534 return;
1535 }
1536
1537 // C++1z [dcl.decomp]/3:
1538 // if the expression std::tuple_size<E>::value is a well-formed integral
1539 // constant expression, [...]
1540 llvm::APSInt TupleSize(32);
1541 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1542 case IsTupleLike::Error:
1543 DD->setInvalidDecl();
1544 return;
1545
1546 case IsTupleLike::TupleLike:
1547 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1548 DD->setInvalidDecl();
1549 return;
1550
1551 case IsTupleLike::NotTupleLike:
1552 break;
1553 }
1554
1555 // C++1z [dcl.dcl]/8:
1556 // [E shall be of array or non-union class type]
1557 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1558 if (!RD || RD->isUnion()) {
1559 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1560 << DD << !RD << DecompType;
1561 DD->setInvalidDecl();
1562 return;
1563 }
1564
1565 // C++1z [dcl.decomp]/4:
1566 // all of E's non-static data members shall be [...] direct members of
1567 // E or of the same unambiguous public base class of E, ...
1568 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1569 DD->setInvalidDecl();
1570}
1571
1572/// Merge the exception specifications of two variable declarations.
1573///
1574/// This is called when there's a redeclaration of a VarDecl. The function
1575/// checks if the redeclaration might have an exception specification and
1576/// validates compatibility and merges the specs if necessary.
1577void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1578 // Shortcut if exceptions are disabled.
1579 if (!getLangOpts().CXXExceptions)
1580 return;
1581
1582 assert(Context.hasSameType(New->getType(), Old->getType()) &&(static_cast <bool> (Context.hasSameType(New->getType
(), Old->getType()) && "Should only be called if types are otherwise the same."
) ? void (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 1583, __extension__ __PRETTY_FUNCTION__
))
1583 "Should only be called if types are otherwise the same.")(static_cast <bool> (Context.hasSameType(New->getType
(), Old->getType()) && "Should only be called if types are otherwise the same."
) ? void (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 1583, __extension__ __PRETTY_FUNCTION__
))
;
1584
1585 QualType NewType = New->getType();
1586 QualType OldType = Old->getType();
1587
1588 // We're only interested in pointers and references to functions, as well
1589 // as pointers to member functions.
1590 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1591 NewType = R->getPointeeType();
1592 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1593 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1594 NewType = P->getPointeeType();
1595 OldType = OldType->castAs<PointerType>()->getPointeeType();
1596 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1597 NewType = M->getPointeeType();
1598 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1599 }
1600
1601 if (!NewType->isFunctionProtoType())
1602 return;
1603
1604 // There's lots of special cases for functions. For function pointers, system
1605 // libraries are hopefully not as broken so that we don't need these
1606 // workarounds.
1607 if (CheckEquivalentExceptionSpec(
1608 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1609 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1610 New->setInvalidDecl();
1611 }
1612}
1613
1614/// CheckCXXDefaultArguments - Verify that the default arguments for a
1615/// function declaration are well-formed according to C++
1616/// [dcl.fct.default].
1617void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1618 unsigned NumParams = FD->getNumParams();
1619 unsigned ParamIdx = 0;
1620
1621 // This checking doesn't make sense for explicit specializations; their
1622 // default arguments are determined by the declaration we're specializing,
1623 // not by FD.
1624 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1625 return;
1626 if (auto *FTD = FD->getDescribedFunctionTemplate())
1627 if (FTD->isMemberSpecialization())
1628 return;
1629
1630 // Find first parameter with a default argument
1631 for (; ParamIdx < NumParams; ++ParamIdx) {
1632 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1633 if (Param->hasDefaultArg())
1634 break;
1635 }
1636
1637 // C++20 [dcl.fct.default]p4:
1638 // In a given function declaration, each parameter subsequent to a parameter
1639 // with a default argument shall have a default argument supplied in this or
1640 // a previous declaration, unless the parameter was expanded from a
1641 // parameter pack, or shall be a function parameter pack.
1642 for (; ParamIdx < NumParams; ++ParamIdx) {
1643 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1644 if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1645 !(CurrentInstantiationScope &&
1646 CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1647 if (Param->isInvalidDecl())
1648 /* We already complained about this parameter. */;
1649 else if (Param->getIdentifier())
1650 Diag(Param->getLocation(),
1651 diag::err_param_default_argument_missing_name)
1652 << Param->getIdentifier();
1653 else
1654 Diag(Param->getLocation(),
1655 diag::err_param_default_argument_missing);
1656 }
1657 }
1658}
1659
1660/// Check that the given type is a literal type. Issue a diagnostic if not,
1661/// if Kind is Diagnose.
1662/// \return \c true if a problem has been found (and optionally diagnosed).
1663template <typename... Ts>
1664static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1665 SourceLocation Loc, QualType T, unsigned DiagID,
1666 Ts &&...DiagArgs) {
1667 if (T->isDependentType())
1668 return false;
1669
1670 switch (Kind) {
1671 case Sema::CheckConstexprKind::Diagnose:
1672 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1673 std::forward<Ts>(DiagArgs)...);
1674
1675 case Sema::CheckConstexprKind::CheckValid:
1676 return !T->isLiteralType(SemaRef.Context);
1677 }
1678
1679 llvm_unreachable("unknown CheckConstexprKind")::llvm::llvm_unreachable_internal("unknown CheckConstexprKind"
, "clang/lib/Sema/SemaDeclCXX.cpp", 1679)
;
1680}
1681
1682/// Determine whether a destructor cannot be constexpr due to
1683static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1684 const CXXDestructorDecl *DD,
1685 Sema::CheckConstexprKind Kind) {
1686 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1687 const CXXRecordDecl *RD =
1688 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1689 if (!RD || RD->hasConstexprDestructor())
1690 return true;
1691
1692 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1693 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1694 << static_cast<int>(DD->getConstexprKind()) << !FD
1695 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1696 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1697 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1698 }
1699 return false;
1700 };
1701
1702 const CXXRecordDecl *RD = DD->getParent();
1703 for (const CXXBaseSpecifier &B : RD->bases())
1704 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1705 return false;
1706 for (const FieldDecl *FD : RD->fields())
1707 if (!Check(FD->getLocation(), FD->getType(), FD))
1708 return false;
1709 return true;
1710}
1711
1712/// Check whether a function's parameter types are all literal types. If so,
1713/// return true. If not, produce a suitable diagnostic and return false.
1714static bool CheckConstexprParameterTypes(Sema &SemaRef,
1715 const FunctionDecl *FD,
1716 Sema::CheckConstexprKind Kind) {
1717 unsigned ArgIndex = 0;
1718 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1719 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1720 e = FT->param_type_end();
1721 i != e; ++i, ++ArgIndex) {
1722 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1723 SourceLocation ParamLoc = PD->getLocation();
1724 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1725 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1726 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1727 FD->isConsteval()))
1728 return false;
1729 }
1730 return true;
1731}
1732
1733/// Check whether a function's return type is a literal type. If so, return
1734/// true. If not, produce a suitable diagnostic and return false.
1735static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1736 Sema::CheckConstexprKind Kind) {
1737 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1738 diag::err_constexpr_non_literal_return,
1739 FD->isConsteval()))
1740 return false;
1741 return true;
1742}
1743
1744/// Get diagnostic %select index for tag kind for
1745/// record diagnostic message.
1746/// WARNING: Indexes apply to particular diagnostics only!
1747///
1748/// \returns diagnostic %select index.
1749static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1750 switch (Tag) {
1751 case TTK_Struct: return 0;
1752 case TTK_Interface: return 1;
1753 case TTK_Class: return 2;
1754 default: llvm_unreachable("Invalid tag kind for record diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for record diagnostic!"
, "clang/lib/Sema/SemaDeclCXX.cpp", 1754)
;
1755 }
1756}
1757
1758static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1759 Stmt *Body,
1760 Sema::CheckConstexprKind Kind);
1761
1762// Check whether a function declaration satisfies the requirements of a
1763// constexpr function definition or a constexpr constructor definition. If so,
1764// return true. If not, produce appropriate diagnostics (unless asked not to by
1765// Kind) and return false.
1766//
1767// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1768bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1769 CheckConstexprKind Kind) {
1770 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1771 if (MD && MD->isInstance()) {
1772 // C++11 [dcl.constexpr]p4:
1773 // The definition of a constexpr constructor shall satisfy the following
1774 // constraints:
1775 // - the class shall not have any virtual base classes;
1776 //
1777 // FIXME: This only applies to constructors and destructors, not arbitrary
1778 // member functions.
1779 const CXXRecordDecl *RD = MD->getParent();
1780 if (RD->getNumVBases()) {
1781 if (Kind == CheckConstexprKind::CheckValid)
1782 return false;
1783
1784 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1785 << isa<CXXConstructorDecl>(NewFD)
1786 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1787 for (const auto &I : RD->vbases())
1788 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1789 << I.getSourceRange();
1790 return false;
1791 }
1792 }
1793
1794 if (!isa<CXXConstructorDecl>(NewFD)) {
1795 // C++11 [dcl.constexpr]p3:
1796 // The definition of a constexpr function shall satisfy the following
1797 // constraints:
1798 // - it shall not be virtual; (removed in C++20)
1799 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1800 if (Method && Method->isVirtual()) {
1801 if (getLangOpts().CPlusPlus20) {
1802 if (Kind == CheckConstexprKind::Diagnose)
1803 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1804 } else {
1805 if (Kind == CheckConstexprKind::CheckValid)
1806 return false;
1807
1808 Method = Method->getCanonicalDecl();
1809 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1810
1811 // If it's not obvious why this function is virtual, find an overridden
1812 // function which uses the 'virtual' keyword.
1813 const CXXMethodDecl *WrittenVirtual = Method;
1814 while (!WrittenVirtual->isVirtualAsWritten())
1815 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1816 if (WrittenVirtual != Method)
1817 Diag(WrittenVirtual->getLocation(),
1818 diag::note_overridden_virtual_function);
1819 return false;
1820 }
1821 }
1822
1823 // - its return type shall be a literal type;
1824 if (!CheckConstexprReturnType(*this, NewFD, Kind))
1825 return false;
1826 }
1827
1828 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1829 // A destructor can be constexpr only if the defaulted destructor could be;
1830 // we don't need to check the members and bases if we already know they all
1831 // have constexpr destructors.
1832 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1833 if (Kind == CheckConstexprKind::CheckValid)
1834 return false;
1835 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1836 return false;
1837 }
1838 }
1839
1840 // - each of its parameter types shall be a literal type;
1841 if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1842 return false;
1843
1844 Stmt *Body = NewFD->getBody();
1845 assert(Body &&(static_cast <bool> (Body && "CheckConstexprFunctionDefinition called on function with no body"
) ? void (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 1846, __extension__ __PRETTY_FUNCTION__
))
1846 "CheckConstexprFunctionDefinition called on function with no body")(static_cast <bool> (Body && "CheckConstexprFunctionDefinition called on function with no body"
) ? void (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 1846, __extension__ __PRETTY_FUNCTION__
))
;
1847 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1848}
1849
1850/// Check the given declaration statement is legal within a constexpr function
1851/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1852///
1853/// \return true if the body is OK (maybe only as an extension), false if we
1854/// have diagnosed a problem.
1855static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1856 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1857 Sema::CheckConstexprKind Kind) {
1858 // C++11 [dcl.constexpr]p3 and p4:
1859 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1860 // contain only
1861 for (const auto *DclIt : DS->decls()) {
1862 switch (DclIt->getKind()) {
1863 case Decl::StaticAssert:
1864 case Decl::Using:
1865 case Decl::UsingShadow:
1866 case Decl::UsingDirective:
1867 case Decl::UnresolvedUsingTypename:
1868 case Decl::UnresolvedUsingValue:
1869 case Decl::UsingEnum:
1870 // - static_assert-declarations
1871 // - using-declarations,
1872 // - using-directives,
1873 // - using-enum-declaration
1874 continue;
1875
1876 case Decl::Typedef:
1877 case Decl::TypeAlias: {
1878 // - typedef declarations and alias-declarations that do not define
1879 // classes or enumerations,
1880 const auto *TN = cast<TypedefNameDecl>(DclIt);
1881 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1882 // Don't allow variably-modified types in constexpr functions.
1883 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1884 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1885 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1886 << TL.getSourceRange() << TL.getType()
1887 << isa<CXXConstructorDecl>(Dcl);
1888 }
1889 return false;
1890 }
1891 continue;
1892 }
1893
1894 case Decl::Enum:
1895 case Decl::CXXRecord:
1896 // C++1y allows types to be defined, not just declared.
1897 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1898 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1899 SemaRef.Diag(DS->getBeginLoc(),
1900 SemaRef.getLangOpts().CPlusPlus14
1901 ? diag::warn_cxx11_compat_constexpr_type_definition
1902 : diag::ext_constexpr_type_definition)
1903 << isa<CXXConstructorDecl>(Dcl);
1904 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1905 return false;
1906 }
1907 }
1908 continue;
1909
1910 case Decl::EnumConstant:
1911 case Decl::IndirectField:
1912 case Decl::ParmVar:
1913 // These can only appear with other declarations which are banned in
1914 // C++11 and permitted in C++1y, so ignore them.
1915 continue;
1916
1917 case Decl::Var:
1918 case Decl::Decomposition: {
1919 // C++1y [dcl.constexpr]p3 allows anything except:
1920 // a definition of a variable of non-literal type or of static or
1921 // thread storage duration or [before C++2a] for which no
1922 // initialization is performed.
1923 const auto *VD = cast<VarDecl>(DclIt);
1924 if (VD->isThisDeclarationADefinition()) {
1925 if (VD->isStaticLocal()) {
1926 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1927 SemaRef.Diag(VD->getLocation(),
1928 SemaRef.getLangOpts().CPlusPlus2b
1929 ? diag::warn_cxx20_compat_constexpr_var
1930 : diag::ext_constexpr_static_var)
1931 << isa<CXXConstructorDecl>(Dcl)
1932 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1933 } else if (!SemaRef.getLangOpts().CPlusPlus2b) {
1934 return false;
1935 }
1936 }
1937 if (SemaRef.LangOpts.CPlusPlus2b) {
1938 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1939 diag::warn_cxx20_compat_constexpr_var,
1940 isa<CXXConstructorDecl>(Dcl),
1941 /*variable of non-literal type*/ 2);
1942 } else if (CheckLiteralType(
1943 SemaRef, Kind, VD->getLocation(), VD->getType(),
1944 diag::err_constexpr_local_var_non_literal_type,
1945 isa<CXXConstructorDecl>(Dcl))) {
1946 return false;
1947 }
1948 if (!VD->getType()->isDependentType() &&
1949 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1950 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1951 SemaRef.Diag(
1952 VD->getLocation(),
1953 SemaRef.getLangOpts().CPlusPlus20
1954 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1955 : diag::ext_constexpr_local_var_no_init)
1956 << isa<CXXConstructorDecl>(Dcl);
1957 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1958 return false;
1959 }
1960 continue;
1961 }
1962 }
1963 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1964 SemaRef.Diag(VD->getLocation(),
1965 SemaRef.getLangOpts().CPlusPlus14
1966 ? diag::warn_cxx11_compat_constexpr_local_var
1967 : diag::ext_constexpr_local_var)
1968 << isa<CXXConstructorDecl>(Dcl);
1969 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1970 return false;
1971 }
1972 continue;
1973 }
1974
1975 case Decl::NamespaceAlias:
1976 case Decl::Function:
1977 // These are disallowed in C++11 and permitted in C++1y. Allow them
1978 // everywhere as an extension.
1979 if (!Cxx1yLoc.isValid())
1980 Cxx1yLoc = DS->getBeginLoc();
1981 continue;
1982
1983 default:
1984 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1985 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1986 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1987 }
1988 return false;
1989 }
1990 }
1991
1992 return true;
1993}
1994
1995/// Check that the given field is initialized within a constexpr constructor.
1996///
1997/// \param Dcl The constexpr constructor being checked.
1998/// \param Field The field being checked. This may be a member of an anonymous
1999/// struct or union nested within the class being checked.
2000/// \param Inits All declarations, including anonymous struct/union members and
2001/// indirect members, for which any initialization was provided.
2002/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2003/// multiple notes for different members to the same error.
2004/// \param Kind Whether we're diagnosing a constructor as written or determining
2005/// whether the formal requirements are satisfied.
2006/// \return \c false if we're checking for validity and the constructor does
2007/// not satisfy the requirements on a constexpr constructor.
2008static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2009 const FunctionDecl *Dcl,
2010 FieldDecl *Field,
2011 llvm::SmallSet<Decl*, 16> &Inits,
2012 bool &Diagnosed,
2013 Sema::CheckConstexprKind Kind) {
2014 // In C++20 onwards, there's nothing to check for validity.
2015 if (Kind == Sema::CheckConstexprKind::CheckValid &&
2016 SemaRef.getLangOpts().CPlusPlus20)
2017 return true;
2018
2019 if (Field->isInvalidDecl())
2020 return true;
2021
2022 if (Field->isUnnamedBitfield())
2023 return true;
2024
2025 // Anonymous unions with no variant members and empty anonymous structs do not
2026 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2027 // indirect fields don't need initializing.
2028 if (Field->isAnonymousStructOrUnion() &&
2029 (Field->getType()->isUnionType()
2030 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2031 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2032 return true;
2033
2034 if (!Inits.count(Field)) {
2035 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2036 if (!Diagnosed) {
2037 SemaRef.Diag(Dcl->getLocation(),
2038 SemaRef.getLangOpts().CPlusPlus20
2039 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2040 : diag::ext_constexpr_ctor_missing_init);
2041 Diagnosed = true;
2042 }
2043 SemaRef.Diag(Field->getLocation(),
2044 diag::note_constexpr_ctor_missing_init);
2045 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2046 return false;
2047 }
2048 } else if (Field->isAnonymousStructOrUnion()) {
2049 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2050 for (auto *I : RD->fields())
2051 // If an anonymous union contains an anonymous struct of which any member
2052 // is initialized, all members must be initialized.
2053 if (!RD->isUnion() || Inits.count(I))
2054 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2055 Kind))
2056 return false;
2057 }
2058 return true;
2059}
2060
2061/// Check the provided statement is allowed in a constexpr function
2062/// definition.
2063static bool
2064CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2065 SmallVectorImpl<SourceLocation> &ReturnStmts,
2066 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2067 SourceLocation &Cxx2bLoc,
2068 Sema::CheckConstexprKind Kind) {
2069 // - its function-body shall be [...] a compound-statement that contains only
2070 switch (S->getStmtClass()) {
2071 case Stmt::NullStmtClass:
2072 // - null statements,
2073 return true;
2074
2075 case Stmt::DeclStmtClass:
2076 // - static_assert-declarations
2077 // - using-declarations,
2078 // - using-directives,
2079 // - typedef declarations and alias-declarations that do not define
2080 // classes or enumerations,
2081 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2082 return false;
2083 return true;
2084
2085 case Stmt::ReturnStmtClass:
2086 // - and exactly one return statement;
2087 if (isa<CXXConstructorDecl>(Dcl)) {
2088 // C++1y allows return statements in constexpr constructors.
2089 if (!Cxx1yLoc.isValid())
2090 Cxx1yLoc = S->getBeginLoc();
2091 return true;
2092 }
2093
2094 ReturnStmts.push_back(S->getBeginLoc());
2095 return true;
2096
2097 case Stmt::AttributedStmtClass:
2098 // Attributes on a statement don't affect its formal kind and hence don't
2099 // affect its validity in a constexpr function.
2100 return CheckConstexprFunctionStmt(
2101 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2102 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2103
2104 case Stmt::CompoundStmtClass: {
2105 // C++1y allows compound-statements.
2106 if (!Cxx1yLoc.isValid())
2107 Cxx1yLoc = S->getBeginLoc();
2108
2109 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2110 for (auto *BodyIt : CompStmt->body()) {
2111 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2112 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2113 return false;
2114 }
2115 return true;
2116 }
2117
2118 case Stmt::IfStmtClass: {
2119 // C++1y allows if-statements.
2120 if (!Cxx1yLoc.isValid())
2121 Cxx1yLoc = S->getBeginLoc();
2122
2123 IfStmt *If = cast<IfStmt>(S);
2124 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2125 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2126 return false;
2127 if (If->getElse() &&
2128 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2129 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2130 return false;
2131 return true;
2132 }
2133
2134 case Stmt::WhileStmtClass:
2135 case Stmt::DoStmtClass:
2136 case Stmt::ForStmtClass:
2137 case Stmt::CXXForRangeStmtClass:
2138 case Stmt::ContinueStmtClass:
2139 // C++1y allows all of these. We don't allow them as extensions in C++11,
2140 // because they don't make sense without variable mutation.
2141 if (!SemaRef.getLangOpts().CPlusPlus14)
2142 break;
2143 if (!Cxx1yLoc.isValid())
2144 Cxx1yLoc = S->getBeginLoc();
2145 for (Stmt *SubStmt : S->children()) {
2146 if (SubStmt &&
2147 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2148 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2149 return false;
2150 }
2151 return true;
2152
2153 case Stmt::SwitchStmtClass:
2154 case Stmt::CaseStmtClass:
2155 case Stmt::DefaultStmtClass:
2156 case Stmt::BreakStmtClass:
2157 // C++1y allows switch-statements, and since they don't need variable
2158 // mutation, we can reasonably allow them in C++11 as an extension.
2159 if (!Cxx1yLoc.isValid())
2160 Cxx1yLoc = S->getBeginLoc();
2161 for (Stmt *SubStmt : S->children()) {
2162 if (SubStmt &&
2163 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2164 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2165 return false;
2166 }
2167 return true;
2168
2169 case Stmt::LabelStmtClass:
2170 case Stmt::GotoStmtClass:
2171 if (Cxx2bLoc.isInvalid())
2172 Cxx2bLoc = S->getBeginLoc();
2173 for (Stmt *SubStmt : S->children()) {
2174 if (SubStmt &&
2175 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2176 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2177 return false;
2178 }
2179 return true;
2180
2181 case Stmt::GCCAsmStmtClass:
2182 case Stmt::MSAsmStmtClass:
2183 // C++2a allows inline assembly statements.
2184 case Stmt::CXXTryStmtClass:
2185 if (Cxx2aLoc.isInvalid())
2186 Cxx2aLoc = S->getBeginLoc();
2187 for (Stmt *SubStmt : S->children()) {
2188 if (SubStmt &&
2189 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2190 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2191 return false;
2192 }
2193 return true;
2194
2195 case Stmt::CXXCatchStmtClass:
2196 // Do not bother checking the language mode (already covered by the
2197 // try block check).
2198 if (!CheckConstexprFunctionStmt(
2199 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2200 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2201 return false;
2202 return true;
2203
2204 default:
2205 if (!isa<Expr>(S))
2206 break;
2207
2208 // C++1y allows expression-statements.
2209 if (!Cxx1yLoc.isValid())
2210 Cxx1yLoc = S->getBeginLoc();
2211 return true;
2212 }
2213
2214 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2215 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2216 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2217 }
2218 return false;
2219}
2220
2221/// Check the body for the given constexpr function declaration only contains
2222/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2223///
2224/// \return true if the body is OK, false if we have found or diagnosed a
2225/// problem.
2226static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2227 Stmt *Body,
2228 Sema::CheckConstexprKind Kind) {
2229 SmallVector<SourceLocation, 4> ReturnStmts;
2230
2231 if (isa<CXXTryStmt>(Body)) {
2232 // C++11 [dcl.constexpr]p3:
2233 // The definition of a constexpr function shall satisfy the following
2234 // constraints: [...]
2235 // - its function-body shall be = delete, = default, or a
2236 // compound-statement
2237 //
2238 // C++11 [dcl.constexpr]p4:
2239 // In the definition of a constexpr constructor, [...]
2240 // - its function-body shall not be a function-try-block;
2241 //
2242 // This restriction is lifted in C++2a, as long as inner statements also
2243 // apply the general constexpr rules.
2244 switch (Kind) {
2245 case Sema::CheckConstexprKind::CheckValid:
2246 if (!SemaRef.getLangOpts().CPlusPlus20)
2247 return false;
2248 break;
2249
2250 case Sema::CheckConstexprKind::Diagnose:
2251 SemaRef.Diag(Body->getBeginLoc(),
2252 !SemaRef.getLangOpts().CPlusPlus20
2253 ? diag::ext_constexpr_function_try_block_cxx20
2254 : diag::warn_cxx17_compat_constexpr_function_try_block)
2255 << isa<CXXConstructorDecl>(Dcl);
2256 break;
2257 }
2258 }
2259
2260 // - its function-body shall be [...] a compound-statement that contains only
2261 // [... list of cases ...]
2262 //
2263 // Note that walking the children here is enough to properly check for
2264 // CompoundStmt and CXXTryStmt body.
2265 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2266 for (Stmt *SubStmt : Body->children()) {
2267 if (SubStmt &&
2268 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2269 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2270 return false;
2271 }
2272
2273 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2274 // If this is only valid as an extension, report that we don't satisfy the
2275 // constraints of the current language.
2276 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2b) ||
2277 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2278 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2279 return false;
2280 } else if (Cxx2bLoc.isValid()) {
2281 SemaRef.Diag(Cxx2bLoc,
2282 SemaRef.getLangOpts().CPlusPlus2b
2283 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2284 : diag::ext_constexpr_body_invalid_stmt_cxx2b)
2285 << isa<CXXConstructorDecl>(Dcl);
2286 } else if (Cxx2aLoc.isValid()) {
2287 SemaRef.Diag(Cxx2aLoc,
2288 SemaRef.getLangOpts().CPlusPlus20
2289 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2290 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2291 << isa<CXXConstructorDecl>(Dcl);
2292 } else if (Cxx1yLoc.isValid()) {
2293 SemaRef.Diag(Cxx1yLoc,
2294 SemaRef.getLangOpts().CPlusPlus14
2295 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2296 : diag::ext_constexpr_body_invalid_stmt)
2297 << isa<CXXConstructorDecl>(Dcl);
2298 }
2299
2300 if (const CXXConstructorDecl *Constructor
2301 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2302 const CXXRecordDecl *RD = Constructor->getParent();
2303 // DR1359:
2304 // - every non-variant non-static data member and base class sub-object
2305 // shall be initialized;
2306 // DR1460:
2307 // - if the class is a union having variant members, exactly one of them
2308 // shall be initialized;
2309 if (RD->isUnion()) {
2310 if (Constructor->getNumCtorInitializers() == 0 &&
2311 RD->hasVariantMembers()) {
2312 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2313 SemaRef.Diag(
2314 Dcl->getLocation(),
2315 SemaRef.getLangOpts().CPlusPlus20
2316 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2317 : diag::ext_constexpr_union_ctor_no_init);
2318 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2319 return false;
2320 }
2321 }
2322 } else if (!Constructor->isDependentContext() &&
2323 !Constructor->isDelegatingConstructor()) {
2324 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases")(static_cast <bool> (RD->getNumVBases() == 0 &&
"constexpr ctor with virtual bases") ? void (0) : __assert_fail
("RD->getNumVBases() == 0 && \"constexpr ctor with virtual bases\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 2324, __extension__ __PRETTY_FUNCTION__
))
;
2325
2326 // Skip detailed checking if we have enough initializers, and we would
2327 // allow at most one initializer per member.
2328 bool AnyAnonStructUnionMembers = false;
2329 unsigned Fields = 0;
2330 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2331 E = RD->field_end(); I != E; ++I, ++Fields) {
2332 if (I->isAnonymousStructOrUnion()) {
2333 AnyAnonStructUnionMembers = true;
2334 break;
2335 }
2336 }
2337 // DR1460:
2338 // - if the class is a union-like class, but is not a union, for each of
2339 // its anonymous union members having variant members, exactly one of
2340 // them shall be initialized;
2341 if (AnyAnonStructUnionMembers ||
2342 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2343 // Check initialization of non-static data members. Base classes are
2344 // always initialized so do not need to be checked. Dependent bases
2345 // might not have initializers in the member initializer list.
2346 llvm::SmallSet<Decl*, 16> Inits;
2347 for (const auto *I: Constructor->inits()) {
2348 if (FieldDecl *FD = I->getMember())
2349 Inits.insert(FD);
2350 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2351 Inits.insert(ID->chain_begin(), ID->chain_end());
2352 }
2353
2354 bool Diagnosed = false;
2355 for (auto *I : RD->fields())
2356 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2357 Kind))
2358 return false;
2359 }
2360 }
2361 } else {
2362 if (ReturnStmts.empty()) {
2363 // C++1y doesn't require constexpr functions to contain a 'return'
2364 // statement. We still do, unless the return type might be void, because
2365 // otherwise if there's no return statement, the function cannot
2366 // be used in a core constant expression.
2367 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2368 (Dcl->getReturnType()->isVoidType() ||
2369 Dcl->getReturnType()->isDependentType());
2370 switch (Kind) {
2371 case Sema::CheckConstexprKind::Diagnose:
2372 SemaRef.Diag(Dcl->getLocation(),
2373 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2374 : diag::err_constexpr_body_no_return)
2375 << Dcl->isConsteval();
2376 if (!OK)
2377 return false;
2378 break;
2379
2380 case Sema::CheckConstexprKind::CheckValid:
2381 // The formal requirements don't include this rule in C++14, even
2382 // though the "must be able to produce a constant expression" rules
2383 // still imply it in some cases.
2384 if (!SemaRef.getLangOpts().CPlusPlus14)
2385 return false;
2386 break;
2387 }
2388 } else if (ReturnStmts.size() > 1) {
2389 switch (Kind) {
2390 case Sema::CheckConstexprKind::Diagnose:
2391 SemaRef.Diag(
2392 ReturnStmts.back(),
2393 SemaRef.getLangOpts().CPlusPlus14
2394 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2395 : diag::ext_constexpr_body_multiple_return);
2396 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2397 SemaRef.Diag(ReturnStmts[I],
2398 diag::note_constexpr_body_previous_return);
2399 break;
2400
2401 case Sema::CheckConstexprKind::CheckValid:
2402 if (!SemaRef.getLangOpts().CPlusPlus14)
2403 return false;
2404 break;
2405 }
2406 }
2407 }
2408
2409 // C++11 [dcl.constexpr]p5:
2410 // if no function argument values exist such that the function invocation
2411 // substitution would produce a constant expression, the program is
2412 // ill-formed; no diagnostic required.
2413 // C++11 [dcl.constexpr]p3:
2414 // - every constructor call and implicit conversion used in initializing the
2415 // return value shall be one of those allowed in a constant expression.
2416 // C++11 [dcl.constexpr]p4:
2417 // - every constructor involved in initializing non-static data members and
2418 // base class sub-objects shall be a constexpr constructor.
2419 //
2420 // Note that this rule is distinct from the "requirements for a constexpr
2421 // function", so is not checked in CheckValid mode.
2422 SmallVector<PartialDiagnosticAt, 8> Diags;
2423 if (Kind == Sema::CheckConstexprKind::Diagnose &&
2424 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2425 SemaRef.Diag(Dcl->getLocation(),
2426 diag::ext_constexpr_function_never_constant_expr)
2427 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2428 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2429 SemaRef.Diag(Diags[I].first, Diags[I].second);
2430 // Don't return false here: we allow this for compatibility in
2431 // system headers.
2432 }
2433
2434 return true;
2435}
2436
2437/// Get the class that is directly named by the current context. This is the
2438/// class for which an unqualified-id in this scope could name a constructor
2439/// or destructor.
2440///
2441/// If the scope specifier denotes a class, this will be that class.
2442/// If the scope specifier is empty, this will be the class whose
2443/// member-specification we are currently within. Otherwise, there
2444/// is no such class.
2445CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2446 assert(getLangOpts().CPlusPlus && "No class names in C!")(static_cast <bool> (getLangOpts().CPlusPlus &&
"No class names in C!") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 2446, __extension__ __PRETTY_FUNCTION__
))
;
2447
2448 if (SS && SS->isInvalid())
2449 return nullptr;
2450
2451 if (SS && SS->isNotEmpty()) {
2452 DeclContext *DC = computeDeclContext(*SS, true);
2453 return dyn_cast_or_null<CXXRecordDecl>(DC);
2454 }
2455
2456 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2457}
2458
2459/// isCurrentClassName - Determine whether the identifier II is the
2460/// name of the class type currently being defined. In the case of
2461/// nested classes, this will only return true if II is the name of
2462/// the innermost class.
2463bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2464 const CXXScopeSpec *SS) {
2465 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2466 return CurDecl && &II == CurDecl->getIdentifier();
2467}
2468
2469/// Determine whether the identifier II is a typo for the name of
2470/// the class type currently being defined. If so, update it to the identifier
2471/// that should have been used.
2472bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2473 assert(getLangOpts().CPlusPlus && "No class names in C!")(static_cast <bool> (getLangOpts().CPlusPlus &&
"No class names in C!") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 2473, __extension__ __PRETTY_FUNCTION__
))
;
2474
2475 if (!getLangOpts().SpellChecking)
2476 return false;
2477
2478 CXXRecordDecl *CurDecl;
2479 if (SS && SS->isSet() && !SS->isInvalid()) {
2480 DeclContext *DC = computeDeclContext(*SS, true);
2481 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2482 } else
2483 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2484
2485 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2486 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2487 < II->getLength()) {
2488 II = CurDecl->getIdentifier();
2489 return true;
2490 }
2491
2492 return false;
2493}
2494
2495/// Determine whether the given class is a base class of the given
2496/// class, including looking at dependent bases.
2497static bool findCircularInheritance(const CXXRecordDecl *Class,
2498 const CXXRecordDecl *Current) {
2499 SmallVector<const CXXRecordDecl*, 8> Queue;
2500
2501 Class = Class->getCanonicalDecl();
2502 while (true) {
2503 for (const auto &I : Current->bases()) {
2504 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2505 if (!Base)
2506 continue;
2507
2508 Base = Base->getDefinition();
2509 if (!Base)
2510 continue;
2511
2512 if (Base->getCanonicalDecl() == Class)
2513 return true;
2514
2515 Queue.push_back(Base);
2516 }
2517
2518 if (Queue.empty())
2519 return false;
2520
2521 Current = Queue.pop_back_val();
2522 }
2523
2524 return false;
2525}
2526
2527/// Check the validity of a C++ base class specifier.
2528///
2529/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2530/// and returns NULL otherwise.
2531CXXBaseSpecifier *
2532Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2533 SourceRange SpecifierRange,
2534 bool Virtual, AccessSpecifier Access,
2535 TypeSourceInfo *TInfo,
2536 SourceLocation EllipsisLoc) {
2537 // In HLSL, unspecified class access is public rather than private.
2538 if (getLangOpts().HLSL && Class->getTagKind() == TTK_Class &&
2539 Access == AS_none)
2540 Access = AS_public;
2541
2542 QualType BaseType = TInfo->getType();
2543 if (BaseType->containsErrors()) {
2544 // Already emitted a diagnostic when parsing the error type.
2545 return nullptr;
2546 }
2547 // C++ [class.union]p1:
2548 // A union shall not have base classes.
2549 if (Class->isUnion()) {
2550 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2551 << SpecifierRange;
2552 return nullptr;
2553 }
2554
2555 if (EllipsisLoc.isValid() &&
2556 !TInfo->getType()->containsUnexpandedParameterPack()) {
2557 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2558 << TInfo->getTypeLoc().getSourceRange();
2559 EllipsisLoc = SourceLocation();
2560 }
2561
2562 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2563
2564 if (BaseType->isDependentType()) {
2565 // Make sure that we don't have circular inheritance among our dependent
2566 // bases. For non-dependent bases, the check for completeness below handles
2567 // this.
2568 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2569 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2570 ((BaseDecl = BaseDecl->getDefinition()) &&
2571 findCircularInheritance(Class, BaseDecl))) {
2572 Diag(BaseLoc, diag::err_circular_inheritance)
2573 << BaseType << Context.getTypeDeclType(Class);
2574
2575 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2576 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2577 << BaseType;
2578
2579 return nullptr;
2580 }
2581 }
2582
2583 // Make sure that we don't make an ill-formed AST where the type of the
2584 // Class is non-dependent and its attached base class specifier is an
2585 // dependent type, which violates invariants in many clang code paths (e.g.
2586 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2587 // explicitly mark the Class decl invalid. The diagnostic was already
2588 // emitted.
2589 if (!Class->getTypeForDecl()->isDependentType())
2590 Class->setInvalidDecl();
2591 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2592 Class->getTagKind() == TTK_Class,
2593 Access, TInfo, EllipsisLoc);
2594 }
2595
2596 // Base specifiers must be record types.
2597 if (!BaseType->isRecordType()) {
2598 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2599 return nullptr;
2600 }
2601
2602 // C++ [class.union]p1:
2603 // A union shall not be used as a base class.
2604 if (BaseType->isUnionType()) {
2605 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2606 return nullptr;
2607 }
2608
2609 // For the MS ABI, propagate DLL attributes to base class templates.
2610 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2611 if (Attr *ClassAttr = getDLLAttr(Class)) {
2612 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2613 BaseType->getAsCXXRecordDecl())) {
2614 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2615 BaseLoc);
2616 }
2617 }
2618 }
2619
2620 // C++ [class.derived]p2:
2621 // The class-name in a base-specifier shall not be an incompletely
2622 // defined class.
2623 if (RequireCompleteType(BaseLoc, BaseType,
2624 diag::err_incomplete_base_class, SpecifierRange)) {
2625 Class->setInvalidDecl();
2626 return nullptr;
2627 }
2628
2629 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2630 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2631 assert(BaseDecl && "Record type has no declaration")(static_cast <bool> (BaseDecl && "Record type has no declaration"
) ? void (0) : __assert_fail ("BaseDecl && \"Record type has no declaration\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 2631, __extension__ __PRETTY_FUNCTION__
))
;
2632 BaseDecl = BaseDecl->getDefinition();
2633 assert(BaseDecl && "Base type is not incomplete, but has no definition")(static_cast <bool> (BaseDecl && "Base type is not incomplete, but has no definition"
) ? void (0) : __assert_fail ("BaseDecl && \"Base type is not incomplete, but has no definition\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 2633, __extension__ __PRETTY_FUNCTION__
))
;
2634 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2635 assert(CXXBaseDecl && "Base type is not a C++ type")(static_cast <bool> (CXXBaseDecl && "Base type is not a C++ type"
) ? void (0) : __assert_fail ("CXXBaseDecl && \"Base type is not a C++ type\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 2635, __extension__ __PRETTY_FUNCTION__
))
;
2636
2637 // Microsoft docs say:
2638 // "If a base-class has a code_seg attribute, derived classes must have the
2639 // same attribute."
2640 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2641 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2642 if ((DerivedCSA || BaseCSA) &&
2643 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2644 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2645 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2646 << CXXBaseDecl;
2647 return nullptr;
2648 }
2649
2650 // A class which contains a flexible array member is not suitable for use as a
2651 // base class:
2652 // - If the layout determines that a base comes before another base,
2653 // the flexible array member would index into the subsequent base.
2654 // - If the layout determines that base comes before the derived class,
2655 // the flexible array member would index into the derived class.
2656 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2657 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2658 << CXXBaseDecl->getDeclName();
2659 return nullptr;
2660 }
2661
2662 // C++ [class]p3:
2663 // If a class is marked final and it appears as a base-type-specifier in
2664 // base-clause, the program is ill-formed.
2665 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2666 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2667 << CXXBaseDecl->getDeclName()
2668 << FA->isSpelledAsSealed();
2669 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2670 << CXXBaseDecl->getDeclName() << FA->getRange();
2671 return nullptr;
2672 }
2673
2674 if (BaseDecl->isInvalidDecl())
2675 Class->setInvalidDecl();
2676
2677 // Create the base specifier.
2678 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2679 Class->getTagKind() == TTK_Class,
2680 Access, TInfo, EllipsisLoc);
2681}
2682
2683/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2684/// one entry in the base class list of a class specifier, for
2685/// example:
2686/// class foo : public bar, virtual private baz {
2687/// 'public bar' and 'virtual private baz' are each base-specifiers.
2688BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2689 const ParsedAttributesView &Attributes,
2690 bool Virtual, AccessSpecifier Access,
2691 ParsedType basetype, SourceLocation BaseLoc,
2692 SourceLocation EllipsisLoc) {
2693 if (!classdecl)
2694 return true;
2695
2696 AdjustDeclIfTemplate(classdecl);
2697 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2698 if (!Class)
2699 return true;
2700
2701 // We haven't yet attached the base specifiers.
2702 Class->setIsParsingBaseSpecifiers();
2703
2704 // We do not support any C++11 attributes on base-specifiers yet.
2705 // Diagnose any attributes we see.
2706 for (const ParsedAttr &AL : Attributes) {
2707 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2708 continue;
2709 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2710 ? (unsigned)diag::warn_unknown_attribute_ignored
2711 : (unsigned)diag::err_base_specifier_attribute)
2712 << AL << AL.getRange();
2713 }
2714
2715 TypeSourceInfo *TInfo = nullptr;
2716 GetTypeFromParser(basetype, &TInfo);
2717
2718 if (EllipsisLoc.isInvalid() &&
2719 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2720 UPPC_BaseType))
2721 return true;
2722
2723 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2724 Virtual, Access, TInfo,
2725 EllipsisLoc))
2726 return BaseSpec;
2727 else
2728 Class->setInvalidDecl();
2729
2730 return true;
2731}
2732
2733/// Use small set to collect indirect bases. As this is only used
2734/// locally, there's no need to abstract the small size parameter.
2735typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2736
2737/// Recursively add the bases of Type. Don't add Type itself.
2738static void
2739NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2740 const QualType &Type)
2741{
2742 // Even though the incoming type is a base, it might not be
2743 // a class -- it could be a template parm, for instance.
2744 if (auto Rec = Type->getAs<RecordType>()) {
2745 auto Decl = Rec->getAsCXXRecordDecl();
2746
2747 // Iterate over its bases.
2748 for (const auto &BaseSpec : Decl->bases()) {
2749 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2750 .getUnqualifiedType();
2751 if (Set.insert(Base).second)
2752 // If we've not already seen it, recurse.
2753 NoteIndirectBases(Context, Set, Base);
2754 }
2755 }
2756}
2757
2758/// Performs the actual work of attaching the given base class
2759/// specifiers to a C++ class.
2760bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2761 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2762 if (Bases.empty())
2763 return false;
2764
2765 // Used to keep track of which base types we have already seen, so
2766 // that we can properly diagnose redundant direct base types. Note
2767 // that the key is always the unqualified canonical type of the base
2768 // class.
2769 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2770
2771 // Used to track indirect bases so we can see if a direct base is
2772 // ambiguous.
2773 IndirectBaseSet IndirectBaseTypes;
2774
2775 // Copy non-redundant base specifiers into permanent storage.
2776 unsigned NumGoodBases = 0;
2777 bool Invalid = false;
2778 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2779 QualType NewBaseType
2780 = Context.getCanonicalType(Bases[idx]->getType());
2781 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2782
2783 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2784 if (KnownBase) {
2785 // C++ [class.mi]p3:
2786 // A class shall not be specified as a direct base class of a
2787 // derived class more than once.
2788 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2789 << KnownBase->getType() << Bases[idx]->getSourceRange();
2790
2791 // Delete the duplicate base class specifier; we're going to
2792 // overwrite its pointer later.
2793 Context.Deallocate(Bases[idx]);
2794
2795 Invalid = true;
2796 } else {
2797 // Okay, add this new base class.
2798 KnownBase = Bases[idx];
2799 Bases[NumGoodBases++] = Bases[idx];
2800
2801 if (NewBaseType->isDependentType())
2802 continue;
2803 // Note this base's direct & indirect bases, if there could be ambiguity.
2804 if (Bases.size() > 1)
2805 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2806
2807 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2808 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2809 if (Class->isInterface() &&
2810 (!RD->isInterfaceLike() ||
2811 KnownBase->getAccessSpecifier() != AS_public)) {
2812 // The Microsoft extension __interface does not permit bases that
2813 // are not themselves public interfaces.
2814 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2815 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2816 << RD->getSourceRange();
2817 Invalid = true;
2818 }
2819 if (RD->hasAttr<WeakAttr>())
2820 Class->addAttr(WeakAttr::CreateImplicit(Context));
2821 }
2822 }
2823 }
2824
2825 // Attach the remaining base class specifiers to the derived class.
2826 Class->setBases(Bases.data(), NumGoodBases);
2827
2828 // Check that the only base classes that are duplicate are virtual.
2829 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2830 // Check whether this direct base is inaccessible due to ambiguity.
2831 QualType BaseType = Bases[idx]->getType();
2832
2833 // Skip all dependent types in templates being used as base specifiers.
2834 // Checks below assume that the base specifier is a CXXRecord.
2835 if (BaseType->isDependentType())
2836 continue;
2837
2838 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2839 .getUnqualifiedType();
2840
2841 if (IndirectBaseTypes.count(CanonicalBase)) {
2842 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2843 /*DetectVirtual=*/true);
2844 bool found
2845 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2846 assert(found)(static_cast <bool> (found) ? void (0) : __assert_fail (
"found", "clang/lib/Sema/SemaDeclCXX.cpp", 2846, __extension__
__PRETTY_FUNCTION__))
;
2847 (void)found;
2848
2849 if (Paths.isAmbiguous(CanonicalBase))
2850 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2851 << BaseType << getAmbiguousPathsDisplayString(Paths)
2852 << Bases[idx]->getSourceRange();
2853 else
2854 assert(Bases[idx]->isVirtual())(static_cast <bool> (Bases[idx]->isVirtual()) ? void
(0) : __assert_fail ("Bases[idx]->isVirtual()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 2854, __extension__ __PRETTY_FUNCTION__))
;
2855 }
2856
2857 // Delete the base class specifier, since its data has been copied
2858 // into the CXXRecordDecl.
2859 Context.Deallocate(Bases[idx]);
2860 }
2861
2862 return Invalid;
2863}
2864
2865/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2866/// class, after checking whether there are any duplicate base
2867/// classes.
2868void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2869 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2870 if (!ClassDecl || Bases.empty())
2871 return;
2872
2873 AdjustDeclIfTemplate(ClassDecl);
2874 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2875}
2876
2877/// Determine whether the type \p Derived is a C++ class that is
2878/// derived from the type \p Base.
2879bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2880 if (!getLangOpts().CPlusPlus)
2881 return false;
2882
2883 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2884 if (!DerivedRD)
2885 return false;
2886
2887 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2888 if (!BaseRD)
2889 return false;
2890
2891 // If either the base or the derived type is invalid, don't try to
2892 // check whether one is derived from the other.
2893 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2894 return false;
2895
2896 // FIXME: In a modules build, do we need the entire path to be visible for us
2897 // to be able to use the inheritance relationship?
2898 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2899 return false;
2900
2901 return DerivedRD->isDerivedFrom(BaseRD);
2902}
2903
2904/// Determine whether the type \p Derived is a C++ class that is
2905/// derived from the type \p Base.
2906bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2907 CXXBasePaths &Paths) {
2908 if (!getLangOpts().CPlusPlus)
2909 return false;
2910
2911 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2912 if (!DerivedRD)
2913 return false;
2914
2915 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2916 if (!BaseRD)
2917 return false;
2918
2919 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2920 return false;
2921
2922 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2923}
2924
2925static void BuildBasePathArray(const CXXBasePath &Path,
2926 CXXCastPath &BasePathArray) {
2927 // We first go backward and check if we have a virtual base.
2928 // FIXME: It would be better if CXXBasePath had the base specifier for
2929 // the nearest virtual base.
2930 unsigned Start = 0;
2931 for (unsigned I = Path.size(); I != 0; --I) {
2932 if (Path[I - 1].Base->isVirtual()) {
2933 Start = I - 1;
2934 break;
2935 }
2936 }
2937
2938 // Now add all bases.
2939 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2940 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2941}
2942
2943
2944void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2945 CXXCastPath &BasePathArray) {
2946 assert(BasePathArray.empty() && "Base path array must be empty!")(static_cast <bool> (BasePathArray.empty() && "Base path array must be empty!"
) ? void (0) : __assert_fail ("BasePathArray.empty() && \"Base path array must be empty!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 2946, __extension__ __PRETTY_FUNCTION__
))
;
2947 assert(Paths.isRecordingPaths() && "Must record paths!")(static_cast <bool> (Paths.isRecordingPaths() &&
"Must record paths!") ? void (0) : __assert_fail ("Paths.isRecordingPaths() && \"Must record paths!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 2947, __extension__ __PRETTY_FUNCTION__
))
;
2948 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2949}
2950/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2951/// conversion (where Derived and Base are class types) is
2952/// well-formed, meaning that the conversion is unambiguous (and
2953/// that all of the base classes are accessible). Returns true
2954/// and emits a diagnostic if the code is ill-formed, returns false
2955/// otherwise. Loc is the location where this routine should point to
2956/// if there is an error, and Range is the source range to highlight
2957/// if there is an error.
2958///
2959/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2960/// diagnostic for the respective type of error will be suppressed, but the
2961/// check for ill-formed code will still be performed.
2962bool
2963Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2964 unsigned InaccessibleBaseID,
2965 unsigned AmbiguousBaseConvID,
2966 SourceLocation Loc, SourceRange Range,
2967 DeclarationName Name,
2968 CXXCastPath *BasePath,
2969 bool IgnoreAccess) {
2970 // First, determine whether the path from Derived to Base is
2971 // ambiguous. This is slightly more expensive than checking whether
2972 // the Derived to Base conversion exists, because here we need to
2973 // explore multiple paths to determine if there is an ambiguity.
2974 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2975 /*DetectVirtual=*/false);
2976 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2977 if (!DerivationOkay)
2978 return true;
2979
2980 const CXXBasePath *Path = nullptr;
2981 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2982 Path = &Paths.front();
2983
2984 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2985 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2986 // user to access such bases.
2987 if (!Path && getLangOpts().MSVCCompat) {
2988 for (const CXXBasePath &PossiblePath : Paths) {
2989 if (PossiblePath.size() == 1) {
2990 Path = &PossiblePath;
2991 if (AmbiguousBaseConvID)
2992 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2993 << Base << Derived << Range;
2994 break;
2995 }
2996 }
2997 }
2998
2999 if (Path) {
3000 if (!IgnoreAccess) {
3001 // Check that the base class can be accessed.
3002 switch (
3003 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3004 case AR_inaccessible:
3005 return true;
3006 case AR_accessible:
3007 case AR_dependent:
3008 case AR_delayed:
3009 break;
3010 }
3011 }
3012
3013 // Build a base path if necessary.
3014 if (BasePath)
3015 ::BuildBasePathArray(*Path, *BasePath);
3016 return false;
3017 }
3018
3019 if (AmbiguousBaseConvID) {
3020 // We know that the derived-to-base conversion is ambiguous, and
3021 // we're going to produce a diagnostic. Perform the derived-to-base
3022 // search just one more time to compute all of the possible paths so
3023 // that we can print them out. This is more expensive than any of
3024 // the previous derived-to-base checks we've done, but at this point
3025 // performance isn't as much of an issue.
3026 Paths.clear();
3027 Paths.setRecordingPaths(true);
3028 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3029 assert(StillOkay && "Can only be used with a derived-to-base conversion")(static_cast <bool> (StillOkay && "Can only be used with a derived-to-base conversion"
) ? void (0) : __assert_fail ("StillOkay && \"Can only be used with a derived-to-base conversion\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 3029, __extension__ __PRETTY_FUNCTION__
))
;
3030 (void)StillOkay;
3031
3032 // Build up a textual representation of the ambiguous paths, e.g.,
3033 // D -> B -> A, that will be used to illustrate the ambiguous
3034 // conversions in the diagnostic. We only print one of the paths
3035 // to each base class subobject.
3036 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3037
3038 Diag(Loc, AmbiguousBaseConvID)
3039 << Derived << Base << PathDisplayStr << Range << Name;
3040 }
3041 return true;
3042}
3043
3044bool
3045Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3046 SourceLocation Loc, SourceRange Range,
3047 CXXCastPath *BasePath,
3048 bool IgnoreAccess) {
3049 return CheckDerivedToBaseConversion(
3050 Derived, Base, diag::err_upcast_to_inaccessible_base,
3051 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3052 BasePath, IgnoreAccess);
3053}
3054
3055
3056/// Builds a string representing ambiguous paths from a
3057/// specific derived class to different subobjects of the same base
3058/// class.
3059///
3060/// This function builds a string that can be used in error messages
3061/// to show the different paths that one can take through the
3062/// inheritance hierarchy to go from the derived class to different
3063/// subobjects of a base class. The result looks something like this:
3064/// @code
3065/// struct D -> struct B -> struct A
3066/// struct D -> struct C -> struct A
3067/// @endcode
3068std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3069 std::string PathDisplayStr;
3070 std::set<unsigned> DisplayedPaths;
3071 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3072 Path != Paths.end(); ++Path) {
3073 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3074 // We haven't displayed a path to this particular base
3075 // class subobject yet.
3076 PathDisplayStr += "\n ";
3077 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3078 for (CXXBasePath::const_iterator Element = Path->begin();
3079 Element != Path->end(); ++Element)
3080 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3081 }
3082 }
3083
3084 return PathDisplayStr;
3085}
3086
3087//===----------------------------------------------------------------------===//
3088// C++ class member Handling
3089//===----------------------------------------------------------------------===//
3090
3091/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3092bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3093 SourceLocation ColonLoc,
3094 const ParsedAttributesView &Attrs) {
3095 assert(Access != AS_none && "Invalid kind for syntactic access specifier!")(static_cast <bool> (Access != AS_none && "Invalid kind for syntactic access specifier!"
) ? void (0) : __assert_fail ("Access != AS_none && \"Invalid kind for syntactic access specifier!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 3095, __extension__ __PRETTY_FUNCTION__
))
;
3096 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3097 ASLoc, ColonLoc);
3098 CurContext->addHiddenDecl(ASDecl);
3099 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3100}
3101
3102/// CheckOverrideControl - Check C++11 override control semantics.
3103void Sema::CheckOverrideControl(NamedDecl *D) {
3104 if (D->isInvalidDecl())
3105 return;
3106
3107 // We only care about "override" and "final" declarations.
3108 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3109 return;
3110
3111 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3112
3113 // We can't check dependent instance methods.
3114 if (MD && MD->isInstance() &&
3115 (MD->getParent()->hasAnyDependentBases() ||
3116 MD->getType()->isDependentType()))
3117 return;
3118
3119 if (MD && !MD->isVirtual()) {
3120 // If we have a non-virtual method, check if it hides a virtual method.
3121 // (In that case, it's most likely the method has the wrong type.)
3122 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3123 FindHiddenVirtualMethods(MD, OverloadedMethods);
3124
3125 if (!OverloadedMethods.empty()) {
3126 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3127 Diag(OA->getLocation(),
3128 diag::override_keyword_hides_virtual_member_function)
3129 << "override" << (OverloadedMethods.size() > 1);
3130 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3131 Diag(FA->getLocation(),
3132 diag::override_keyword_hides_virtual_member_function)
3133 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3134 << (OverloadedMethods.size() > 1);
3135 }
3136 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3137 MD->setInvalidDecl();
3138 return;
3139 }
3140 // Fall through into the general case diagnostic.
3141 // FIXME: We might want to attempt typo correction here.
3142 }
3143
3144 if (!MD || !MD->isVirtual()) {
3145 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3146 Diag(OA->getLocation(),
3147 diag::override_keyword_only_allowed_on_virtual_member_functions)
3148 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3149 D->dropAttr<OverrideAttr>();
3150 }
3151 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3152 Diag(FA->getLocation(),
3153 diag::override_keyword_only_allowed_on_virtual_member_functions)
3154 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3155 << FixItHint::CreateRemoval(FA->getLocation());
3156 D->dropAttr<FinalAttr>();
3157 }
3158 return;
3159 }
3160
3161 // C++11 [class.virtual]p5:
3162 // If a function is marked with the virt-specifier override and
3163 // does not override a member function of a base class, the program is
3164 // ill-formed.
3165 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3166 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3167 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3168 << MD->getDeclName();
3169}
3170
3171void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3172 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3173 return;
3174 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3175 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3176 return;
3177
3178 SourceLocation Loc = MD->getLocation();
3179 SourceLocation SpellingLoc = Loc;
3180 if (getSourceManager().isMacroArgExpansion(Loc))
3181 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3182 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3183 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3184 return;
3185
3186 if (MD->size_overridden_methods() > 0) {
3187 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3188 unsigned DiagID =
3189 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3190 ? DiagInconsistent
3191 : DiagSuggest;
3192 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3193 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3194 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3195 };
3196 if (isa<CXXDestructorDecl>(MD))
3197 EmitDiag(
3198 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3199 diag::warn_suggest_destructor_marked_not_override_overriding);
3200 else
3201 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3202 diag::warn_suggest_function_marked_not_override_overriding);
3203 }
3204}
3205
3206/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3207/// function overrides a virtual member function marked 'final', according to
3208/// C++11 [class.virtual]p4.
3209bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3210 const CXXMethodDecl *Old) {
3211 FinalAttr *FA = Old->getAttr<FinalAttr>();
3212 if (!FA)
3213 return false;
3214
3215 Diag(New->getLocation(), diag::err_final_function_overridden)
3216 << New->getDeclName()
3217 << FA->isSpelledAsSealed();
3218 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3219 return true;
3220}
3221
3222static bool InitializationHasSideEffects(const FieldDecl &FD) {
3223 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3224 // FIXME: Destruction of ObjC lifetime types has side-effects.
3225 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3226 return !RD->isCompleteDefinition() ||
3227 !RD->hasTrivialDefaultConstructor() ||
3228 !RD->hasTrivialDestructor();
3229 return false;
3230}
3231
3232static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3233 ParsedAttributesView::const_iterator Itr =
3234 llvm::find_if(list, [](const ParsedAttr &AL) {
3235 return AL.isDeclspecPropertyAttribute();
3236 });
3237 if (Itr != list.end())
3238 return &*Itr;
3239 return nullptr;
3240}
3241
3242// Check if there is a field shadowing.
3243void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3244 DeclarationName FieldName,
3245 const CXXRecordDecl *RD,
3246 bool DeclIsField) {
3247 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3248 return;
3249
3250 // To record a shadowed field in a base
3251 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3252 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3253 CXXBasePath &Path) {
3254 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3255 // Record an ambiguous path directly
3256 if (Bases.find(Base) != Bases.end())
3257 return true;
3258 for (const auto Field : Base->lookup(FieldName)) {
3259 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3260 Field->getAccess() != AS_private) {
3261 assert(Field->getAccess() != AS_none)(static_cast <bool> (Field->getAccess() != AS_none) ?
void (0) : __assert_fail ("Field->getAccess() != AS_none"
, "clang/lib/Sema/SemaDeclCXX.cpp", 3261, __extension__ __PRETTY_FUNCTION__
))
;
3262 assert(Bases.find(Base) == Bases.end())(static_cast <bool> (Bases.find(Base) == Bases.end()) ?
void (0) : __assert_fail ("Bases.find(Base) == Bases.end()",
"clang/lib/Sema/SemaDeclCXX.cpp", 3262, __extension__ __PRETTY_FUNCTION__
))
;
3263 Bases[Base] = Field;
3264 return true;
3265 }
3266 }
3267 return false;
3268 };
3269
3270 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3271 /*DetectVirtual=*/true);
3272 if (!RD->lookupInBases(FieldShadowed, Paths))
3273 return;
3274
3275 for (const auto &P : Paths) {
3276 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3277 auto It = Bases.find(Base);
3278 // Skip duplicated bases
3279 if (It == Bases.end())
3280 continue;
3281 auto BaseField = It->second;
3282 assert(BaseField->getAccess() != AS_private)(static_cast <bool> (BaseField->getAccess() != AS_private
) ? void (0) : __assert_fail ("BaseField->getAccess() != AS_private"
, "clang/lib/Sema/SemaDeclCXX.cpp", 3282, __extension__ __PRETTY_FUNCTION__
))
;
3283 if (AS_none !=
3284 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3285 Diag(Loc, diag::warn_shadow_field)
3286 << FieldName << RD << Base << DeclIsField;
3287 Diag(BaseField->getLocation(), diag::note_shadow_field);
3288 Bases.erase(It);
3289 }
3290 }
3291}
3292
3293/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3294/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3295/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3296/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3297/// present (but parsing it has been deferred).
3298NamedDecl *
3299Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3300 MultiTemplateParamsArg TemplateParameterLists,
3301 Expr *BW, const VirtSpecifiers &VS,
3302 InClassInitStyle InitStyle) {
3303 const DeclSpec &DS = D.getDeclSpec();
3304 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3305 DeclarationName Name = NameInfo.getName();
3306 SourceLocation Loc = NameInfo.getLoc();
3307
3308 // For anonymous bitfields, the location should point to the type.
3309 if (Loc.isInvalid())
3310 Loc = D.getBeginLoc();
3311
3312 Expr *BitWidth = static_cast<Expr*>(BW);
3313
3314 assert(isa<CXXRecordDecl>(CurContext))(static_cast <bool> (isa<CXXRecordDecl>(CurContext
)) ? void (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)"
, "clang/lib/Sema/SemaDeclCXX.cpp", 3314, __extension__ __PRETTY_FUNCTION__
))
;
3315 assert(!DS.isFriendSpecified())(static_cast <bool> (!DS.isFriendSpecified()) ? void (0
) : __assert_fail ("!DS.isFriendSpecified()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 3315, __extension__ __PRETTY_FUNCTION__))
;
3316
3317 bool isFunc = D.isDeclarationOfFunction();
3318 const ParsedAttr *MSPropertyAttr =
3319 getMSPropertyAttr(D.getDeclSpec().getAttributes());
3320
3321 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3322 // The Microsoft extension __interface only permits public member functions
3323 // and prohibits constructors, destructors, operators, non-public member
3324 // functions, static methods and data members.
3325 unsigned InvalidDecl;
3326 bool ShowDeclName = true;
3327 if (!isFunc &&
3328 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3329 InvalidDecl = 0;
3330 else if (!isFunc)
3331 InvalidDecl = 1;
3332 else if (AS != AS_public)
3333 InvalidDecl = 2;
3334 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3335 InvalidDecl = 3;
3336 else switch (Name.getNameKind()) {
3337 case DeclarationName::CXXConstructorName:
3338 InvalidDecl = 4;
3339 ShowDeclName = false;
3340 break;
3341
3342 case DeclarationName::CXXDestructorName:
3343 InvalidDecl = 5;
3344 ShowDeclName = false;
3345 break;
3346
3347 case DeclarationName::CXXOperatorName:
3348 case DeclarationName::CXXConversionFunctionName:
3349 InvalidDecl = 6;
3350 break;
3351
3352 default:
3353 InvalidDecl = 0;
3354 break;
3355 }
3356
3357 if (InvalidDecl) {
3358 if (ShowDeclName)
3359 Diag(Loc, diag::err_invalid_member_in_interface)
3360 << (InvalidDecl-1) << Name;
3361 else
3362 Diag(Loc, diag::err_invalid_member_in_interface)
3363 << (InvalidDecl-1) << "";
3364 return nullptr;
3365 }
3366 }
3367
3368 // C++ 9.2p6: A member shall not be declared to have automatic storage
3369 // duration (auto, register) or with the extern storage-class-specifier.
3370 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3371 // data members and cannot be applied to names declared const or static,
3372 // and cannot be applied to reference members.
3373 switch (DS.getStorageClassSpec()) {
3374 case DeclSpec::SCS_unspecified:
3375 case DeclSpec::SCS_typedef:
3376 case DeclSpec::SCS_static:
3377 break;
3378 case DeclSpec::SCS_mutable:
3379 if (isFunc) {
3380 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3381
3382 // FIXME: It would be nicer if the keyword was ignored only for this
3383 // declarator. Otherwise we could get follow-up errors.
3384 D.getMutableDeclSpec().ClearStorageClassSpecs();
3385 }
3386 break;
3387 default:
3388 Diag(DS.getStorageClassSpecLoc(),
3389 diag::err_storageclass_invalid_for_member);
3390 D.getMutableDeclSpec().ClearStorageClassSpecs();
3391 break;
3392 }
3393
3394 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3395 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3396 !isFunc);
3397
3398 if (DS.hasConstexprSpecifier() && isInstField) {
3399 SemaDiagnosticBuilder B =
3400 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3401 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3402 if (InitStyle == ICIS_NoInit) {
3403 B << 0 << 0;
3404 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3405 B << FixItHint::CreateRemoval(ConstexprLoc);
3406 else {
3407 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3408 D.getMutableDeclSpec().ClearConstexprSpec();
3409 const char *PrevSpec;
3410 unsigned DiagID;
3411 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3412 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3413 (void)Failed;
3414 assert(!Failed && "Making a constexpr member const shouldn't fail")(static_cast <bool> (!Failed && "Making a constexpr member const shouldn't fail"
) ? void (0) : __assert_fail ("!Failed && \"Making a constexpr member const shouldn't fail\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 3414, __extension__ __PRETTY_FUNCTION__
))
;
3415 }
3416 } else {
3417 B << 1;
3418 const char *PrevSpec;
3419 unsigned DiagID;
3420 if (D.getMutableDeclSpec().SetStorageClassSpec(
3421 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3422 Context.getPrintingPolicy())) {
3423 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&(static_cast <bool> (DS.getStorageClassSpec() == DeclSpec
::SCS_mutable && "This is the only DeclSpec that should fail to be applied"
) ? void (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 3424, __extension__ __PRETTY_FUNCTION__
))
3424 "This is the only DeclSpec that should fail to be applied")(static_cast <bool> (DS.getStorageClassSpec() == DeclSpec
::SCS_mutable && "This is the only DeclSpec that should fail to be applied"
) ? void (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 3424, __extension__ __PRETTY_FUNCTION__
))
;
3425 B << 1;
3426 } else {
3427 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3428 isInstField = false;
3429 }
3430 }
3431 }
3432
3433 NamedDecl *Member;
3434 if (isInstField) {
3435 CXXScopeSpec &SS = D.getCXXScopeSpec();
3436
3437 // Data members must have identifiers for names.
3438 if (!Name.isIdentifier()) {
3439 Diag(Loc, diag::err_bad_variable_name)
3440 << Name;
3441 return nullptr;
3442 }
3443
3444 IdentifierInfo *II = Name.getAsIdentifierInfo();
3445
3446 // Member field could not be with "template" keyword.
3447 // So TemplateParameterLists should be empty in this case.
3448 if (TemplateParameterLists.size()) {
3449 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3450 if (TemplateParams->size()) {
3451 // There is no such thing as a member field template.
3452 Diag(D.getIdentifierLoc(), diag::err_template_member)
3453 << II
3454 << SourceRange(TemplateParams->getTemplateLoc(),
3455 TemplateParams->getRAngleLoc());
3456 } else {
3457 // There is an extraneous 'template<>' for this member.
3458 Diag(TemplateParams->getTemplateLoc(),
3459 diag::err_template_member_noparams)
3460 << II
3461 << SourceRange(TemplateParams->getTemplateLoc(),
3462 TemplateParams->getRAngleLoc());
3463 }
3464 return nullptr;
3465 }
3466
3467 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3468 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3469 << II
3470 << SourceRange(D.getName().TemplateId->LAngleLoc,
3471 D.getName().TemplateId->RAngleLoc)
3472 << D.getName().TemplateId->LAngleLoc;
3473 D.SetIdentifier(II, Loc);
3474 }
3475
3476 if (SS.isSet() && !SS.isInvalid()) {
3477 // The user provided a superfluous scope specifier inside a class
3478 // definition:
3479 //
3480 // class X {
3481 // int X::member;
3482 // };
3483 if (DeclContext *DC = computeDeclContext(SS, false))
3484 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3485 D.getName().getKind() ==
3486 UnqualifiedIdKind::IK_TemplateId);
3487 else
3488 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3489 << Name << SS.getRange();
3490
3491 SS.clear();
3492 }
3493
3494 if (MSPropertyAttr) {
3495 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3496 BitWidth, InitStyle, AS, *MSPropertyAttr);
3497 if (!Member)
3498 return nullptr;
3499 isInstField = false;
3500 } else {
3501 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3502 BitWidth, InitStyle, AS);
3503 if (!Member)
3504 return nullptr;
3505 }
3506
3507 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3508 } else {
3509 Member = HandleDeclarator(S, D, TemplateParameterLists);
3510 if (!Member)
3511 return nullptr;
3512
3513 // Non-instance-fields can't have a bitfield.
3514 if (BitWidth) {
3515 if (Member->isInvalidDecl()) {
3516 // don't emit another diagnostic.
3517 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3518 // C++ 9.6p3: A bit-field shall not be a static member.
3519 // "static member 'A' cannot be a bit-field"
3520 Diag(Loc, diag::err_static_not_bitfield)
3521 << Name << BitWidth->getSourceRange();
3522 } else if (isa<TypedefDecl>(Member)) {
3523 // "typedef member 'x' cannot be a bit-field"
3524 Diag(Loc, diag::err_typedef_not_bitfield)
3525 << Name << BitWidth->getSourceRange();
3526 } else {
3527 // A function typedef ("typedef int f(); f a;").
3528 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3529 Diag(Loc, diag::err_not_integral_type_bitfield)
3530 << Name << cast<ValueDecl>(Member)->getType()
3531 << BitWidth->getSourceRange();
3532 }
3533
3534 BitWidth = nullptr;
3535 Member->setInvalidDecl();
3536 }
3537
3538 NamedDecl *NonTemplateMember = Member;
3539 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3540 NonTemplateMember = FunTmpl->getTemplatedDecl();
3541 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3542 NonTemplateMember = VarTmpl->getTemplatedDecl();
3543
3544 Member->setAccess(AS);
3545
3546 // If we have declared a member function template or static data member
3547 // template, set the access of the templated declaration as well.
3548 if (NonTemplateMember != Member)
3549 NonTemplateMember->setAccess(AS);
3550
3551 // C++ [temp.deduct.guide]p3:
3552 // A deduction guide [...] for a member class template [shall be
3553 // declared] with the same access [as the template].
3554 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3555 auto *TD = DG->getDeducedTemplate();
3556 // Access specifiers are only meaningful if both the template and the
3557 // deduction guide are from the same scope.
3558 if (AS != TD->getAccess() &&
3559 TD->getDeclContext()->getRedeclContext()->Equals(
3560 DG->getDeclContext()->getRedeclContext())) {
3561 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3562 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3563 << TD->getAccess();
3564 const AccessSpecDecl *LastAccessSpec = nullptr;
3565 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3566 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3567 LastAccessSpec = AccessSpec;
3568 }
3569 assert(LastAccessSpec && "differing access with no access specifier")(static_cast <bool> (LastAccessSpec && "differing access with no access specifier"
) ? void (0) : __assert_fail ("LastAccessSpec && \"differing access with no access specifier\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 3569, __extension__ __PRETTY_FUNCTION__
))
;
3570 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3571 << AS;
3572 }
3573 }
3574 }
3575
3576 if (VS.isOverrideSpecified())
3577 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3578 AttributeCommonInfo::AS_Keyword));
3579 if (VS.isFinalSpecified())
3580 Member->addAttr(FinalAttr::Create(
3581 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3582 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3583
3584 if (VS.getLastLocation().isValid()) {
3585 // Update the end location of a method that has a virt-specifiers.
3586 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3587 MD->setRangeEnd(VS.getLastLocation());
3588 }
3589
3590 CheckOverrideControl(Member);
3591
3592 assert((Name || isInstField) && "No identifier for non-field ?")(static_cast <bool> ((Name || isInstField) && "No identifier for non-field ?"
) ? void (0) : __assert_fail ("(Name || isInstField) && \"No identifier for non-field ?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 3592, __extension__ __PRETTY_FUNCTION__
))
;
3593
3594 if (isInstField) {
3595 FieldDecl *FD = cast<FieldDecl>(Member);
3596 FieldCollector->Add(FD);
3597
3598 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3599 // Remember all explicit private FieldDecls that have a name, no side
3600 // effects and are not part of a dependent type declaration.
3601 if (!FD->isImplicit() && FD->getDeclName() &&
3602 FD->getAccess() == AS_private &&
3603 !FD->hasAttr<UnusedAttr>() &&
3604 !FD->getParent()->isDependentContext() &&
3605 !InitializationHasSideEffects(*FD))
3606 UnusedPrivateFields.insert(FD);
3607 }
3608 }
3609
3610 return Member;
3611}
3612
3613namespace {
3614 class UninitializedFieldVisitor
3615 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3616 Sema &S;
3617 // List of Decls to generate a warning on. Also remove Decls that become
3618 // initialized.
3619 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3620 // List of base classes of the record. Classes are removed after their
3621 // initializers.
3622 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3623 // Vector of decls to be removed from the Decl set prior to visiting the
3624 // nodes. These Decls may have been initialized in the prior initializer.
3625 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3626 // If non-null, add a note to the warning pointing back to the constructor.
3627 const CXXConstructorDecl *Constructor;
3628 // Variables to hold state when processing an initializer list. When
3629 // InitList is true, special case initialization of FieldDecls matching
3630 // InitListFieldDecl.
3631 bool InitList;
3632 FieldDecl *InitListFieldDecl;
3633 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3634
3635 public:
3636 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3637 UninitializedFieldVisitor(Sema &S,
3638 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3639 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3640 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3641 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3642
3643 // Returns true if the use of ME is not an uninitialized use.
3644 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3645 bool CheckReferenceOnly) {
3646 llvm::SmallVector<FieldDecl*, 4> Fields;
3647 bool ReferenceField = false;
3648 while (ME) {
3649 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3650 if (!FD)
3651 return false;
3652 Fields.push_back(FD);
3653 if (FD->getType()->isReferenceType())
3654 ReferenceField = true;
3655 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3656 }
3657
3658 // Binding a reference to an uninitialized field is not an
3659 // uninitialized use.
3660 if (CheckReferenceOnly && !ReferenceField)
3661 return true;
3662
3663 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3664 // Discard the first field since it is the field decl that is being
3665 // initialized.
3666 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3667 UsedFieldIndex.push_back(FD->getFieldIndex());
3668
3669 for (auto UsedIter = UsedFieldIndex.begin(),
3670 UsedEnd = UsedFieldIndex.end(),
3671 OrigIter = InitFieldIndex.begin(),
3672 OrigEnd = InitFieldIndex.end();
3673 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3674 if (*UsedIter < *OrigIter)
3675 return true;
3676 if (*UsedIter > *OrigIter)
3677 break;
3678 }
3679
3680 return false;
3681 }
3682
3683 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3684 bool AddressOf) {
3685 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3686 return;
3687
3688 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3689 // or union.
3690 MemberExpr *FieldME = ME;
3691
3692 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3693
3694 Expr *Base = ME;
3695 while (MemberExpr *SubME =
3696 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3697
3698 if (isa<VarDecl>(SubME->getMemberDecl()))
3699 return;
3700
3701 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3702 if (!FD->isAnonymousStructOrUnion())
3703 FieldME = SubME;
3704
3705 if (!FieldME->getType().isPODType(S.Context))
3706 AllPODFields = false;
3707
3708 Base = SubME->getBase();
3709 }
3710
3711 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3712 Visit(Base);
3713 return;
3714 }
3715
3716 if (AddressOf && AllPODFields)
3717 return;
3718
3719 ValueDecl* FoundVD = FieldME->getMemberDecl();
3720
3721 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3722 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3723 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3724 }
3725
3726 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3727 QualType T = BaseCast->getType();
3728 if (T->isPointerType() &&
3729 BaseClasses.count(T->getPointeeType())) {
3730 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3731 << T->getPointeeType() << FoundVD;
3732 }
3733 }
3734 }
3735
3736 if (!Decls.count(FoundVD))
3737 return;
3738
3739 const bool IsReference = FoundVD->getType()->isReferenceType();
3740
3741 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3742 // Special checking for initializer lists.
3743 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3744 return;
3745 }
3746 } else {
3747 // Prevent double warnings on use of unbounded references.
3748 if (CheckReferenceOnly && !IsReference)
3749 return;
3750 }
3751
3752 unsigned diag = IsReference
3753 ? diag::warn_reference_field_is_uninit
3754 : diag::warn_field_is_uninit;
3755 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3756 if (Constructor)
3757 S.Diag(Constructor->getLocation(),
3758 diag::note_uninit_in_this_constructor)
3759 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3760
3761 }
3762
3763 void HandleValue(Expr *E, bool AddressOf) {
3764 E = E->IgnoreParens();
3765
3766 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3767 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3768 AddressOf /*AddressOf*/);
3769 return;
3770 }
3771
3772 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3773 Visit(CO->getCond());
3774 HandleValue(CO->getTrueExpr(), AddressOf);
3775 HandleValue(CO->getFalseExpr(), AddressOf);
3776 return;
3777 }
3778
3779 if (BinaryConditionalOperator *BCO =
3780 dyn_cast<BinaryConditionalOperator>(E)) {
3781 Visit(BCO->getCond());
3782 HandleValue(BCO->getFalseExpr(), AddressOf);
3783 return;
3784 }
3785
3786 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3787 HandleValue(OVE->getSourceExpr(), AddressOf);
3788 return;
3789 }
3790
3791 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3792 switch (BO->getOpcode()) {
3793 default:
3794 break;
3795 case(BO_PtrMemD):
3796 case(BO_PtrMemI):
3797 HandleValue(BO->getLHS(), AddressOf);
3798 Visit(BO->getRHS());
3799 return;
3800 case(BO_Comma):
3801 Visit(BO->getLHS());
3802 HandleValue(BO->getRHS(), AddressOf);
3803 return;
3804 }
3805 }
3806
3807 Visit(E);
3808 }
3809
3810 void CheckInitListExpr(InitListExpr *ILE) {
3811 InitFieldIndex.push_back(0);
3812 for (auto *Child : ILE->children()) {
3813 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3814 CheckInitListExpr(SubList);
3815 } else {
3816 Visit(Child);
3817 }
3818 ++InitFieldIndex.back();
3819 }
3820 InitFieldIndex.pop_back();
3821 }
3822
3823 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3824 FieldDecl *Field, const Type *BaseClass) {
3825 // Remove Decls that may have been initialized in the previous
3826 // initializer.
3827 for (ValueDecl* VD : DeclsToRemove)
3828 Decls.erase(VD);
3829 DeclsToRemove.clear();
3830
3831 Constructor = FieldConstructor;
3832 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3833
3834 if (ILE && Field) {
3835 InitList = true;
3836 InitListFieldDecl = Field;
3837 InitFieldIndex.clear();
3838 CheckInitListExpr(ILE);
3839 } else {
3840 InitList = false;
3841 Visit(E);
3842 }
3843
3844 if (Field)
3845 Decls.erase(Field);
3846 if (BaseClass)
3847 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3848 }
3849
3850 void VisitMemberExpr(MemberExpr *ME) {
3851 // All uses of unbounded reference fields will warn.
3852 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3853 }
3854
3855 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3856 if (E->getCastKind() == CK_LValueToRValue) {
3857 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3858 return;
3859 }
3860
3861 Inherited::VisitImplicitCastExpr(E);
3862 }
3863
3864 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3865 if (E->getConstructor()->isCopyConstructor()) {
3866 Expr *ArgExpr = E->getArg(0);
3867 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3868 if (ILE->getNumInits() == 1)
3869 ArgExpr = ILE->getInit(0);
3870 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3871 if (ICE->getCastKind() == CK_NoOp)
3872 ArgExpr = ICE->getSubExpr();
3873 HandleValue(ArgExpr, false /*AddressOf*/);
3874 return;
3875 }
3876 Inherited::VisitCXXConstructExpr(E);
3877 }
3878
3879 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3880 Expr *Callee = E->getCallee();
3881 if (isa<MemberExpr>(Callee)) {
3882 HandleValue(Callee, false /*AddressOf*/);
3883 for (auto *Arg : E->arguments())
3884 Visit(Arg);
3885 return;
3886 }
3887
3888 Inherited::VisitCXXMemberCallExpr(E);
3889 }
3890
3891 void VisitCallExpr(CallExpr *E) {
3892 // Treat std::move as a use.
3893 if (E->isCallToStdMove()) {
3894 HandleValue(E->getArg(0), /*AddressOf=*/false);
3895 return;
3896 }
3897
3898 Inherited::VisitCallExpr(E);
3899 }
3900
3901 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3902 Expr *Callee = E->getCallee();
3903
3904 if (isa<UnresolvedLookupExpr>(Callee))
3905 return Inherited::VisitCXXOperatorCallExpr(E);
3906
3907 Visit(Callee);
3908 for (auto *Arg : E->arguments())
3909 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3910 }
3911
3912 void VisitBinaryOperator(BinaryOperator *E) {
3913 // If a field assignment is detected, remove the field from the
3914 // uninitiailized field set.
3915 if (E->getOpcode() == BO_Assign)
3916 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3917 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3918 if (!FD->getType()->isReferenceType())
3919 DeclsToRemove.push_back(FD);
3920
3921 if (E->isCompoundAssignmentOp()) {
3922 HandleValue(E->getLHS(), false /*AddressOf*/);
3923 Visit(E->getRHS());
3924 return;
3925 }
3926
3927 Inherited::VisitBinaryOperator(E);
3928 }
3929
3930 void VisitUnaryOperator(UnaryOperator *E) {
3931 if (E->isIncrementDecrementOp()) {
3932 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3933 return;
3934 }
3935 if (E->getOpcode() == UO_AddrOf) {
3936 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3937 HandleValue(ME->getBase(), true /*AddressOf*/);
3938 return;
3939 }
3940 }
3941
3942 Inherited::VisitUnaryOperator(E);
3943 }
3944 };
3945
3946 // Diagnose value-uses of fields to initialize themselves, e.g.
3947 // foo(foo)
3948 // where foo is not also a parameter to the constructor.
3949 // Also diagnose across field uninitialized use such as
3950 // x(y), y(x)
3951 // TODO: implement -Wuninitialized and fold this into that framework.
3952 static void DiagnoseUninitializedFields(
3953 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3954
3955 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3956 Constructor->getLocation())) {
3957 return;
3958 }
3959
3960 if (Constructor->isInvalidDecl())
3961 return;
3962
3963 const CXXRecordDecl *RD = Constructor->getParent();
3964
3965 if (RD->isDependentContext())
3966 return;
3967
3968 // Holds fields that are uninitialized.
3969 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3970
3971 // At the beginning, all fields are uninitialized.
3972 for (auto *I : RD->decls()) {
3973 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3974 UninitializedFields.insert(FD);
3975 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3976 UninitializedFields.insert(IFD->getAnonField());
3977 }
3978 }
3979
3980 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3981 for (auto I : RD->bases())
3982 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3983
3984 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3985 return;
3986
3987 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3988 UninitializedFields,
3989 UninitializedBaseClasses);
3990
3991 for (const auto *FieldInit : Constructor->inits()) {
3992 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3993 break;
3994
3995 Expr *InitExpr = FieldInit->getInit();
3996 if (!InitExpr)
3997 continue;
3998
3999 if (CXXDefaultInitExpr *Default =
4000 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4001 InitExpr = Default->getExpr();
4002 if (!InitExpr)
4003 continue;
4004 // In class initializers will point to the constructor.
4005 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4006 FieldInit->getAnyMember(),
4007 FieldInit->getBaseClass());
4008 } else {
4009 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4010 FieldInit->getAnyMember(),
4011 FieldInit->getBaseClass());
4012 }
4013 }
4014 }
4015} // namespace
4016
4017/// Enter a new C++ default initializer scope. After calling this, the
4018/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
4019/// parsing or instantiating the initializer failed.
4020void Sema::ActOnStartCXXInClassMemberInitializer() {
4021 // Create a synthetic function scope to represent the call to the constructor
4022 // that notionally surrounds a use of this initializer.
4023 PushFunctionScope();
4024}
4025
4026void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4027 if (!D.isFunctionDeclarator())
4028 return;
4029 auto &FTI = D.getFunctionTypeInfo();
4030 if (!FTI.Params)
4031 return;
4032 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4033 FTI.NumParams)) {
4034 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4035 if (ParamDecl->getDeclName())
4036 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4037 }
4038}
4039
4040ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4041 return ActOnRequiresClause(ConstraintExpr);
4042}
4043
4044ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4045 if (ConstraintExpr.isInvalid())
4046 return ExprError();
4047
4048 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4049 if (ConstraintExpr.isInvalid())
4050 return ExprError();
4051
4052 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4053 UPPC_RequiresClause))
4054 return ExprError();
4055
4056 return ConstraintExpr;
4057}
4058
4059ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4060 Expr *InitExpr,
4061 SourceLocation InitLoc) {
4062 InitializedEntity Entity =
4063 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4064 InitializationKind Kind =
4065 FD->getInClassInitStyle() == ICIS_ListInit
4066 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4067 InitExpr->getBeginLoc(),
4068 InitExpr->getEndLoc())
4069 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4070 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4071 return Seq.Perform(*this, Entity, Kind, InitExpr);
4072}
4073
4074/// This is invoked after parsing an in-class initializer for a
4075/// non-static C++ class member, and after instantiating an in-class initializer
4076/// in a class template. Such actions are deferred until the class is complete.
4077void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4078 SourceLocation InitLoc,
4079 Expr *InitExpr) {
4080 // Pop the notional constructor scope we created earlier.
4081 PopFunctionScopeInfo(nullptr, D);
4082
4083 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4084 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&(static_cast <bool> ((isa<MSPropertyDecl>(D) || FD
->getInClassInitStyle() != ICIS_NoInit) && "must set init style when field is created"
) ? void (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 4085, __extension__ __PRETTY_FUNCTION__
))
4085 "must set init style when field is created")(static_cast <bool> ((isa<MSPropertyDecl>(D) || FD
->getInClassInitStyle() != ICIS_NoInit) && "must set init style when field is created"
) ? void (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 4085, __extension__ __PRETTY_FUNCTION__
))
;
4086
4087 if (!InitExpr) {
4088 D->setInvalidDecl();
4089 if (FD)
4090 FD->removeInClassInitializer();
4091 return;
4092 }
4093
4094 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
4095 FD->setInvalidDecl();
4096 FD->removeInClassInitializer();
4097 return;
4098 }
4099
4100 ExprResult Init = InitExpr;
4101 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
4102 Init = ConvertMemberDefaultInitExpression(FD, InitExpr, InitLoc);
4103 // C++11 [class.base.init]p7:
4104 // The initialization of each base and member constitutes a
4105 // full-expression.
4106 if (!Init.isInvalid())
4107 Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4108 if (Init.isInvalid()) {
4109 FD->setInvalidDecl();
4110 return;
4111 }
4112 }
4113
4114 InitExpr = Init.get();
4115
4116 FD->setInClassInitializer(InitExpr);
4117}
4118
4119/// Find the direct and/or virtual base specifiers that
4120/// correspond to the given base type, for use in base initialization
4121/// within a constructor.
4122static bool FindBaseInitializer(Sema &SemaRef,
4123 CXXRecordDecl *ClassDecl,
4124 QualType BaseType,
4125 const CXXBaseSpecifier *&DirectBaseSpec,
4126 const CXXBaseSpecifier *&VirtualBaseSpec) {
4127 // First, check for a direct base class.
4128 DirectBaseSpec = nullptr;
4129 for (const auto &Base : ClassDecl->bases()) {
4130 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4131 // We found a direct base of this type. That's what we're
4132 // initializing.
4133 DirectBaseSpec = &Base;
4134 break;
4135 }
4136 }
4137
4138 // Check for a virtual base class.
4139 // FIXME: We might be able to short-circuit this if we know in advance that
4140 // there are no virtual bases.
4141 VirtualBaseSpec = nullptr;
4142 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4143 // We haven't found a base yet; search the class hierarchy for a
4144 // virtual base class.
4145 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4146 /*DetectVirtual=*/false);
4147 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4148 SemaRef.Context.getTypeDeclType(ClassDecl),
4149 BaseType, Paths)) {
4150 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4151 Path != Paths.end(); ++Path) {
4152 if (Path->back().Base->isVirtual()) {
4153 VirtualBaseSpec = Path->back().Base;
4154 break;
4155 }
4156 }
4157 }
4158 }
4159
4160 return DirectBaseSpec || VirtualBaseSpec;
4161}
4162
4163/// Handle a C++ member initializer using braced-init-list syntax.
4164MemInitResult
4165Sema::ActOnMemInitializer(Decl *ConstructorD,
4166 Scope *S,
4167 CXXScopeSpec &SS,
4168 IdentifierInfo *MemberOrBase,
4169 ParsedType TemplateTypeTy,
4170 const DeclSpec &DS,
4171 SourceLocation IdLoc,
4172 Expr *InitList,
4173 SourceLocation EllipsisLoc) {
4174 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4175 DS, IdLoc, InitList,
4176 EllipsisLoc);
4177}
4178
4179/// Handle a C++ member initializer using parentheses syntax.
4180MemInitResult
4181Sema::ActOnMemInitializer(Decl *ConstructorD,
4182 Scope *S,
4183 CXXScopeSpec &SS,
4184 IdentifierInfo *MemberOrBase,
4185 ParsedType TemplateTypeTy,
4186 const DeclSpec &DS,
4187 SourceLocation IdLoc,
4188 SourceLocation LParenLoc,
4189 ArrayRef<Expr *> Args,
4190 SourceLocation RParenLoc,
4191 SourceLocation EllipsisLoc) {
4192 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4193 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4194 DS, IdLoc, List, EllipsisLoc);
4195}
4196
4197namespace {
4198
4199// Callback to only accept typo corrections that can be a valid C++ member
4200// initializer: either a non-static field member or a base class.
4201class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4202public:
4203 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4204 : ClassDecl(ClassDecl) {}
4205
4206 bool ValidateCandidate(const TypoCorrection &candidate) override {
4207 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4208 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4209 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4210 return isa<TypeDecl>(ND);
4211 }
4212 return false;
4213 }
4214
4215 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4216 return std::make_unique<MemInitializerValidatorCCC>(*this);
4217 }
4218
4219private:
4220 CXXRecordDecl *ClassDecl;
4221};
4222
4223}
4224
4225ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4226 CXXScopeSpec &SS,
4227 ParsedType TemplateTypeTy,
4228 IdentifierInfo *MemberOrBase) {
4229 if (SS.getScopeRep() || TemplateTypeTy)
4230 return nullptr;
4231 for (auto *D : ClassDecl->lookup(MemberOrBase))
4232 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4233 return cast<ValueDecl>(D);
4234 return nullptr;
4235}
4236
4237/// Handle a C++ member initializer.
4238MemInitResult
4239Sema::BuildMemInitializer(Decl *ConstructorD,
4240 Scope *S,
4241 CXXScopeSpec &SS,
4242 IdentifierInfo *MemberOrBase,
4243 ParsedType TemplateTypeTy,
4244 const DeclSpec &DS,
4245 SourceLocation IdLoc,
4246 Expr *Init,
4247 SourceLocation EllipsisLoc) {
4248 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4249 /*RecoverUncorrectedTypos=*/true);
4250 if (!Res.isUsable())
4251 return true;
4252 Init = Res.get();
4253
4254 if (!ConstructorD)
4255 return true;
4256
4257 AdjustDeclIfTemplate(ConstructorD);
4258
4259 CXXConstructorDecl *Constructor
4260 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4261 if (!Constructor) {
4262 // The user wrote a constructor initializer on a function that is
4263 // not a C++ constructor. Ignore the error for now, because we may
4264 // have more member initializers coming; we'll diagnose it just
4265 // once in ActOnMemInitializers.
4266 return true;
4267 }
4268
4269 CXXRecordDecl *ClassDecl = Constructor->getParent();
4270
4271 // C++ [class.base.init]p2:
4272 // Names in a mem-initializer-id are looked up in the scope of the
4273 // constructor's class and, if not found in that scope, are looked
4274 // up in the scope containing the constructor's definition.
4275 // [Note: if the constructor's class contains a member with the
4276 // same name as a direct or virtual base class of the class, a
4277 // mem-initializer-id naming the member or base class and composed
4278 // of a single identifier refers to the class member. A
4279 // mem-initializer-id for the hidden base class may be specified
4280 // using a qualified name. ]
4281
4282 // Look for a member, first.
4283 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4284 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4285 if (EllipsisLoc.isValid())
4286 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4287 << MemberOrBase
4288 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4289
4290 return BuildMemberInitializer(Member, Init, IdLoc);
4291 }
4292 // It didn't name a member, so see if it names a class.
4293 QualType BaseType;
4294 TypeSourceInfo *TInfo = nullptr;
4295
4296 if (TemplateTypeTy) {
4297 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4298 if (BaseType.isNull())
4299 return true;
4300 } else if (DS.getTypeSpecType() == TST_decltype) {
4301 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4302 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4303 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4304 return true;
4305 } else {
4306 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4307 LookupParsedName(R, S, &SS);
4308
4309 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4310 if (!TyD) {
4311 if (R.isAmbiguous()) return true;
4312
4313 // We don't want access-control diagnostics here.
4314 R.suppressDiagnostics();
4315
4316 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4317 bool NotUnknownSpecialization = false;
4318 DeclContext *DC = computeDeclContext(SS, false);
4319 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4320 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4321
4322 if (!NotUnknownSpecialization) {
4323 // When the scope specifier can refer to a member of an unknown
4324 // specialization, we take it as a type name.
4325 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4326 SS.getWithLocInContext(Context),
4327 *MemberOrBase, IdLoc);
4328 if (BaseType.isNull())
4329 return true;
4330
4331 TInfo = Context.CreateTypeSourceInfo(BaseType);
4332 DependentNameTypeLoc TL =
4333 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4334 if (!TL.isNull()) {
4335 TL.setNameLoc(IdLoc);
4336 TL.setElaboratedKeywordLoc(SourceLocation());
4337 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4338 }
4339
4340 R.clear();
4341 R.setLookupName(MemberOrBase);
4342 }
4343 }
4344
4345 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4346 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4347 auto *TempSpec = cast<TemplateSpecializationType>(
4348 UnqualifiedBase->getInjectedClassNameSpecialization());
4349 TemplateName TN = TempSpec->getTemplateName();
4350 for (auto const &Base : ClassDecl->bases()) {
4351 auto BaseTemplate =
4352 Base.getType()->getAs<TemplateSpecializationType>();
4353 if (BaseTemplate && Context.hasSameTemplateName(
4354 BaseTemplate->getTemplateName(), TN)) {
4355 Diag(IdLoc, diag::ext_unqualified_base_class)
4356 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4357 BaseType = Base.getType();
4358 break;
4359 }
4360 }
4361 }
4362 }
4363
4364 // If no results were found, try to correct typos.
4365 TypoCorrection Corr;
4366 MemInitializerValidatorCCC CCC(ClassDecl);
4367 if (R.empty() && BaseType.isNull() &&
4368 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4369 CCC, CTK_ErrorRecovery, ClassDecl))) {
4370 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4371 // We have found a non-static data member with a similar
4372 // name to what was typed; complain and initialize that
4373 // member.
4374 diagnoseTypo(Corr,
4375 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4376 << MemberOrBase << true);
4377 return BuildMemberInitializer(Member, Init, IdLoc);
4378 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4379 const CXXBaseSpecifier *DirectBaseSpec;
4380 const CXXBaseSpecifier *VirtualBaseSpec;
4381 if (FindBaseInitializer(*this, ClassDecl,
4382 Context.getTypeDeclType(Type),
4383 DirectBaseSpec, VirtualBaseSpec)) {
4384 // We have found a direct or virtual base class with a
4385 // similar name to what was typed; complain and initialize
4386 // that base class.
4387 diagnoseTypo(Corr,
4388 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4389 << MemberOrBase << false,
4390 PDiag() /*Suppress note, we provide our own.*/);
4391
4392 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4393 : VirtualBaseSpec;
4394 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4395 << BaseSpec->getType() << BaseSpec->getSourceRange();
4396
4397 TyD = Type;
4398 }
4399 }
4400 }
4401
4402 if (!TyD && BaseType.isNull()) {
4403 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4404 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4405 return true;
4406 }
4407 }
4408
4409 if (BaseType.isNull()) {
4410 BaseType = getElaboratedType(ETK_None, SS, Context.getTypeDeclType(TyD));
4411 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4412 TInfo = Context.CreateTypeSourceInfo(BaseType);
4413 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4414 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4415 TL.setElaboratedKeywordLoc(SourceLocation());
4416 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4417 }
4418 }
4419
4420 if (!TInfo)
4421 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4422
4423 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4424}
4425
4426MemInitResult
4427Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4428 SourceLocation IdLoc) {
4429 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4430 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4431 assert((DirectMember || IndirectMember) &&(static_cast <bool> ((DirectMember || IndirectMember) &&
"Member must be a FieldDecl or IndirectFieldDecl") ? void (0
) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 4432, __extension__ __PRETTY_FUNCTION__
))
4432 "Member must be a FieldDecl or IndirectFieldDecl")(static_cast <bool> ((DirectMember || IndirectMember) &&
"Member must be a FieldDecl or IndirectFieldDecl") ? void (0
) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 4432, __extension__ __PRETTY_FUNCTION__
))
;
4433
4434 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4435 return true;
4436
4437 if (Member->isInvalidDecl())
4438 return true;
4439
4440 MultiExprArg Args;
4441 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4442 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4443 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4444 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4445 } else {
4446 // Template instantiation doesn't reconstruct ParenListExprs for us.
4447 Args = Init;
4448 }
4449
4450 SourceRange InitRange = Init->getSourceRange();
4451
4452 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4453 // Can't check initialization for a member of dependent type or when
4454 // any of the arguments are type-dependent expressions.
4455 DiscardCleanupsInEvaluationContext();
4456 } else {
4457 bool InitList = false;
4458 if (isa<InitListExpr>(Init)) {
4459 InitList = true;
4460 Args = Init;
4461 }
4462
4463 // Initialize the member.
4464 InitializedEntity MemberEntity =
4465 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4466 : InitializedEntity::InitializeMember(IndirectMember,
4467 nullptr);
4468 InitializationKind Kind =
4469 InitList ? InitializationKind::CreateDirectList(
4470 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4471 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4472 InitRange.getEnd());
4473
4474 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4475 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4476 nullptr);
4477 if (!MemberInit.isInvalid()) {
4478 // C++11 [class.base.init]p7:
4479 // The initialization of each base and member constitutes a
4480 // full-expression.
4481 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4482 /*DiscardedValue*/ false);
4483 }
4484
4485 if (MemberInit.isInvalid()) {
4486 // Args were sensible expressions but we couldn't initialize the member
4487 // from them. Preserve them in a RecoveryExpr instead.
4488 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4489 Member->getType())
4490 .get();
4491 if (!Init)
4492 return true;
4493 } else {
4494 Init = MemberInit.get();
4495 }
4496 }
4497
4498 if (DirectMember) {
4499 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4500 InitRange.getBegin(), Init,
4501 InitRange.getEnd());
4502 } else {
4503 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4504 InitRange.getBegin(), Init,
4505 InitRange.getEnd());
4506 }
4507}
4508
4509MemInitResult
4510Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4511 CXXRecordDecl *ClassDecl) {
4512 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4513 if (!LangOpts.CPlusPlus11)
4514 return Diag(NameLoc, diag::err_delegating_ctor)
4515 << TInfo->getTypeLoc().getSourceRange();
4516 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4517
4518 bool InitList = true;
4519 MultiExprArg Args = Init;
4520 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4521 InitList = false;
4522 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4523 }
4524
4525 SourceRange InitRange = Init->getSourceRange();
4526 // Initialize the object.
4527 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4528 QualType(ClassDecl->getTypeForDecl(), 0));
4529 InitializationKind Kind =
4530 InitList ? InitializationKind::CreateDirectList(
4531 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4532 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4533 InitRange.getEnd());
4534 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4535 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4536 Args, nullptr);
4537 if (!DelegationInit.isInvalid()) {
4538 assert((DelegationInit.get()->containsErrors() ||(static_cast <bool> ((DelegationInit.get()->containsErrors
() || cast<CXXConstructExpr>(DelegationInit.get())->
getConstructor()) && "Delegating constructor with no target?"
) ? void (0) : __assert_fail ("(DelegationInit.get()->containsErrors() || cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) && \"Delegating constructor with no target?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 4540, __extension__ __PRETTY_FUNCTION__
))
4539 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&(static_cast <bool> ((DelegationInit.get()->containsErrors
() || cast<CXXConstructExpr>(DelegationInit.get())->
getConstructor()) && "Delegating constructor with no target?"
) ? void (0) : __assert_fail ("(DelegationInit.get()->containsErrors() || cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) && \"Delegating constructor with no target?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 4540, __extension__ __PRETTY_FUNCTION__
))
4540 "Delegating constructor with no target?")(static_cast <bool> ((DelegationInit.get()->containsErrors
() || cast<CXXConstructExpr>(DelegationInit.get())->
getConstructor()) && "Delegating constructor with no target?"
) ? void (0) : __assert_fail ("(DelegationInit.get()->containsErrors() || cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) && \"Delegating constructor with no target?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 4540, __extension__ __PRETTY_FUNCTION__
))
;
4541
4542 // C++11 [class.base.init]p7:
4543 // The initialization of each base and member constitutes a
4544 // full-expression.
4545 DelegationInit = ActOnFinishFullExpr(
4546 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4547 }
4548
4549 if (DelegationInit.isInvalid()) {
4550 DelegationInit =
4551 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4552 QualType(ClassDecl->getTypeForDecl(), 0));
4553 if (DelegationInit.isInvalid())
4554 return true;
4555 } else {
4556 // If we are in a dependent context, template instantiation will
4557 // perform this type-checking again. Just save the arguments that we
4558 // received in a ParenListExpr.
4559 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4560 // of the information that we have about the base
4561 // initializer. However, deconstructing the ASTs is a dicey process,
4562 // and this approach is far more likely to get the corner cases right.
4563 if (CurContext->isDependentContext())
4564 DelegationInit = Init;
4565 }
4566
4567 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4568 DelegationInit.getAs<Expr>(),
4569 InitRange.getEnd());
4570}
4571
4572MemInitResult
4573Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4574 Expr *Init, CXXRecordDecl *ClassDecl,
4575 SourceLocation EllipsisLoc) {
4576 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4577
4578 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4579 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4580 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4581
4582 // C++ [class.base.init]p2:
4583 // [...] Unless the mem-initializer-id names a nonstatic data
4584 // member of the constructor's class or a direct or virtual base
4585 // of that class, the mem-initializer is ill-formed. A
4586 // mem-initializer-list can initialize a base class using any
4587 // name that denotes that base class type.
4588
4589 // We can store the initializers in "as-written" form and delay analysis until
4590 // instantiation if the constructor is dependent. But not for dependent
4591 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4592 bool Dependent = CurContext->isDependentContext() &&
4593 (BaseType->isDependentType() || Init->isTypeDependent());
4594
4595 SourceRange InitRange = Init->getSourceRange();
4596 if (EllipsisLoc.isValid()) {
4597 // This is a pack expansion.
4598 if (!BaseType->containsUnexpandedParameterPack()) {
4599 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4600 << SourceRange(BaseLoc, InitRange.getEnd());
4601
4602 EllipsisLoc = SourceLocation();
4603 }
4604 } else {
4605 // Check for any unexpanded parameter packs.
4606 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4607 return true;
4608
4609 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4610 return true;
4611 }
4612
4613 // Check for direct and virtual base classes.
4614 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4615 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4616 if (!Dependent) {
4617 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4618 BaseType))
4619 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4620
4621 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4622 VirtualBaseSpec);
4623
4624 // C++ [base.class.init]p2:
4625 // Unless the mem-initializer-id names a nonstatic data member of the
4626 // constructor's class or a direct or virtual base of that class, the
4627 // mem-initializer is ill-formed.
4628 if (!DirectBaseSpec && !VirtualBaseSpec) {
4629 // If the class has any dependent bases, then it's possible that
4630 // one of those types will resolve to the same type as
4631 // BaseType. Therefore, just treat this as a dependent base
4632 // class initialization. FIXME: Should we try to check the
4633 // initialization anyway? It seems odd.
4634 if (ClassDecl->hasAnyDependentBases())
4635 Dependent = true;
4636 else
4637 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4638 << BaseType << Context.getTypeDeclType(ClassDecl)
4639 << BaseTInfo->getTypeLoc().getSourceRange();
4640 }
4641 }
4642
4643 if (Dependent) {
4644 DiscardCleanupsInEvaluationContext();
4645
4646 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4647 /*IsVirtual=*/false,
4648 InitRange.getBegin(), Init,
4649 InitRange.getEnd(), EllipsisLoc);
4650 }
4651
4652 // C++ [base.class.init]p2:
4653 // If a mem-initializer-id is ambiguous because it designates both
4654 // a direct non-virtual base class and an inherited virtual base
4655 // class, the mem-initializer is ill-formed.
4656 if (DirectBaseSpec && VirtualBaseSpec)
4657 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4658 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4659
4660 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4661 if (!BaseSpec)
4662 BaseSpec = VirtualBaseSpec;
4663
4664 // Initialize the base.
4665 bool InitList = true;
4666 MultiExprArg Args = Init;
4667 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4668 InitList = false;
4669 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4670 }
4671
4672 InitializedEntity BaseEntity =
4673 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4674 InitializationKind Kind =
4675 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4676 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4677 InitRange.getEnd());
4678 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4679 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4680 if (!BaseInit.isInvalid()) {
4681 // C++11 [class.base.init]p7:
4682 // The initialization of each base and member constitutes a
4683 // full-expression.
4684 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4685 /*DiscardedValue*/ false);
4686 }
4687
4688 if (BaseInit.isInvalid()) {
4689 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4690 Args, BaseType);
4691 if (BaseInit.isInvalid())
4692 return true;
4693 } else {
4694 // If we are in a dependent context, template instantiation will
4695 // perform this type-checking again. Just save the arguments that we
4696 // received in a ParenListExpr.
4697 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4698 // of the information that we have about the base
4699 // initializer. However, deconstructing the ASTs is a dicey process,
4700 // and this approach is far more likely to get the corner cases right.
4701 if (CurContext->isDependentContext())
4702 BaseInit = Init;
4703 }
4704
4705 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4706 BaseSpec->isVirtual(),
4707 InitRange.getBegin(),
4708 BaseInit.getAs<Expr>(),
4709 InitRange.getEnd(), EllipsisLoc);
4710}
4711
4712// Create a static_cast\<T&&>(expr).
4713static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4714 QualType TargetType =
4715 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4716 SourceLocation(), DeclarationName());
4717 SourceLocation ExprLoc = E->getBeginLoc();
4718 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4719 TargetType, ExprLoc);
4720
4721 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4722 SourceRange(ExprLoc, ExprLoc),
4723 E->getSourceRange()).get();
4724}
4725
4726/// ImplicitInitializerKind - How an implicit base or member initializer should
4727/// initialize its base or member.
4728enum ImplicitInitializerKind {
4729 IIK_Default,
4730 IIK_Copy,
4731 IIK_Move,
4732 IIK_Inherit
4733};
4734
4735static bool
4736BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4737 ImplicitInitializerKind ImplicitInitKind,
4738 CXXBaseSpecifier *BaseSpec,
4739 bool IsInheritedVirtualBase,
4740 CXXCtorInitializer *&CXXBaseInit) {
4741 InitializedEntity InitEntity
4742 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4743 IsInheritedVirtualBase);
4744
4745 ExprResult BaseInit;
4746
4747 switch (ImplicitInitKind) {
4748 case IIK_Inherit:
4749 case IIK_Default: {
4750 InitializationKind InitKind
4751 = InitializationKind::CreateDefault(Constructor->getLocation());
4752 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4753 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4754 break;
4755 }
4756
4757 case IIK_Move:
4758 case IIK_Copy: {
4759 bool Moving = ImplicitInitKind == IIK_Move;
4760 ParmVarDecl *Param = Constructor->getParamDecl(0);
4761 QualType ParamType = Param->getType().getNonReferenceType();
4762
4763 Expr *CopyCtorArg =
4764 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4765 SourceLocation(), Param, false,
4766 Constructor->getLocation(), ParamType,
4767 VK_LValue, nullptr);
4768
4769 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4770
4771 // Cast to the base class to avoid ambiguities.
4772 QualType ArgTy =
4773 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4774 ParamType.getQualifiers());
4775
4776 if (Moving) {
4777 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4778 }
4779
4780 CXXCastPath BasePath;
4781 BasePath.push_back(BaseSpec);
4782 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4783 CK_UncheckedDerivedToBase,
4784 Moving ? VK_XValue : VK_LValue,
4785 &BasePath).get();
4786
4787 InitializationKind InitKind
4788 = InitializationKind::CreateDirect(Constructor->getLocation(),
4789 SourceLocation(), SourceLocation());
4790 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4791 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4792 break;
4793 }
4794 }
4795
4796 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4797 if (BaseInit.isInvalid())
4798 return true;
4799
4800 CXXBaseInit =
4801 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4802 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4803 SourceLocation()),
4804 BaseSpec->isVirtual(),
4805 SourceLocation(),
4806 BaseInit.getAs<Expr>(),
4807 SourceLocation(),
4808 SourceLocation());
4809
4810 return false;
4811}
4812
4813static bool RefersToRValueRef(Expr *MemRef) {
4814 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4815 return Referenced->getType()->isRValueReferenceType();
4816}
4817
4818static bool
4819BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4820 ImplicitInitializerKind ImplicitInitKind,
4821 FieldDecl *Field, IndirectFieldDecl *Indirect,
4822 CXXCtorInitializer *&CXXMemberInit) {
4823 if (Field->isInvalidDecl())
4824 return true;
4825
4826 SourceLocation Loc = Constructor->getLocation();
4827
4828 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4829 bool Moving = ImplicitInitKind == IIK_Move;
4830 ParmVarDecl *Param = Constructor->getParamDecl(0);
4831 QualType ParamType = Param->getType().getNonReferenceType();
4832
4833 // Suppress copying zero-width bitfields.
4834 if (Field->isZeroLengthBitField(SemaRef.Context))
4835 return false;
4836
4837 Expr *MemberExprBase =
4838 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4839 SourceLocation(), Param, false,
4840 Loc, ParamType, VK_LValue, nullptr);
4841
4842 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4843
4844 if (Moving) {
4845 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4846 }
4847
4848 // Build a reference to this field within the parameter.
4849 CXXScopeSpec SS;
4850 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4851 Sema::LookupMemberName);
4852 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4853 : cast<ValueDecl>(Field), AS_public);
4854 MemberLookup.resolveKind();
4855 ExprResult CtorArg
4856 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4857 ParamType, Loc,
4858 /*IsArrow=*/false,
4859 SS,
4860 /*TemplateKWLoc=*/SourceLocation(),
4861 /*FirstQualifierInScope=*/nullptr,
4862 MemberLookup,
4863 /*TemplateArgs=*/nullptr,
4864 /*S*/nullptr);
4865 if (CtorArg.isInvalid())
4866 return true;
4867
4868 // C++11 [class.copy]p15:
4869 // - if a member m has rvalue reference type T&&, it is direct-initialized
4870 // with static_cast<T&&>(x.m);
4871 if (RefersToRValueRef(CtorArg.get())) {
4872 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4873 }
4874
4875 InitializedEntity Entity =
4876 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4877 /*Implicit*/ true)
4878 : InitializedEntity::InitializeMember(Field, nullptr,
4879 /*Implicit*/ true);
4880
4881 // Direct-initialize to use the copy constructor.
4882 InitializationKind InitKind =
4883 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4884
4885 Expr *CtorArgE = CtorArg.getAs<Expr>();
4886 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4887 ExprResult MemberInit =
4888 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4889 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4890 if (MemberInit.isInvalid())
4891 return true;
4892
4893 if (Indirect)
4894 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4895 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4896 else
4897 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4898 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4899 return false;
4900 }
4901
4902 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&(static_cast <bool> ((ImplicitInitKind == IIK_Default ||
ImplicitInitKind == IIK_Inherit) && "Unhandled implicit init kind!"
) ? void (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 4903, __extension__ __PRETTY_FUNCTION__
))
4903 "Unhandled implicit init kind!")(static_cast <bool> ((ImplicitInitKind == IIK_Default ||
ImplicitInitKind == IIK_Inherit) && "Unhandled implicit init kind!"
) ? void (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 4903, __extension__ __PRETTY_FUNCTION__
))
;
4904
4905 QualType FieldBaseElementType =
4906 SemaRef.Context.getBaseElementType(Field->getType());
4907
4908 if (FieldBaseElementType->isRecordType()) {
4909 InitializedEntity InitEntity =
4910 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4911 /*Implicit*/ true)
4912 : InitializedEntity::InitializeMember(Field, nullptr,
4913 /*Implicit*/ true);
4914 InitializationKind InitKind =
4915 InitializationKind::CreateDefault(Loc);
4916
4917 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4918 ExprResult MemberInit =
4919 InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4920
4921 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4922 if (MemberInit.isInvalid())
4923 return true;
4924
4925 if (Indirect)
4926 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4927 Indirect, Loc,
4928 Loc,
4929 MemberInit.get(),
4930 Loc);
4931 else
4932 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4933 Field, Loc, Loc,
4934 MemberInit.get(),
4935 Loc);
4936 return false;
4937 }
4938
4939 if (!Field->getParent()->isUnion()) {
4940 if (FieldBaseElementType->isReferenceType()) {
4941 SemaRef.Diag(Constructor->getLocation(),
4942 diag::err_uninitialized_member_in_ctor)
4943 << (int)Constructor->isImplicit()
4944 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4945 << 0 << Field->getDeclName();
4946 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4947 return true;
4948 }
4949
4950 if (FieldBaseElementType.isConstQualified()) {
4951 SemaRef.Diag(Constructor->getLocation(),
4952 diag::err_uninitialized_member_in_ctor)
4953 << (int)Constructor->isImplicit()
4954 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4955 << 1 << Field->getDeclName();
4956 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4957 return true;
4958 }
4959 }
4960
4961 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4962 // ARC and Weak:
4963 // Default-initialize Objective-C pointers to NULL.
4964 CXXMemberInit
4965 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4966 Loc, Loc,
4967 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4968 Loc);
4969 return false;
4970 }
4971
4972 // Nothing to initialize.
4973 CXXMemberInit = nullptr;
4974 return false;
4975}
4976
4977namespace {
4978struct BaseAndFieldInfo {
4979 Sema &S;
4980 CXXConstructorDecl *Ctor;
4981 bool AnyErrorsInInits;
4982 ImplicitInitializerKind IIK;
4983 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4984 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4985 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4986
4987 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4988 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4989 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4990 if (Ctor->getInheritedConstructor())
4991 IIK = IIK_Inherit;
4992 else if (Generated && Ctor->isCopyConstructor())
4993 IIK = IIK_Copy;
4994 else if (Generated && Ctor->isMoveConstructor())
4995 IIK = IIK_Move;
4996 else
4997 IIK = IIK_Default;
4998 }
4999
5000 bool isImplicitCopyOrMove() const {
5001 switch (IIK) {
5002 case IIK_Copy:
5003 case IIK_Move:
5004 return true;
5005
5006 case IIK_Default:
5007 case IIK_Inherit:
5008 return false;
5009 }
5010
5011 llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!"
, "clang/lib/Sema/SemaDeclCXX.cpp", 5011)
;
5012 }
5013
5014 bool addFieldInitializer(CXXCtorInitializer *Init) {
5015 AllToInit.push_back(Init);
5016
5017 // Check whether this initializer makes the field "used".
5018 if (Init->getInit()->HasSideEffects(S.Context))
5019 S.UnusedPrivateFields.remove(Init->getAnyMember());
5020
5021 return false;
5022 }
5023
5024 bool isInactiveUnionMember(FieldDecl *Field) {
5025 RecordDecl *Record = Field->getParent();
5026 if (!Record->isUnion())
5027 return false;
5028
5029 if (FieldDecl *Active =
5030 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
5031 return Active != Field->getCanonicalDecl();
5032
5033 // In an implicit copy or move constructor, ignore any in-class initializer.
5034 if (isImplicitCopyOrMove())
5035 return true;
5036
5037 // If there's no explicit initialization, the field is active only if it
5038 // has an in-class initializer...
5039 if (Field->hasInClassInitializer())
5040 return false;
5041 // ... or it's an anonymous struct or union whose class has an in-class
5042 // initializer.
5043 if (!Field->isAnonymousStructOrUnion())
5044 return true;
5045 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5046 return !FieldRD->hasInClassInitializer();
5047 }
5048
5049 /// Determine whether the given field is, or is within, a union member
5050 /// that is inactive (because there was an initializer given for a different
5051 /// member of the union, or because the union was not initialized at all).
5052 bool isWithinInactiveUnionMember(FieldDecl *Field,
5053 IndirectFieldDecl *Indirect) {
5054 if (!Indirect)
5055 return isInactiveUnionMember(Field);
5056
5057 for (auto *C : Indirect->chain()) {
5058 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5059 if (Field && isInactiveUnionMember(Field))
5060 return true;
5061 }
5062 return false;
5063 }
5064};
5065}
5066
5067/// Determine whether the given type is an incomplete or zero-lenfgth
5068/// array type.
5069static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5070 if (T->isIncompleteArrayType())
5071 return true;
5072
5073 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5074 if (!ArrayT->getSize())
5075 return true;
5076
5077 T = ArrayT->getElementType();
5078 }
5079
5080 return false;
5081}
5082
5083static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5084 FieldDecl *Field,
5085 IndirectFieldDecl *Indirect = nullptr) {
5086 if (Field->isInvalidDecl())
5087 return false;
5088
5089 // Overwhelmingly common case: we have a direct initializer for this field.
5090 if (CXXCtorInitializer *Init =
5091 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5092 return Info.addFieldInitializer(Init);
5093
5094 // C++11 [class.base.init]p8:
5095 // if the entity is a non-static data member that has a
5096 // brace-or-equal-initializer and either
5097 // -- the constructor's class is a union and no other variant member of that
5098 // union is designated by a mem-initializer-id or
5099 // -- the constructor's class is not a union, and, if the entity is a member
5100 // of an anonymous union, no other member of that union is designated by
5101 // a mem-initializer-id,
5102 // the entity is initialized as specified in [dcl.init].
5103 //
5104 // We also apply the same rules to handle anonymous structs within anonymous
5105 // unions.
5106 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5107 return false;
5108
5109 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5110 ExprResult DIE =
5111 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5112 if (DIE.isInvalid())
5113 return true;
5114
5115 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5116 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5117
5118 CXXCtorInitializer *Init;
5119 if (Indirect)
5120 Init = new (SemaRef.Context)
5121 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5122 SourceLocation(), DIE.get(), SourceLocation());
5123 else
5124 Init = new (SemaRef.Context)
5125 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5126 SourceLocation(), DIE.get(), SourceLocation());
5127 return Info.addFieldInitializer(Init);
5128 }
5129
5130 // Don't initialize incomplete or zero-length arrays.
5131 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5132 return false;
5133
5134 // Don't try to build an implicit initializer if there were semantic
5135 // errors in any of the initializers (and therefore we might be
5136 // missing some that the user actually wrote).
5137 if (Info.AnyErrorsInInits)
5138 return false;
5139
5140 CXXCtorInitializer *Init = nullptr;
5141 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5142 Indirect, Init))
5143 return true;
5144
5145 if (!Init)
5146 return false;
5147
5148 return Info.addFieldInitializer(Init);
5149}
5150
5151bool
5152Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5153 CXXCtorInitializer *Initializer) {
5154 assert(Initializer->isDelegatingInitializer())(static_cast <bool> (Initializer->isDelegatingInitializer
()) ? void (0) : __assert_fail ("Initializer->isDelegatingInitializer()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 5154, __extension__ __PRETTY_FUNCTION__
))
;
5155 Constructor->setNumCtorInitializers(1);
5156 CXXCtorInitializer **initializer =
5157 new (Context) CXXCtorInitializer*[1];
5158 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5159 Constructor->setCtorInitializers(initializer);
5160
5161 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5162 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5163 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5164 }
5165
5166 DelegatingCtorDecls.push_back(Constructor);
5167
5168 DiagnoseUninitializedFields(*this, Constructor);
5169
5170 return false;
5171}
5172
5173bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5174 ArrayRef<CXXCtorInitializer *> Initializers) {
5175 if (Constructor->isDependentContext()) {
5176 // Just store the initializers as written, they will be checked during
5177 // instantiation.
5178 if (!Initializers.empty()) {
5179 Constructor->setNumCtorInitializers(Initializers.size());
5180 CXXCtorInitializer **baseOrMemberInitializers =
5181 new (Context) CXXCtorInitializer*[Initializers.size()];
5182 memcpy(baseOrMemberInitializers, Initializers.data(),
5183 Initializers.size() * sizeof(CXXCtorInitializer*));
5184 Constructor->setCtorInitializers(baseOrMemberInitializers);
5185 }
5186
5187 // Let template instantiation know whether we had errors.
5188 if (AnyErrors)
5189 Constructor->setInvalidDecl();
5190
5191 return false;
5192 }
5193
5194 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5195
5196 // We need to build the initializer AST according to order of construction
5197 // and not what user specified in the Initializers list.
5198 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5199 if (!ClassDecl)
5200 return true;
5201
5202 bool HadError = false;
5203
5204 for (unsigned i = 0; i < Initializers.size(); i++) {
5205 CXXCtorInitializer *Member = Initializers[i];
5206
5207 if (Member->isBaseInitializer())
5208 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5209 else {
5210 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5211
5212 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5213 for (auto *C : F->chain()) {
5214 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5215 if (FD && FD->getParent()->isUnion())
5216 Info.ActiveUnionMember.insert(std::make_pair(
5217 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5218 }
5219 } else if (FieldDecl *FD = Member->getMember()) {
5220 if (FD->getParent()->isUnion())
5221 Info.ActiveUnionMember.insert(std::make_pair(
5222 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5223 }
5224 }
5225 }
5226
5227 // Keep track of the direct virtual bases.
5228 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5229 for (auto &I : ClassDecl->bases()) {
5230 if (I.isVirtual())
5231 DirectVBases.insert(&I);
5232 }
5233
5234 // Push virtual bases before others.
5235 for (auto &VBase : ClassDecl->vbases()) {
5236 if (CXXCtorInitializer *Value
5237 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5238 // [class.base.init]p7, per DR257:
5239 // A mem-initializer where the mem-initializer-id names a virtual base
5240 // class is ignored during execution of a constructor of any class that
5241 // is not the most derived class.
5242 if (ClassDecl->isAbstract()) {
5243 // FIXME: Provide a fixit to remove the base specifier. This requires
5244 // tracking the location of the associated comma for a base specifier.
5245 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5246 << VBase.getType() << ClassDecl;
5247 DiagnoseAbstractType(ClassDecl);
5248 }
5249
5250 Info.AllToInit.push_back(Value);
5251 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5252 // [class.base.init]p8, per DR257:
5253 // If a given [...] base class is not named by a mem-initializer-id
5254 // [...] and the entity is not a virtual base class of an abstract
5255 // class, then [...] the entity is default-initialized.
5256 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5257 CXXCtorInitializer *CXXBaseInit;
5258 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5259 &VBase, IsInheritedVirtualBase,
5260 CXXBaseInit)) {
5261 HadError = true;
5262 continue;
5263 }
5264
5265 Info.AllToInit.push_back(CXXBaseInit);
5266 }
5267 }
5268
5269 // Non-virtual bases.
5270 for (auto &Base : ClassDecl->bases()) {
5271 // Virtuals are in the virtual base list and already constructed.
5272 if (Base.isVirtual())
5273 continue;
5274
5275 if (CXXCtorInitializer *Value
5276 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5277 Info.AllToInit.push_back(Value);
5278 } else if (!AnyErrors) {
5279 CXXCtorInitializer *CXXBaseInit;
5280 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5281 &Base, /*IsInheritedVirtualBase=*/false,
5282 CXXBaseInit)) {
5283 HadError = true;
5284 continue;
5285 }
5286
5287 Info.AllToInit.push_back(CXXBaseInit);
5288 }
5289 }
5290
5291 // Fields.
5292 for (auto *Mem : ClassDecl->decls()) {
5293 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5294 // C++ [class.bit]p2:
5295 // A declaration for a bit-field that omits the identifier declares an
5296 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5297 // initialized.
5298 if (F->isUnnamedBitfield())
5299 continue;
5300
5301 // If we're not generating the implicit copy/move constructor, then we'll
5302 // handle anonymous struct/union fields based on their individual
5303 // indirect fields.
5304 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5305 continue;
5306
5307 if (CollectFieldInitializer(*this, Info, F))
5308 HadError = true;
5309 continue;
5310 }
5311
5312 // Beyond this point, we only consider default initialization.
5313 if (Info.isImplicitCopyOrMove())
5314 continue;
5315
5316 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5317 if (F->getType()->isIncompleteArrayType()) {
5318 assert(ClassDecl->hasFlexibleArrayMember() &&(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 5319, __extension__ __PRETTY_FUNCTION__
))
5319 "Incomplete array type is not valid")(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 5319, __extension__ __PRETTY_FUNCTION__
))
;
5320 continue;
5321 }
5322
5323 // Initialize each field of an anonymous struct individually.
5324 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5325 HadError = true;
5326
5327 continue;
5328 }
5329 }
5330
5331 unsigned NumInitializers = Info.AllToInit.size();
5332 if (NumInitializers > 0) {
5333 Constructor->setNumCtorInitializers(NumInitializers);
5334 CXXCtorInitializer **baseOrMemberInitializers =
5335 new (Context) CXXCtorInitializer*[NumInitializers];
5336 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5337 NumInitializers * sizeof(CXXCtorInitializer*));
5338 Constructor->setCtorInitializers(baseOrMemberInitializers);
5339
5340 // Constructors implicitly reference the base and member
5341 // destructors.
5342 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5343 Constructor->getParent());
5344 }
5345
5346 return HadError;
5347}
5348
5349static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5350 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5351 const RecordDecl *RD = RT->getDecl();
5352 if (RD->isAnonymousStructOrUnion()) {
5353 for (auto *Field : RD->fields())
5354 PopulateKeysForFields(Field, IdealInits);
5355 return;
5356 }
5357 }
5358 IdealInits.push_back(Field->getCanonicalDecl());
5359}
5360
5361static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5362 return Context.getCanonicalType(BaseType).getTypePtr();
5363}
5364
5365static const void *GetKeyForMember(ASTContext &Context,
5366 CXXCtorInitializer *Member) {
5367 if (!Member->isAnyMemberInitializer())
5368 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5369
5370 return Member->getAnyMember()->getCanonicalDecl();
5371}
5372
5373static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5374 const CXXCtorInitializer *Previous,
5375 const CXXCtorInitializer *Current) {
5376 if (Previous->isAnyMemberInitializer())
5377 Diag << 0 << Previous->getAnyMember();
5378 else
5379 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5380
5381 if (Current->isAnyMemberInitializer())
5382 Diag << 0 << Current->getAnyMember();
5383 else
5384 Diag << 1 << Current->getTypeSourceInfo()->getType();
5385}
5386
5387static void DiagnoseBaseOrMemInitializerOrder(
5388 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5389 ArrayRef<CXXCtorInitializer *> Inits) {
5390 if (Constructor->getDeclContext()->isDependentContext())
5391 return;
5392
5393 // Don't check initializers order unless the warning is enabled at the
5394 // location of at least one initializer.
5395 bool ShouldCheckOrder = false;
5396 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5397 CXXCtorInitializer *Init = Inits[InitIndex];
5398 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5399 Init->getSourceLocation())) {
5400 ShouldCheckOrder = true;
5401 break;
5402 }
5403 }
5404 if (!ShouldCheckOrder)
5405 return;
5406
5407 // Build the list of bases and members in the order that they'll
5408 // actually be initialized. The explicit initializers should be in
5409 // this same order but may be missing things.
5410 SmallVector<const void*, 32> IdealInitKeys;
5411
5412 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5413
5414 // 1. Virtual bases.
5415 for (const auto &VBase : ClassDecl->vbases())
5416 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5417
5418 // 2. Non-virtual bases.
5419 for (const auto &Base : ClassDecl->bases()) {
5420 if (Base.isVirtual())
5421 continue;
5422 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5423 }
5424
5425 // 3. Direct fields.
5426 for (auto *Field : ClassDecl->fields()) {
5427 if (Field->isUnnamedBitfield())
5428 continue;
5429
5430 PopulateKeysForFields(Field, IdealInitKeys);
5431 }
5432
5433 unsigned NumIdealInits = IdealInitKeys.size();
5434 unsigned IdealIndex = 0;
5435
5436 // Track initializers that are in an incorrect order for either a warning or
5437 // note if multiple ones occur.
5438 SmallVector<unsigned> WarnIndexes;
5439 // Correlates the index of an initializer in the init-list to the index of
5440 // the field/base in the class.
5441 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5442
5443 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5444 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5445
5446 // Scan forward to try to find this initializer in the idealized
5447 // initializers list.
5448 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5449 if (InitKey == IdealInitKeys[IdealIndex])
5450 break;
5451
5452 // If we didn't find this initializer, it must be because we
5453 // scanned past it on a previous iteration. That can only
5454 // happen if we're out of order; emit a warning.
5455 if (IdealIndex == NumIdealInits && InitIndex) {
5456 WarnIndexes.push_back(InitIndex);
5457
5458 // Move back to the initializer's location in the ideal list.
5459 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5460 if (InitKey == IdealInitKeys[IdealIndex])
5461 break;
5462
5463 assert(IdealIndex < NumIdealInits &&(static_cast <bool> (IdealIndex < NumIdealInits &&
"initializer not found in initializer list") ? void (0) : __assert_fail
("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 5464, __extension__ __PRETTY_FUNCTION__
))
5464 "initializer not found in initializer list")(static_cast <bool> (IdealIndex < NumIdealInits &&
"initializer not found in initializer list") ? void (0) : __assert_fail
("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 5464, __extension__ __PRETTY_FUNCTION__
))
;
5465 }
5466 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5467 }
5468
5469 if (WarnIndexes.empty())
5470 return;
5471
5472 // Sort based on the ideal order, first in the pair.
5473 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5474
5475 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5476 // emit the diagnostic before we can try adding notes.
5477 {
5478 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5479 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5480 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5481 : diag::warn_some_initializers_out_of_order);
5482
5483 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5484 if (CorrelatedInitOrder[I].second == I)
5485 continue;
5486 // Ideally we would be using InsertFromRange here, but clang doesn't
5487 // appear to handle InsertFromRange correctly when the source range is
5488 // modified by another fix-it.
5489 D << FixItHint::CreateReplacement(
5490 Inits[I]->getSourceRange(),
5491 Lexer::getSourceText(
5492 CharSourceRange::getTokenRange(
5493 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5494 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5495 }
5496
5497 // If there is only 1 item out of order, the warning expects the name and
5498 // type of each being added to it.
5499 if (WarnIndexes.size() == 1) {
5500 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5501 Inits[WarnIndexes.front()]);
5502 return;
5503 }
5504 }
5505 // More than 1 item to warn, create notes letting the user know which ones
5506 // are bad.
5507 for (unsigned WarnIndex : WarnIndexes) {
5508 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5509 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5510 diag::note_initializer_out_of_order);
5511 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5512 D << PrevInit->getSourceRange();
5513 }
5514}
5515
5516namespace {
5517bool CheckRedundantInit(Sema &S,
5518 CXXCtorInitializer *Init,
5519 CXXCtorInitializer *&PrevInit) {
5520 if (!PrevInit) {
5521 PrevInit = Init;
5522 return false;
5523 }
5524
5525 if (FieldDecl *Field = Init->getAnyMember())
5526 S.Diag(Init->getSourceLocation(),
5527 diag::err_multiple_mem_initialization)
5528 << Field->getDeclName()
5529 << Init->getSourceRange();
5530 else {
5531 const Type *BaseClass = Init->getBaseClass();
5532 assert(BaseClass && "neither field nor base")(static_cast <bool> (BaseClass && "neither field nor base"
) ? void (0) : __assert_fail ("BaseClass && \"neither field nor base\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 5532, __extension__ __PRETTY_FUNCTION__
))
;
5533 S.Diag(Init->getSourceLocation(),
5534 diag::err_multiple_base_initialization)
5535 << QualType(BaseClass, 0)
5536 << Init->getSourceRange();
5537 }
5538 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5539 << 0 << PrevInit->getSourceRange();
5540
5541 return true;
5542}
5543
5544typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5545typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5546
5547bool CheckRedundantUnionInit(Sema &S,
5548 CXXCtorInitializer *Init,
5549 RedundantUnionMap &Unions) {
5550 FieldDecl *Field = Init->getAnyMember();
5551 RecordDecl *Parent = Field->getParent();
5552 NamedDecl *Child = Field;
5553
5554 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5555 if (Parent->isUnion()) {
5556 UnionEntry &En = Unions[Parent];
5557 if (En.first && En.first != Child) {
5558 S.Diag(Init->getSourceLocation(),
5559 diag::err_multiple_mem_union_initialization)
5560 << Field->getDeclName()
5561 << Init->getSourceRange();
5562 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5563 << 0 << En.second->getSourceRange();
5564 return true;
5565 }
5566 if (!En.first) {
5567 En.first = Child;
5568 En.second = Init;
5569 }
5570 if (!Parent->isAnonymousStructOrUnion())
5571 return false;
5572 }
5573
5574 Child = Parent;
5575 Parent = cast<RecordDecl>(Parent->getDeclContext());
5576 }
5577
5578 return false;
5579}
5580} // namespace
5581
5582/// ActOnMemInitializers - Handle the member initializers for a constructor.
5583void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5584 SourceLocation ColonLoc,
5585 ArrayRef<CXXCtorInitializer*> MemInits,
5586 bool AnyErrors) {
5587 if (!ConstructorDecl)
5588 return;
5589
5590 AdjustDeclIfTemplate(ConstructorDecl);
5591
5592 CXXConstructorDecl *Constructor
5593 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5594
5595 if (!Constructor) {
5596 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5597 return;
5598 }
5599
5600 // Mapping for the duplicate initializers check.
5601 // For member initializers, this is keyed with a FieldDecl*.
5602 // For base initializers, this is keyed with a Type*.
5603 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5604
5605 // Mapping for the inconsistent anonymous-union initializers check.
5606 RedundantUnionMap MemberUnions;
5607
5608 bool HadError = false;
5609 for (unsigned i = 0; i < MemInits.size(); i++) {
5610 CXXCtorInitializer *Init = MemInits[i];
5611
5612 // Set the source order index.
5613 Init->setSourceOrder(i);
5614
5615 if (Init->isAnyMemberInitializer()) {
5616 const void *Key = GetKeyForMember(Context, Init);
5617 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5618 CheckRedundantUnionInit(*this, Init, MemberUnions))
5619 HadError = true;
5620 } else if (Init->isBaseInitializer()) {
5621 const void *Key = GetKeyForMember(Context, Init);
5622 if (CheckRedundantInit(*this, Init, Members[Key]))
5623 HadError = true;
5624 } else {
5625 assert(Init->isDelegatingInitializer())(static_cast <bool> (Init->isDelegatingInitializer()
) ? void (0) : __assert_fail ("Init->isDelegatingInitializer()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 5625, __extension__ __PRETTY_FUNCTION__
))
;
5626 // This must be the only initializer
5627 if (MemInits.size() != 1) {
5628 Diag(Init->getSourceLocation(),
5629 diag::err_delegating_initializer_alone)
5630 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5631 // We will treat this as being the only initializer.
5632 }
5633 SetDelegatingInitializer(Constructor, MemInits[i]);
5634 // Return immediately as the initializer is set.
5635 return;
5636 }
5637 }
5638
5639 if (HadError)
5640 return;
5641
5642 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5643
5644 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5645
5646 DiagnoseUninitializedFields(*this, Constructor);
5647}
5648
5649void
5650Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5651 CXXRecordDecl *ClassDecl) {
5652 // Ignore dependent contexts. Also ignore unions, since their members never
5653 // have destructors implicitly called.
5654 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5655 return;
5656
5657 // FIXME: all the access-control diagnostics are positioned on the
5658 // field/base declaration. That's probably good; that said, the
5659 // user might reasonably want to know why the destructor is being
5660 // emitted, and we currently don't say.
5661
5662 // Non-static data members.
5663 for (auto *Field : ClassDecl->fields()) {
5664 if (Field->isInvalidDecl())
5665 continue;
5666
5667 // Don't destroy incomplete or zero-length arrays.
5668 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5669 continue;
5670
5671 QualType FieldType = Context.getBaseElementType(Field->getType());
5672
5673 const RecordType* RT = FieldType->getAs<RecordType>();
5674 if (!RT)
5675 continue;
5676
5677 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5678 if (FieldClassDecl->isInvalidDecl())
5679 continue;
5680 if (FieldClassDecl->hasIrrelevantDestructor())
5681 continue;
5682 // The destructor for an implicit anonymous union member is never invoked.
5683 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5684 continue;
5685
5686 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5687 // Dtor might still be missing, e.g because it's invalid.
5688 if (!Dtor)
5689 continue;
5690 CheckDestructorAccess(Field->getLocation(), Dtor,
5691 PDiag(diag::err_access_dtor_field)
5692 << Field->getDeclName()
5693 << FieldType);
5694
5695 MarkFunctionReferenced(Location, Dtor);
5696 DiagnoseUseOfDecl(Dtor, Location);
5697 }
5698
5699 // We only potentially invoke the destructors of potentially constructed
5700 // subobjects.
5701 bool VisitVirtualBases = !ClassDecl->isAbstract();
5702
5703 // If the destructor exists and has already been marked used in the MS ABI,
5704 // then virtual base destructors have already been checked and marked used.
5705 // Skip checking them again to avoid duplicate diagnostics.
5706 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5707 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5708 if (Dtor && Dtor->isUsed())
5709 VisitVirtualBases = false;
5710 }
5711
5712 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5713
5714 // Bases.
5715 for (const auto &Base : ClassDecl->bases()) {
5716 const RecordType *RT = Base.getType()->getAs<RecordType>();
5717 if (!RT)
5718 continue;
5719
5720 // Remember direct virtual bases.
5721 if (Base.isVirtual()) {
5722 if (!VisitVirtualBases)
5723 continue;
5724 DirectVirtualBases.insert(RT);
5725 }
5726
5727 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5728 // If our base class is invalid, we probably can't get its dtor anyway.
5729 if (BaseClassDecl->isInvalidDecl())
5730 continue;
5731 if (BaseClassDecl->hasIrrelevantDestructor())
5732 continue;
5733
5734 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5735 // Dtor might still be missing, e.g because it's invalid.
5736 if (!Dtor)
5737 continue;
5738
5739 // FIXME: caret should be on the start of the class name
5740 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5741 PDiag(diag::err_access_dtor_base)
5742 << Base.getType() << Base.getSourceRange(),
5743 Context.getTypeDeclType(ClassDecl));
5744
5745 MarkFunctionReferenced(Location, Dtor);
5746 DiagnoseUseOfDecl(Dtor, Location);
5747 }
5748
5749 if (VisitVirtualBases)
5750 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5751 &DirectVirtualBases);
5752}
5753
5754void Sema::MarkVirtualBaseDestructorsReferenced(
5755 SourceLocation Location, CXXRecordDecl *ClassDecl,
5756 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5757 // Virtual bases.
5758 for (const auto &VBase : ClassDecl->vbases()) {
5759 // Bases are always records in a well-formed non-dependent class.
5760 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5761
5762 // Ignore already visited direct virtual bases.
5763 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5764 continue;
5765
5766 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5767 // If our base class is invalid, we probably can't get its dtor anyway.
5768 if (BaseClassDecl->isInvalidDecl())
5769 continue;
5770 if (BaseClassDecl->hasIrrelevantDestructor())
5771 continue;
5772
5773 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5774 // Dtor might still be missing, e.g because it's invalid.
5775 if (!Dtor)
5776 continue;
5777 if (CheckDestructorAccess(
5778 ClassDecl->getLocation(), Dtor,
5779 PDiag(diag::err_access_dtor_vbase)
5780 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5781 Context.getTypeDeclType(ClassDecl)) ==
5782 AR_accessible) {
5783 CheckDerivedToBaseConversion(
5784 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5785 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5786 SourceRange(), DeclarationName(), nullptr);
5787 }
5788
5789 MarkFunctionReferenced(Location, Dtor);
5790 DiagnoseUseOfDecl(Dtor, Location);
5791 }
5792}
5793
5794void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5795 if (!CDtorDecl)
5796 return;
5797
5798 if (CXXConstructorDecl *Constructor
5799 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5800 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5801 DiagnoseUninitializedFields(*this, Constructor);
5802 }
5803}
5804
5805bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5806 if (!getLangOpts().CPlusPlus)
5807 return false;
5808
5809 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5810 if (!RD)
5811 return false;
5812
5813 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5814 // class template specialization here, but doing so breaks a lot of code.
5815
5816 // We can't answer whether something is abstract until it has a
5817 // definition. If it's currently being defined, we'll walk back
5818 // over all the declarations when we have a full definition.
5819 const CXXRecordDecl *Def = RD->getDefinition();
5820 if (!Def || Def->isBeingDefined())
5821 return false;
5822
5823 return RD->isAbstract();
5824}
5825
5826bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5827 TypeDiagnoser &Diagnoser) {
5828 if (!isAbstractType(Loc, T))
5829 return false;
5830
5831 T = Context.getBaseElementType(T);
5832 Diagnoser.diagnose(*this, Loc, T);
5833 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5834 return true;
5835}
5836
5837void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5838 // Check if we've already emitted the list of pure virtual functions
5839 // for this class.
5840 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5841 return;
5842
5843 // If the diagnostic is suppressed, don't emit the notes. We're only
5844 // going to emit them once, so try to attach them to a diagnostic we're
5845 // actually going to show.
5846 if (Diags.isLastDiagnosticIgnored())
5847 return;
5848
5849 CXXFinalOverriderMap FinalOverriders;
5850 RD->getFinalOverriders(FinalOverriders);
5851
5852 // Keep a set of seen pure methods so we won't diagnose the same method
5853 // more than once.
5854 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5855
5856 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5857 MEnd = FinalOverriders.end();
5858 M != MEnd;
5859 ++M) {
5860 for (OverridingMethods::iterator SO = M->second.begin(),
5861 SOEnd = M->second.end();
5862 SO != SOEnd; ++SO) {
5863 // C++ [class.abstract]p4:
5864 // A class is abstract if it contains or inherits at least one
5865 // pure virtual function for which the final overrider is pure
5866 // virtual.
5867
5868 //
5869 if (SO->second.size() != 1)
5870 continue;
5871
5872 if (!SO->second.front().Method->isPure())
5873 continue;
5874
5875 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5876 continue;
5877
5878 Diag(SO->second.front().Method->getLocation(),
5879 diag::note_pure_virtual_function)
5880 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5881 }
5882 }
5883
5884 if (!PureVirtualClassDiagSet)
5885 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5886 PureVirtualClassDiagSet->insert(RD);
5887}
5888
5889namespace {
5890struct AbstractUsageInfo {
5891 Sema &S;
5892 CXXRecordDecl *Record;
5893 CanQualType AbstractType;
5894 bool Invalid;
5895
5896 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5897 : S(S), Record(Record),
5898 AbstractType(S.Context.getCanonicalType(
5899 S.Context.getTypeDeclType(Record))),
5900 Invalid(false) {}
5901
5902 void DiagnoseAbstractType() {
5903 if (Invalid) return;
5904 S.DiagnoseAbstractType(Record);
5905 Invalid = true;
5906 }
5907
5908 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5909};
5910
5911struct CheckAbstractUsage {
5912 AbstractUsageInfo &Info;
5913 const NamedDecl *Ctx;
5914
5915 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5916 : Info(Info), Ctx(Ctx) {}
5917
5918 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5919 switch (TL.getTypeLocClass()) {
5920#define ABSTRACT_TYPELOC(CLASS, PARENT)
5921#define TYPELOC(CLASS, PARENT) \
5922 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5923#include "clang/AST/TypeLocNodes.def"
5924 }
5925 }
5926
5927 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5928 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5929 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5930 if (!TL.getParam(I))
5931 continue;
5932
5933 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5934 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5935 }
5936 }
5937
5938 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5939 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5940 }
5941
5942 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5943 // Visit the type parameters from a permissive context.
5944 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5945 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5946 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5947 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5948 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5949 // TODO: other template argument types?
5950 }
5951 }
5952
5953 // Visit pointee types from a permissive context.
5954#define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc
(), Sema::AbstractNone); }
\
5955 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5956 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5957 }
5958 CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5959 CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5960 CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5961 CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5962 CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5963
5964 /// Handle all the types we haven't given a more specific
5965 /// implementation for above.
5966 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5967 // Every other kind of type that we haven't called out already
5968 // that has an inner type is either (1) sugar or (2) contains that
5969 // inner type in some way as a subobject.
5970 if (TypeLoc Next = TL.getNextTypeLoc())
5971 return Visit(Next, Sel);
5972
5973 // If there's no inner type and we're in a permissive context,
5974 // don't diagnose.
5975 if (Sel == Sema::AbstractNone) return;
5976
5977 // Check whether the type matches the abstract type.
5978 QualType T = TL.getType();
5979 if (T->isArrayType()) {
5980 Sel = Sema::AbstractArrayType;
5981 T = Info.S.Context.getBaseElementType(T);
5982 }
5983 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5984 if (CT != Info.AbstractType) return;
5985
5986 // It matched; do some magic.
5987 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
5988 if (Sel == Sema::AbstractArrayType) {
5989 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5990 << T << TL.getSourceRange();
5991 } else {
5992 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5993 << Sel << T << TL.getSourceRange();
5994 }
5995 Info.DiagnoseAbstractType();
5996 }
5997};
5998
5999void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6000 Sema::AbstractDiagSelID Sel) {
6001 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6002}
6003
6004}
6005
6006/// Check for invalid uses of an abstract type in a function declaration.
6007static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6008 FunctionDecl *FD) {
6009 // No need to do the check on definitions, which require that
6010 // the return/param types be complete.
6011 if (FD->doesThisDeclarationHaveABody())
6012 return;
6013
6014 // For safety's sake, just ignore it if we don't have type source
6015 // information. This should never happen for non-implicit methods,
6016 // but...
6017 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6018 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
6019}
6020
6021/// Check for invalid uses of an abstract type in a variable0 declaration.
6022static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6023 VarDecl *VD) {
6024 // No need to do the check on definitions, which require that
6025 // the type is complete.
6026 if (VD->isThisDeclarationADefinition())
6027 return;
6028
6029 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
6030 Sema::AbstractVariableType);
6031}
6032
6033/// Check for invalid uses of an abstract type within a class definition.
6034static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6035 CXXRecordDecl *RD) {
6036 for (auto *D : RD->decls()) {
6037 if (D->isImplicit()) continue;
6038
6039 // Step through friends to the befriended declaration.
6040 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6041 D = FD->getFriendDecl();
6042 if (!D) continue;
6043 }
6044
6045 // Functions and function templates.
6046 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6047 CheckAbstractClassUsage(Info, FD);
6048 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6049 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6050
6051 // Fields and static variables.
6052 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6053 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6054 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6055 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6056 CheckAbstractClassUsage(Info, VD);
6057 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6058 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6059
6060 // Nested classes and class templates.
6061 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6062 CheckAbstractClassUsage(Info, RD);
6063 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6064 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6065 }
6066 }
6067}
6068
6069static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6070 Attr *ClassAttr = getDLLAttr(Class);
6071 if (!ClassAttr)
6072 return;
6073
6074 assert(ClassAttr->getKind() == attr::DLLExport)(static_cast <bool> (ClassAttr->getKind() == attr::DLLExport
) ? void (0) : __assert_fail ("ClassAttr->getKind() == attr::DLLExport"
, "clang/lib/Sema/SemaDeclCXX.cpp", 6074, __extension__ __PRETTY_FUNCTION__
))
;
6075
6076 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6077
6078 if (TSK == TSK_ExplicitInstantiationDeclaration)
6079 // Don't go any further if this is just an explicit instantiation
6080 // declaration.
6081 return;
6082
6083 // Add a context note to explain how we got to any diagnostics produced below.
6084 struct MarkingClassDllexported {
6085 Sema &S;
6086 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6087 SourceLocation AttrLoc)
6088 : S(S) {
6089 Sema::CodeSynthesisContext Ctx;
6090 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6091 Ctx.PointOfInstantiation = AttrLoc;
6092 Ctx.Entity = Class;
6093 S.pushCodeSynthesisContext(Ctx);
6094 }
6095 ~MarkingClassDllexported() {
6096 S.popCodeSynthesisContext();
6097 }
6098 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6099
6100 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6101 S.MarkVTableUsed(Class->getLocation(), Class, true);
6102
6103 for (Decl *Member : Class->decls()) {
6104 // Skip members that were not marked exported.
6105 if (!Member->hasAttr<DLLExportAttr>())
6106 continue;
6107
6108 // Defined static variables that are members of an exported base
6109 // class must be marked export too.
6110 auto *VD = dyn_cast<VarDecl>(Member);
6111 if (VD && VD->getStorageClass() == SC_Static &&
6112 TSK == TSK_ImplicitInstantiation)
6113 S.MarkVariableReferenced(VD->getLocation(), VD);
6114
6115 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6116 if (!MD)
6117 continue;
6118
6119 if (MD->isUserProvided()) {
6120 // Instantiate non-default class member functions ...
6121
6122 // .. except for certain kinds of template specializations.
6123 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6124 continue;
6125
6126 // If this is an MS ABI dllexport default constructor, instantiate any
6127 // default arguments.
6128 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6129 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6130 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6131 S.InstantiateDefaultCtorDefaultArgs(CD);
6132 }
6133 }
6134
6135 S.MarkFunctionReferenced(Class->getLocation(), MD);
6136
6137 // The function will be passed to the consumer when its definition is
6138 // encountered.
6139 } else if (MD->isExplicitlyDefaulted()) {
6140 // Synthesize and instantiate explicitly defaulted methods.
6141 S.MarkFunctionReferenced(Class->getLocation(), MD);
6142
6143 if (TSK != TSK_ExplicitInstantiationDefinition) {
6144 // Except for explicit instantiation defs, we will not see the
6145 // definition again later, so pass it to the consumer now.
6146 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6147 }
6148 } else if (!MD->isTrivial() ||
6149 MD->isCopyAssignmentOperator() ||
6150 MD->isMoveAssignmentOperator()) {
6151 // Synthesize and instantiate non-trivial implicit methods, and the copy
6152 // and move assignment operators. The latter are exported even if they
6153 // are trivial, because the address of an operator can be taken and
6154 // should compare equal across libraries.
6155 S.MarkFunctionReferenced(Class->getLocation(), MD);
6156
6157 // There is no later point when we will see the definition of this
6158 // function, so pass it to the consumer now.
6159 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6160 }
6161 }
6162}
6163
6164static void checkForMultipleExportedDefaultConstructors(Sema &S,
6165 CXXRecordDecl *Class) {
6166 // Only the MS ABI has default constructor closures, so we don't need to do
6167 // this semantic checking anywhere else.
6168 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6169 return;
6170
6171 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6172 for (Decl *Member : Class->decls()) {
6173 // Look for exported default constructors.
6174 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6175 if (!CD || !CD->isDefaultConstructor())
6176 continue;
6177 auto *Attr = CD->getAttr<DLLExportAttr>();
6178 if (!Attr)
6179 continue;
6180
6181 // If the class is non-dependent, mark the default arguments as ODR-used so
6182 // that we can properly codegen the constructor closure.
6183 if (!Class->isDependentContext()) {
6184 for (ParmVarDecl *PD : CD->parameters()) {
6185 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6186 S.DiscardCleanupsInEvaluationContext();
6187 }
6188 }
6189
6190 if (LastExportedDefaultCtor) {
6191 S.Diag(LastExportedDefaultCtor->getLocation(),
6192 diag::err_attribute_dll_ambiguous_default_ctor)
6193 << Class;
6194 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6195 << CD->getDeclName();
6196 return;
6197 }
6198 LastExportedDefaultCtor = CD;
6199 }
6200}
6201
6202static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6203 CXXRecordDecl *Class) {
6204 bool ErrorReported = false;
6205 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6206 ClassTemplateDecl *TD) {
6207 if (ErrorReported)
6208 return;
6209 S.Diag(TD->getLocation(),
6210 diag::err_cuda_device_builtin_surftex_cls_template)
6211 << /*surface*/ 0 << TD;
6212 ErrorReported = true;
6213 };
6214
6215 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6216 if (!TD) {
6217 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6218 if (!SD) {
6219 S.Diag(Class->getLocation(),
6220 diag::err_cuda_device_builtin_surftex_ref_decl)
6221 << /*surface*/ 0 << Class;
6222 S.Diag(Class->getLocation(),
6223 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6224 << Class;
6225 return;
6226 }
6227 TD = SD->getSpecializedTemplate();
6228 }
6229
6230 TemplateParameterList *Params = TD->getTemplateParameters();
6231 unsigned N = Params->size();
6232
6233 if (N != 2) {
6234 reportIllegalClassTemplate(S, TD);
6235 S.Diag(TD->getLocation(),
6236 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6237 << TD << 2;
6238 }
6239 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6240 reportIllegalClassTemplate(S, TD);
6241 S.Diag(TD->getLocation(),
6242 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6243 << TD << /*1st*/ 0 << /*type*/ 0;
6244 }
6245 if (N > 1) {
6246 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6247 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6248 reportIllegalClassTemplate(S, TD);
6249 S.Diag(TD->getLocation(),
6250 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6251 << TD << /*2nd*/ 1 << /*integer*/ 1;
6252 }
6253 }
6254}
6255
6256static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6257 CXXRecordDecl *Class) {
6258 bool ErrorReported = false;
6259 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6260 ClassTemplateDecl *TD) {
6261 if (ErrorReported)
6262 return;
6263 S.Diag(TD->getLocation(),
6264 diag::err_cuda_device_builtin_surftex_cls_template)
6265 << /*texture*/ 1 << TD;
6266 ErrorReported = true;
6267 };
6268
6269 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6270 if (!TD) {
6271 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6272 if (!SD) {
6273 S.Diag(Class->getLocation(),
6274 diag::err_cuda_device_builtin_surftex_ref_decl)
6275 << /*texture*/ 1 << Class;
6276 S.Diag(Class->getLocation(),
6277 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6278 << Class;
6279 return;
6280 }
6281 TD = SD->getSpecializedTemplate();
6282 }
6283
6284 TemplateParameterList *Params = TD->getTemplateParameters();
6285 unsigned N = Params->size();
6286
6287 if (N != 3) {
6288 reportIllegalClassTemplate(S, TD);
6289 S.Diag(TD->getLocation(),
6290 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6291 << TD << 3;
6292 }
6293 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6294 reportIllegalClassTemplate(S, TD);
6295 S.Diag(TD->getLocation(),
6296 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6297 << TD << /*1st*/ 0 << /*type*/ 0;
6298 }
6299 if (N > 1) {
6300 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6301 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6302 reportIllegalClassTemplate(S, TD);
6303 S.Diag(TD->getLocation(),
6304 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6305 << TD << /*2nd*/ 1 << /*integer*/ 1;
6306 }
6307 }
6308 if (N > 2) {
6309 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6310 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6311 reportIllegalClassTemplate(S, TD);
6312 S.Diag(TD->getLocation(),
6313 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6314 << TD << /*3rd*/ 2 << /*integer*/ 1;
6315 }
6316 }
6317}
6318
6319void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6320 // Mark any compiler-generated routines with the implicit code_seg attribute.
6321 for (auto *Method : Class->methods()) {
6322 if (Method->isUserProvided())
6323 continue;
6324 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6325 Method->addAttr(A);
6326 }
6327}
6328
6329/// Check class-level dllimport/dllexport attribute.
6330void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6331 Attr *ClassAttr = getDLLAttr(Class);
6332
6333 // MSVC inherits DLL attributes to partial class template specializations.
6334 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6335 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6336 if (Attr *TemplateAttr =
6337 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6338 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6339 A->setInherited(true);
6340 ClassAttr = A;
6341 }
6342 }
6343 }
6344
6345 if (!ClassAttr)
6346 return;
6347
6348 if (!Class->isExternallyVisible()) {
6349 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6350 << Class << ClassAttr;
6351 return;
6352 }
6353
6354 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6355 !ClassAttr->isInherited()) {
6356 // Diagnose dll attributes on members of class with dll attribute.
6357 for (Decl *Member : Class->decls()) {
6358 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6359 continue;
6360 InheritableAttr *MemberAttr = getDLLAttr(Member);
6361 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6362 continue;
6363
6364 Diag(MemberAttr->getLocation(),
6365 diag::err_attribute_dll_member_of_dll_class)
6366 << MemberAttr << ClassAttr;
6367 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6368 Member->setInvalidDecl();
6369 }
6370 }
6371
6372 if (Class->getDescribedClassTemplate())
6373 // Don't inherit dll attribute until the template is instantiated.
6374 return;
6375
6376 // The class is either imported or exported.
6377 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6378
6379 // Check if this was a dllimport attribute propagated from a derived class to
6380 // a base class template specialization. We don't apply these attributes to
6381 // static data members.
6382 const bool PropagatedImport =
6383 !ClassExported &&
6384 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6385
6386 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6387
6388 // Ignore explicit dllexport on explicit class template instantiation
6389 // declarations, except in MinGW mode.
6390 if (ClassExported && !ClassAttr->isInherited() &&
6391 TSK == TSK_ExplicitInstantiationDeclaration &&
6392 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6393 Class->dropAttr<DLLExportAttr>();
6394 return;
6395 }
6396
6397 // Force declaration of implicit members so they can inherit the attribute.
6398 ForceDeclarationOfImplicitMembers(Class);
6399
6400 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6401 // seem to be true in practice?
6402
6403 for (Decl *Member : Class->decls()) {
6404 VarDecl *VD = dyn_cast<VarDecl>(Member);
6405 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6406
6407 // Only methods and static fields inherit the attributes.
6408 if (!VD && !MD)
6409 continue;
6410
6411 if (MD) {
6412 // Don't process deleted methods.
6413 if (MD->isDeleted())
6414 continue;
6415
6416 if (MD->isInlined()) {
6417 // MinGW does not import or export inline methods. But do it for
6418 // template instantiations.
6419 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6420 TSK != TSK_ExplicitInstantiationDeclaration &&
6421 TSK != TSK_ExplicitInstantiationDefinition)
6422 continue;
6423
6424 // MSVC versions before 2015 don't export the move assignment operators
6425 // and move constructor, so don't attempt to import/export them if
6426 // we have a definition.
6427 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6428 if ((MD->isMoveAssignmentOperator() ||
6429 (Ctor && Ctor->isMoveConstructor())) &&
6430 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6431 continue;
6432
6433 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6434 // operator is exported anyway.
6435 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6436 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6437 continue;
6438 }
6439 }
6440
6441 // Don't apply dllimport attributes to static data members of class template
6442 // instantiations when the attribute is propagated from a derived class.
6443 if (VD && PropagatedImport)
6444 continue;
6445
6446 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6447 continue;
6448
6449 if (!getDLLAttr(Member)) {
6450 InheritableAttr *NewAttr = nullptr;
6451
6452 // Do not export/import inline function when -fno-dllexport-inlines is
6453 // passed. But add attribute for later local static var check.
6454 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6455 TSK != TSK_ExplicitInstantiationDeclaration &&
6456 TSK != TSK_ExplicitInstantiationDefinition) {
6457 if (ClassExported) {
6458 NewAttr = ::new (getASTContext())
6459 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6460 } else {
6461 NewAttr = ::new (getASTContext())
6462 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6463 }
6464 } else {
6465 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6466 }
6467
6468 NewAttr->setInherited(true);
6469 Member->addAttr(NewAttr);
6470
6471 if (MD) {
6472 // Propagate DLLAttr to friend re-declarations of MD that have already
6473 // been constructed.
6474 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6475 FD = FD->getPreviousDecl()) {
6476 if (FD->getFriendObjectKind() == Decl::FOK_None)
6477 continue;
6478 assert(!getDLLAttr(FD) &&(static_cast <bool> (!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr"
) ? void (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 6479, __extension__ __PRETTY_FUNCTION__
))
6479 "friend re-decl should not already have a DLLAttr")(static_cast <bool> (!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr"
) ? void (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 6479, __extension__ __PRETTY_FUNCTION__
))
;
6480 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6481 NewAttr->setInherited(true);
6482 FD->addAttr(NewAttr);
6483 }
6484 }
6485 }
6486 }
6487
6488 if (ClassExported)
6489 DelayedDllExportClasses.push_back(Class);
6490}
6491
6492/// Perform propagation of DLL attributes from a derived class to a
6493/// templated base class for MS compatibility.
6494void Sema::propagateDLLAttrToBaseClassTemplate(
6495 CXXRecordDecl *Class, Attr *ClassAttr,
6496 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6497 if (getDLLAttr(
6498 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6499 // If the base class template has a DLL attribute, don't try to change it.
6500 return;
6501 }
6502
6503 auto TSK = BaseTemplateSpec->getSpecializationKind();
6504 if (!getDLLAttr(BaseTemplateSpec) &&
6505 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6506 TSK == TSK_ImplicitInstantiation)) {
6507 // The template hasn't been instantiated yet (or it has, but only as an
6508 // explicit instantiation declaration or implicit instantiation, which means
6509 // we haven't codegenned any members yet), so propagate the attribute.
6510 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6511 NewAttr->setInherited(true);
6512 BaseTemplateSpec->addAttr(NewAttr);
6513
6514 // If this was an import, mark that we propagated it from a derived class to
6515 // a base class template specialization.
6516 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6517 ImportAttr->setPropagatedToBaseTemplate();
6518
6519 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6520 // needs to be run again to work see the new attribute. Otherwise this will
6521 // get run whenever the template is instantiated.
6522 if (TSK != TSK_Undeclared)
6523 checkClassLevelDLLAttribute(BaseTemplateSpec);
6524
6525 return;
6526 }
6527
6528 if (getDLLAttr(BaseTemplateSpec)) {
6529 // The template has already been specialized or instantiated with an
6530 // attribute, explicitly or through propagation. We should not try to change
6531 // it.
6532 return;
6533 }
6534
6535 // The template was previously instantiated or explicitly specialized without
6536 // a dll attribute, It's too late for us to add an attribute, so warn that
6537 // this is unsupported.
6538 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6539 << BaseTemplateSpec->isExplicitSpecialization();
6540 Diag(ClassAttr->getLocation(), diag::note_attribute);
6541 if (BaseTemplateSpec->isExplicitSpecialization()) {
6542 Diag(BaseTemplateSpec->getLocation(),
6543 diag::note_template_class_explicit_specialization_was_here)
6544 << BaseTemplateSpec;
6545 } else {
6546 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6547 diag::note_template_class_instantiation_was_here)
6548 << BaseTemplateSpec;
6549 }
6550}
6551
6552/// Determine the kind of defaulting that would be done for a given function.
6553///
6554/// If the function is both a default constructor and a copy / move constructor
6555/// (due to having a default argument for the first parameter), this picks
6556/// CXXDefaultConstructor.
6557///
6558/// FIXME: Check that case is properly handled by all callers.
6559Sema::DefaultedFunctionKind
6560Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6561 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6562 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6563 if (Ctor->isDefaultConstructor())
6564 return Sema::CXXDefaultConstructor;
6565
6566 if (Ctor->isCopyConstructor())
6567 return Sema::CXXCopyConstructor;
6568
6569 if (Ctor->isMoveConstructor())
6570 return Sema::CXXMoveConstructor;
6571 }
6572
6573 if (MD->isCopyAssignmentOperator())
6574 return Sema::CXXCopyAssignment;
6575
6576 if (MD->isMoveAssignmentOperator())
6577 return Sema::CXXMoveAssignment;
6578
6579 if (isa<CXXDestructorDecl>(FD))
6580 return Sema::CXXDestructor;
6581 }
6582
6583 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6584 case OO_EqualEqual:
6585 return DefaultedComparisonKind::Equal;
6586
6587 case OO_ExclaimEqual:
6588 return DefaultedComparisonKind::NotEqual;
6589
6590 case OO_Spaceship:
6591 // No point allowing this if <=> doesn't exist in the current language mode.
6592 if (!getLangOpts().CPlusPlus20)
6593 break;
6594 return DefaultedComparisonKind::ThreeWay;
6595
6596 case OO_Less:
6597 case OO_LessEqual:
6598 case OO_Greater:
6599 case OO_GreaterEqual:
6600 // No point allowing this if <=> doesn't exist in the current language mode.
6601 if (!getLangOpts().CPlusPlus20)
6602 break;
6603 return DefaultedComparisonKind::Relational;
6604
6605 default:
6606 break;
6607 }
6608
6609 // Not defaultable.
6610 return DefaultedFunctionKind();
6611}
6612
6613static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6614 SourceLocation DefaultLoc) {
6615 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6616 if (DFK.isComparison())
6617 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6618
6619 switch (DFK.asSpecialMember()) {
6620 case Sema::CXXDefaultConstructor:
6621 S.DefineImplicitDefaultConstructor(DefaultLoc,
6622 cast<CXXConstructorDecl>(FD));
6623 break;
6624 case Sema::CXXCopyConstructor:
6625 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6626 break;
6627 case Sema::CXXCopyAssignment:
6628 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6629 break;
6630 case Sema::CXXDestructor:
6631 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6632 break;
6633 case Sema::CXXMoveConstructor:
6634 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6635 break;
6636 case Sema::CXXMoveAssignment:
6637 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6638 break;
6639 case Sema::CXXInvalid:
6640 llvm_unreachable("Invalid special member.")::llvm::llvm_unreachable_internal("Invalid special member.", "clang/lib/Sema/SemaDeclCXX.cpp"
, 6640)
;
6641 }
6642}
6643
6644/// Determine whether a type is permitted to be passed or returned in
6645/// registers, per C++ [class.temporary]p3.
6646static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6647 TargetInfo::CallingConvKind CCK) {
6648 if (D->isDependentType() || D->isInvalidDecl())
6649 return false;
6650
6651 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6652 // The PS4 platform ABI follows the behavior of Clang 3.2.
6653 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6654 return !D->hasNonTrivialDestructorForCall() &&
6655 !D->hasNonTrivialCopyConstructorForCall();
6656
6657 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6658 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6659 bool DtorIsTrivialForCall = false;
6660
6661 // If a class has at least one eligible, trivial copy constructor, it
6662 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6663 //
6664 // Note: This permits classes with non-trivial copy or move ctors to be
6665 // passed in registers, so long as they *also* have a trivial copy ctor,
6666 // which is non-conforming.
6667 if (D->needsImplicitCopyConstructor()) {
6668 if (!D->defaultedCopyConstructorIsDeleted()) {
6669 if (D->hasTrivialCopyConstructor())
6670 CopyCtorIsTrivial = true;
6671 if (D->hasTrivialCopyConstructorForCall())
6672 CopyCtorIsTrivialForCall = true;
6673 }
6674 } else {
6675 for (const CXXConstructorDecl *CD : D->ctors()) {
6676 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6677 !CD->isIneligibleOrNotSelected()) {
6678 if (CD->isTrivial())
6679 CopyCtorIsTrivial = true;
6680 if (CD->isTrivialForCall())
6681 CopyCtorIsTrivialForCall = true;
6682 }
6683 }
6684 }
6685
6686 if (D->needsImplicitDestructor()) {
6687 if (!D->defaultedDestructorIsDeleted() &&
6688 D->hasTrivialDestructorForCall())
6689 DtorIsTrivialForCall = true;
6690 } else if (const auto *DD = D->getDestructor()) {
6691 if (!DD->isDeleted() && DD->isTrivialForCall())
6692 DtorIsTrivialForCall = true;
6693 }
6694
6695 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6696 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6697 return true;
6698
6699 // If a class has a destructor, we'd really like to pass it indirectly
6700 // because it allows us to elide copies. Unfortunately, MSVC makes that
6701 // impossible for small types, which it will pass in a single register or
6702 // stack slot. Most objects with dtors are large-ish, so handle that early.
6703 // We can't call out all large objects as being indirect because there are
6704 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6705 // how we pass large POD types.
6706
6707 // Note: This permits small classes with nontrivial destructors to be
6708 // passed in registers, which is non-conforming.
6709 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6710 uint64_t TypeSize = isAArch64 ? 128 : 64;
6711
6712 if (CopyCtorIsTrivial &&
6713 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6714 return true;
6715 return false;
6716 }
6717
6718 // Per C++ [class.temporary]p3, the relevant condition is:
6719 // each copy constructor, move constructor, and destructor of X is
6720 // either trivial or deleted, and X has at least one non-deleted copy
6721 // or move constructor
6722 bool HasNonDeletedCopyOrMove = false;
6723
6724 if (D->needsImplicitCopyConstructor() &&
6725 !D->defaultedCopyConstructorIsDeleted()) {
6726 if (!D->hasTrivialCopyConstructorForCall())
6727 return false;
6728 HasNonDeletedCopyOrMove = true;
6729 }
6730
6731 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6732 !D->defaultedMoveConstructorIsDeleted()) {
6733 if (!D->hasTrivialMoveConstructorForCall())
6734 return false;
6735 HasNonDeletedCopyOrMove = true;
6736 }
6737
6738 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6739 !D->hasTrivialDestructorForCall())
6740 return false;
6741
6742 for (const CXXMethodDecl *MD : D->methods()) {
6743 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6744 continue;
6745
6746 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6747 if (CD && CD->isCopyOrMoveConstructor())
6748 HasNonDeletedCopyOrMove = true;
6749 else if (!isa<CXXDestructorDecl>(MD))
6750 continue;
6751
6752 if (!MD->isTrivialForCall())
6753 return false;
6754 }
6755
6756 return HasNonDeletedCopyOrMove;
6757}
6758
6759/// Report an error regarding overriding, along with any relevant
6760/// overridden methods.
6761///
6762/// \param DiagID the primary error to report.
6763/// \param MD the overriding method.
6764static bool
6765ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6766 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6767 bool IssuedDiagnostic = false;
6768 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6769 if (Report(O)) {
6770 if (!IssuedDiagnostic) {
6771 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6772 IssuedDiagnostic = true;
6773 }
6774 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6775 }
6776 }
6777 return IssuedDiagnostic;
6778}
6779
6780/// Perform semantic checks on a class definition that has been
6781/// completing, introducing implicitly-declared members, checking for
6782/// abstract types, etc.
6783///
6784/// \param S The scope in which the class was parsed. Null if we didn't just
6785/// parse a class definition.
6786/// \param Record The completed class.
6787void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6788 if (!Record)
6789 return;
6790
6791 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6792 AbstractUsageInfo Info(*this, Record);
6793 CheckAbstractClassUsage(Info, Record);
6794 }
6795
6796 // If this is not an aggregate type and has no user-declared constructor,
6797 // complain about any non-static data members of reference or const scalar
6798 // type, since they will never get initializers.
6799 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6800 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6801 !Record->isLambda()) {
6802 bool Complained = false;
6803 for (const auto *F : Record->fields()) {
6804 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6805 continue;
6806
6807 if (F->getType()->isReferenceType() ||
6808 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6809 if (!Complained) {
6810 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6811 << Record->getTagKind() << Record;
6812 Complained = true;
6813 }
6814
6815 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6816 << F->getType()->isReferenceType()
6817 << F->getDeclName();
6818 }
6819 }
6820 }
6821
6822 if (Record->getIdentifier()) {
6823 // C++ [class.mem]p13:
6824 // If T is the name of a class, then each of the following shall have a
6825 // name different from T:
6826 // - every member of every anonymous union that is a member of class T.
6827 //
6828 // C++ [class.mem]p14:
6829 // In addition, if class T has a user-declared constructor (12.1), every
6830 // non-static data member of class T shall have a name different from T.
6831 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6832 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6833 ++I) {
6834 NamedDecl *D = (*I)->getUnderlyingDecl();
6835 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6836 Record->hasUserDeclaredConstructor()) ||
6837 isa<IndirectFieldDecl>(D)) {
6838 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6839 << D->getDeclName();
6840 break;
6841 }
6842 }
6843 }
6844
6845 // Warn if the class has virtual methods but non-virtual public destructor.
6846 if (Record->isPolymorphic() && !Record->isDependentType()) {
6847 CXXDestructorDecl *dtor = Record->getDestructor();
6848 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6849 !Record->hasAttr<FinalAttr>())
6850 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6851 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6852 }
6853
6854 if (Record->isAbstract()) {
6855 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6856 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6857 << FA->isSpelledAsSealed();
6858 DiagnoseAbstractType(Record);
6859 }
6860 }
6861
6862 // Warn if the class has a final destructor but is not itself marked final.
6863 if (!Record->hasAttr<FinalAttr>()) {
6864 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6865 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6866 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6867 << FA->isSpelledAsSealed()
6868 << FixItHint::CreateInsertion(
6869 getLocForEndOfToken(Record->getLocation()),
6870 (FA->isSpelledAsSealed() ? " sealed" : " final"));
6871 Diag(Record->getLocation(),
6872 diag::note_final_dtor_non_final_class_silence)
6873 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6874 }
6875 }
6876 }
6877
6878 // See if trivial_abi has to be dropped.
6879 if (Record->hasAttr<TrivialABIAttr>())
6880 checkIllFormedTrivialABIStruct(*Record);
6881
6882 // Set HasTrivialSpecialMemberForCall if the record has attribute
6883 // "trivial_abi".
6884 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6885
6886 if (HasTrivialABI)
6887 Record->setHasTrivialSpecialMemberForCall();
6888
6889 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6890 // We check these last because they can depend on the properties of the
6891 // primary comparison functions (==, <=>).
6892 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6893
6894 // Perform checks that can't be done until we know all the properties of a
6895 // member function (whether it's defaulted, deleted, virtual, overriding,
6896 // ...).
6897 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6898 // A static function cannot override anything.
6899 if (MD->getStorageClass() == SC_Static) {
6900 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6901 [](const CXXMethodDecl *) { return true; }))
6902 return;
6903 }
6904
6905 // A deleted function cannot override a non-deleted function and vice
6906 // versa.
6907 if (ReportOverrides(*this,
6908 MD->isDeleted() ? diag::err_deleted_override
6909 : diag::err_non_deleted_override,
6910 MD, [&](const CXXMethodDecl *V) {
6911 return MD->isDeleted() != V->isDeleted();
6912 })) {
6913 if (MD->isDefaulted() && MD->isDeleted())
6914 // Explain why this defaulted function was deleted.
6915 DiagnoseDeletedDefaultedFunction(MD);
6916 return;
6917 }
6918
6919 // A consteval function cannot override a non-consteval function and vice
6920 // versa.
6921 if (ReportOverrides(*this,
6922 MD->isConsteval() ? diag::err_consteval_override
6923 : diag::err_non_consteval_override,
6924 MD, [&](const CXXMethodDecl *V) {
6925 return MD->isConsteval() != V->isConsteval();
6926 })) {
6927 if (MD->isDefaulted() && MD->isDeleted())
6928 // Explain why this defaulted function was deleted.
6929 DiagnoseDeletedDefaultedFunction(MD);
6930 return;
6931 }
6932 };
6933
6934 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6935 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6936 return false;
6937
6938 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6939 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6940 DFK.asComparison() == DefaultedComparisonKind::Relational) {
6941 DefaultedSecondaryComparisons.push_back(FD);
6942 return true;
6943 }
6944
6945 CheckExplicitlyDefaultedFunction(S, FD);
6946 return false;
6947 };
6948
6949 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6950 // Check whether the explicitly-defaulted members are valid.
6951 bool Incomplete = CheckForDefaultedFunction(M);
6952
6953 // Skip the rest of the checks for a member of a dependent class.
6954 if (Record->isDependentType())
6955 return;
6956
6957 // For an explicitly defaulted or deleted special member, we defer
6958 // determining triviality until the class is complete. That time is now!
6959 CXXSpecialMember CSM = getSpecialMember(M);
6960 if (!M->isImplicit() && !M->isUserProvided()) {
6961 if (CSM != CXXInvalid) {
6962 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6963 // Inform the class that we've finished declaring this member.
6964 Record->finishedDefaultedOrDeletedMember(M);
6965 M->setTrivialForCall(
6966 HasTrivialABI ||
6967 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6968 Record->setTrivialForCallFlags(M);
6969 }
6970 }
6971
6972 // Set triviality for the purpose of calls if this is a user-provided
6973 // copy/move constructor or destructor.
6974 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6975 CSM == CXXDestructor) && M->isUserProvided()) {
6976 M->setTrivialForCall(HasTrivialABI);
6977 Record->setTrivialForCallFlags(M);
6978 }
6979
6980 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6981 M->hasAttr<DLLExportAttr>()) {
6982 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6983 M->isTrivial() &&
6984 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6985 CSM == CXXDestructor))
6986 M->dropAttr<DLLExportAttr>();
6987
6988 if (M->hasAttr<DLLExportAttr>()) {
6989 // Define after any fields with in-class initializers have been parsed.
6990 DelayedDllExportMemberFunctions.push_back(M);
6991 }
6992 }
6993
6994 // Define defaulted constexpr virtual functions that override a base class
6995 // function right away.
6996 // FIXME: We can defer doing this until the vtable is marked as used.
6997 if (CSM != CXXInvalid && !M->isDeleted() && M->isDefaulted() &&
6998 M->isConstexpr() && M->size_overridden_methods())
6999 DefineDefaultedFunction(*this, M, M->getLocation());
7000
7001 if (!Incomplete)
7002 CheckCompletedMemberFunction(M);
7003 };
7004
7005 // Check the destructor before any other member function. We need to
7006 // determine whether it's trivial in order to determine whether the claas
7007 // type is a literal type, which is a prerequisite for determining whether
7008 // other special member functions are valid and whether they're implicitly
7009 // 'constexpr'.
7010 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7011 CompleteMemberFunction(Dtor);
7012
7013 bool HasMethodWithOverrideControl = false,
7014 HasOverridingMethodWithoutOverrideControl = false;
7015 for (auto *D : Record->decls()) {
7016 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
7017 // FIXME: We could do this check for dependent types with non-dependent
7018 // bases.
7019 if (!Record->isDependentType()) {
7020 // See if a method overloads virtual methods in a base
7021 // class without overriding any.
7022 if (!M->isStatic())
7023 DiagnoseHiddenVirtualMethods(M);
7024 if (M->hasAttr<OverrideAttr>())
7025 HasMethodWithOverrideControl = true;
7026 else if (M->size_overridden_methods() > 0)
7027 HasOverridingMethodWithoutOverrideControl = true;
7028 }
7029
7030 if (!isa<CXXDestructorDecl>(M))
7031 CompleteMemberFunction(M);
7032 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
7033 CheckForDefaultedFunction(
7034 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
7035 }
7036 }
7037
7038 if (HasOverridingMethodWithoutOverrideControl) {
7039 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7040 for (auto *M : Record->methods())
7041 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7042 }
7043
7044 // Check the defaulted secondary comparisons after any other member functions.
7045 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7046 CheckExplicitlyDefaultedFunction(S, FD);
7047
7048 // If this is a member function, we deferred checking it until now.
7049 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7050 CheckCompletedMemberFunction(MD);
7051 }
7052
7053 // ms_struct is a request to use the same ABI rules as MSVC. Check
7054 // whether this class uses any C++ features that are implemented
7055 // completely differently in MSVC, and if so, emit a diagnostic.
7056 // That diagnostic defaults to an error, but we allow projects to
7057 // map it down to a warning (or ignore it). It's a fairly common
7058 // practice among users of the ms_struct pragma to mass-annotate
7059 // headers, sweeping up a bunch of types that the project doesn't
7060 // really rely on MSVC-compatible layout for. We must therefore
7061 // support "ms_struct except for C++ stuff" as a secondary ABI.
7062 // Don't emit this diagnostic if the feature was enabled as a
7063 // language option (as opposed to via a pragma or attribute), as
7064 // the option -mms-bitfields otherwise essentially makes it impossible
7065 // to build C++ code, unless this diagnostic is turned off.
7066 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7067 (Record->isPolymorphic() || Record->getNumBases())) {
7068 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7069 }
7070
7071 checkClassLevelDLLAttribute(Record);
7072 checkClassLevelCodeSegAttribute(Record);
7073
7074 bool ClangABICompat4 =
7075 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7076 TargetInfo::CallingConvKind CCK =
7077 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7078 bool CanPass = canPassInRegisters(*this, Record, CCK);
7079
7080 // Do not change ArgPassingRestrictions if it has already been set to
7081 // APK_CanNeverPassInRegs.
7082 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
7083 Record->setArgPassingRestrictions(CanPass
7084 ? RecordDecl::APK_CanPassInRegs
7085 : RecordDecl::APK_CannotPassInRegs);
7086
7087 // If canPassInRegisters returns true despite the record having a non-trivial
7088 // destructor, the record is destructed in the callee. This happens only when
7089 // the record or one of its subobjects has a field annotated with trivial_abi
7090 // or a field qualified with ObjC __strong/__weak.
7091 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7092 Record->setParamDestroyedInCallee(true);
7093 else if (Record->hasNonTrivialDestructor())
7094 Record->setParamDestroyedInCallee(CanPass);
7095
7096 if (getLangOpts().ForceEmitVTables) {
7097 // If we want to emit all the vtables, we need to mark it as used. This
7098 // is especially required for cases like vtable assumption loads.
7099 MarkVTableUsed(Record->getInnerLocStart(), Record);
7100 }
7101
7102 if (getLangOpts().CUDA) {
7103 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7104 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7105 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7106 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7107 }
7108}
7109
7110/// Look up the special member function that would be called by a special
7111/// member function for a subobject of class type.
7112///
7113/// \param Class The class type of the subobject.
7114/// \param CSM The kind of special member function.
7115/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7116/// \param ConstRHS True if this is a copy operation with a const object
7117/// on its RHS, that is, if the argument to the outer special member
7118/// function is 'const' and this is not a field marked 'mutable'.
7119static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7120 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7121 unsigned FieldQuals, bool ConstRHS) {
7122 unsigned LHSQuals = 0;
7123 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7124 LHSQuals = FieldQuals;
7125
7126 unsigned RHSQuals = FieldQuals;
7127 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7128 RHSQuals = 0;
7129 else if (ConstRHS)
7130 RHSQuals |= Qualifiers::Const;
7131
7132 return S.LookupSpecialMember(Class, CSM,
7133 RHSQuals & Qualifiers::Const,
7134 RHSQuals & Qualifiers::Volatile,
7135 false,
7136 LHSQuals & Qualifiers::Const,
7137 LHSQuals & Qualifiers::Volatile);
7138}
7139
7140class Sema::InheritedConstructorInfo {
7141 Sema &S;
7142 SourceLocation UseLoc;
7143
7144 /// A mapping from the base classes through which the constructor was
7145 /// inherited to the using shadow declaration in that base class (or a null
7146 /// pointer if the constructor was declared in that base class).
7147 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7148 InheritedFromBases;
7149
7150public:
7151 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7152 ConstructorUsingShadowDecl *Shadow)
7153 : S(S), UseLoc(UseLoc) {
7154 bool DiagnosedMultipleConstructedBases = false;
7155 CXXRecordDecl *ConstructedBase = nullptr;
7156 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7157
7158 // Find the set of such base class subobjects and check that there's a
7159 // unique constructed subobject.
7160 for (auto *D : Shadow->redecls()) {
7161 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7162 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7163 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7164
7165 InheritedFromBases.insert(
7166 std::make_pair(DNominatedBase->getCanonicalDecl(),
7167 DShadow->getNominatedBaseClassShadowDecl()));
7168 if (DShadow->constructsVirtualBase())
7169 InheritedFromBases.insert(
7170 std::make_pair(DConstructedBase->getCanonicalDecl(),
7171 DShadow->getConstructedBaseClassShadowDecl()));
7172 else
7173 assert(DNominatedBase == DConstructedBase)(static_cast <bool> (DNominatedBase == DConstructedBase
) ? void (0) : __assert_fail ("DNominatedBase == DConstructedBase"
, "clang/lib/Sema/SemaDeclCXX.cpp", 7173, __extension__ __PRETTY_FUNCTION__
))
;
7174
7175 // [class.inhctor.init]p2:
7176 // If the constructor was inherited from multiple base class subobjects
7177 // of type B, the program is ill-formed.
7178 if (!ConstructedBase) {
7179 ConstructedBase = DConstructedBase;
7180 ConstructedBaseIntroducer = D->getIntroducer();
7181 } else if (ConstructedBase != DConstructedBase &&
7182 !Shadow->isInvalidDecl()) {
7183 if (!DiagnosedMultipleConstructedBases) {
7184 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7185 << Shadow->getTargetDecl();
7186 S.Diag(ConstructedBaseIntroducer->getLocation(),
7187 diag::note_ambiguous_inherited_constructor_using)
7188 << ConstructedBase;
7189 DiagnosedMultipleConstructedBases = true;
7190 }
7191 S.Diag(D->getIntroducer()->getLocation(),
7192 diag::note_ambiguous_inherited_constructor_using)
7193 << DConstructedBase;
7194 }
7195 }
7196
7197 if (DiagnosedMultipleConstructedBases)
7198 Shadow->setInvalidDecl();
7199 }
7200
7201 /// Find the constructor to use for inherited construction of a base class,
7202 /// and whether that base class constructor inherits the constructor from a
7203 /// virtual base class (in which case it won't actually invoke it).
7204 std::pair<CXXConstructorDecl *, bool>
7205 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7206 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7207 if (It == InheritedFromBases.end())
7208 return std::make_pair(nullptr, false);
7209
7210 // This is an intermediary class.
7211 if (It->second)
7212 return std::make_pair(
7213 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7214 It->second->constructsVirtualBase());
7215
7216 // This is the base class from which the constructor was inherited.
7217 return std::make_pair(Ctor, false);
7218 }
7219};
7220
7221/// Is the special member function which would be selected to perform the
7222/// specified operation on the specified class type a constexpr constructor?
7223static bool
7224specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7225 Sema::CXXSpecialMember CSM, unsigned Quals,
7226 bool ConstRHS,
7227 CXXConstructorDecl *InheritedCtor = nullptr,
7228 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7229 // Suppress duplicate constraint checking here, in case a constraint check
7230 // caused us to decide to do this. Any truely recursive checks will get
7231 // caught during these checks anyway.
7232 Sema::SatisfactionStackResetRAII SSRAII{S};
7233
7234 // If we're inheriting a constructor, see if we need to call it for this base
7235 // class.
7236 if (InheritedCtor) {
7237 assert(CSM == Sema::CXXDefaultConstructor)(static_cast <bool> (CSM == Sema::CXXDefaultConstructor
) ? void (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor"
, "clang/lib/Sema/SemaDeclCXX.cpp", 7237, __extension__ __PRETTY_FUNCTION__
))
;
7238 auto BaseCtor =
7239 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7240 if (BaseCtor)
7241 return BaseCtor->isConstexpr();
7242 }
7243
7244 if (CSM == Sema::CXXDefaultConstructor)
7245 return ClassDecl->hasConstexprDefaultConstructor();
7246 if (CSM == Sema::CXXDestructor)
7247 return ClassDecl->hasConstexprDestructor();
7248
7249 Sema::SpecialMemberOverloadResult SMOR =
7250 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7251 if (!SMOR.getMethod())
7252 // A constructor we wouldn't select can't be "involved in initializing"
7253 // anything.
7254 return true;
7255 return SMOR.getMethod()->isConstexpr();
7256}
7257
7258/// Determine whether the specified special member function would be constexpr
7259/// if it were implicitly defined.
7260static bool defaultedSpecialMemberIsConstexpr(
7261 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7262 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7263 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7264 if (!S.getLangOpts().CPlusPlus11)
7265 return false;
7266
7267 // C++11 [dcl.constexpr]p4:
7268 // In the definition of a constexpr constructor [...]
7269 bool Ctor = true;
7270 switch (CSM) {
7271 case Sema::CXXDefaultConstructor:
7272 if (Inherited)
7273 break;
7274 // Since default constructor lookup is essentially trivial (and cannot
7275 // involve, for instance, template instantiation), we compute whether a
7276 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7277 //
7278 // This is important for performance; we need to know whether the default
7279 // constructor is constexpr to determine whether the type is a literal type.
7280 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7281
7282 case Sema::CXXCopyConstructor:
7283 case Sema::CXXMoveConstructor:
7284 // For copy or move constructors, we need to perform overload resolution.
7285 break;
7286
7287 case Sema::CXXCopyAssignment:
7288 case Sema::CXXMoveAssignment:
7289 if (!S.getLangOpts().CPlusPlus14)
7290 return false;
7291 // In C++1y, we need to perform overload resolution.
7292 Ctor = false;
7293 break;
7294
7295 case Sema::CXXDestructor:
7296 return ClassDecl->defaultedDestructorIsConstexpr();
7297
7298 case Sema::CXXInvalid:
7299 return false;
7300 }
7301
7302 // -- if the class is a non-empty union, or for each non-empty anonymous
7303 // union member of a non-union class, exactly one non-static data member
7304 // shall be initialized; [DR1359]
7305 //
7306 // If we squint, this is guaranteed, since exactly one non-static data member
7307 // will be initialized (if the constructor isn't deleted), we just don't know
7308 // which one.
7309 if (Ctor && ClassDecl->isUnion())
7310 return CSM == Sema::CXXDefaultConstructor
7311 ? ClassDecl->hasInClassInitializer() ||
7312 !ClassDecl->hasVariantMembers()
7313 : true;
7314
7315 // -- the class shall not have any virtual base classes;
7316 if (Ctor && ClassDecl->getNumVBases())
7317 return false;
7318
7319 // C++1y [class.copy]p26:
7320 // -- [the class] is a literal type, and
7321 if (!Ctor && !ClassDecl->isLiteral())
7322 return false;
7323
7324 // -- every constructor involved in initializing [...] base class
7325 // sub-objects shall be a constexpr constructor;
7326 // -- the assignment operator selected to copy/move each direct base
7327 // class is a constexpr function, and
7328 for (const auto &B : ClassDecl->bases()) {
7329 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7330 if (!BaseType)
7331 continue;
7332 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7333 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7334 InheritedCtor, Inherited))
7335 return false;
7336 }
7337
7338 // -- every constructor involved in initializing non-static data members
7339 // [...] shall be a constexpr constructor;
7340 // -- every non-static data member and base class sub-object shall be
7341 // initialized
7342 // -- for each non-static data member of X that is of class type (or array
7343 // thereof), the assignment operator selected to copy/move that member is
7344 // a constexpr function
7345 for (const auto *F : ClassDecl->fields()) {
7346 if (F->isInvalidDecl())
7347 continue;
7348 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7349 continue;
7350 QualType BaseType = S.Context.getBaseElementType(F->getType());
7351 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7352 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7353 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7354 BaseType.getCVRQualifiers(),
7355 ConstArg && !F->isMutable()))
7356 return false;
7357 } else if (CSM == Sema::CXXDefaultConstructor) {
7358 return false;
7359 }
7360 }
7361
7362 // All OK, it's constexpr!
7363 return true;
7364}
7365
7366namespace {
7367/// RAII object to register a defaulted function as having its exception
7368/// specification computed.
7369struct ComputingExceptionSpec {
7370 Sema &S;
7371
7372 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7373 : S(S) {
7374 Sema::CodeSynthesisContext Ctx;
7375 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7376 Ctx.PointOfInstantiation = Loc;
7377 Ctx.Entity = FD;
7378 S.pushCodeSynthesisContext(Ctx);
7379 }
7380 ~ComputingExceptionSpec() {
7381 S.popCodeSynthesisContext();
7382 }
7383};
7384}
7385
7386static Sema::ImplicitExceptionSpecification
7387ComputeDefaultedSpecialMemberExceptionSpec(
7388 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7389 Sema::InheritedConstructorInfo *ICI);
7390
7391static Sema::ImplicitExceptionSpecification
7392ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7393 FunctionDecl *FD,
7394 Sema::DefaultedComparisonKind DCK);
7395
7396static Sema::ImplicitExceptionSpecification
7397computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7398 auto DFK = S.getDefaultedFunctionKind(FD);
7399 if (DFK.isSpecialMember())
7400 return ComputeDefaultedSpecialMemberExceptionSpec(
7401 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7402 if (DFK.isComparison())
7403 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7404 DFK.asComparison());
7405
7406 auto *CD = cast<CXXConstructorDecl>(FD);
7407 assert(CD->getInheritedConstructor() &&(static_cast <bool> (CD->getInheritedConstructor() &&
"only defaulted functions and inherited constructors have implicit "
"exception specs") ? void (0) : __assert_fail ("CD->getInheritedConstructor() && \"only defaulted functions and inherited constructors have implicit \" \"exception specs\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7409, __extension__ __PRETTY_FUNCTION__
))
7408 "only defaulted functions and inherited constructors have implicit "(static_cast <bool> (CD->getInheritedConstructor() &&
"only defaulted functions and inherited constructors have implicit "
"exception specs") ? void (0) : __assert_fail ("CD->getInheritedConstructor() && \"only defaulted functions and inherited constructors have implicit \" \"exception specs\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7409, __extension__ __PRETTY_FUNCTION__
))
7409 "exception specs")(static_cast <bool> (CD->getInheritedConstructor() &&
"only defaulted functions and inherited constructors have implicit "
"exception specs") ? void (0) : __assert_fail ("CD->getInheritedConstructor() && \"only defaulted functions and inherited constructors have implicit \" \"exception specs\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7409, __extension__ __PRETTY_FUNCTION__
))
;
7410 Sema::InheritedConstructorInfo ICI(
7411 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7412 return ComputeDefaultedSpecialMemberExceptionSpec(
7413 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7414}
7415
7416static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7417 CXXMethodDecl *MD) {
7418 FunctionProtoType::ExtProtoInfo EPI;
7419
7420 // Build an exception specification pointing back at this member.
7421 EPI.ExceptionSpec.Type = EST_Unevaluated;
7422 EPI.ExceptionSpec.SourceDecl = MD;
7423
7424 // Set the calling convention to the default for C++ instance methods.
7425 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7426 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7427 /*IsCXXMethod=*/true));
7428 return EPI;
7429}
7430
7431void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7432 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7433 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7434 return;
7435
7436 // Evaluate the exception specification.
7437 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7438 auto ESI = IES.getExceptionSpec();
7439
7440 // Update the type of the special member to use it.
7441 UpdateExceptionSpec(FD, ESI);
7442}
7443
7444void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7445 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted")(static_cast <bool> (FD->isExplicitlyDefaulted() &&
"not explicitly-defaulted") ? void (0) : __assert_fail ("FD->isExplicitlyDefaulted() && \"not explicitly-defaulted\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7445, __extension__ __PRETTY_FUNCTION__
))
;
7446
7447 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7448 if (!DefKind) {
7449 assert(FD->getDeclContext()->isDependentContext())(static_cast <bool> (FD->getDeclContext()->isDependentContext
()) ? void (0) : __assert_fail ("FD->getDeclContext()->isDependentContext()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 7449, __extension__ __PRETTY_FUNCTION__
))
;
7450 return;
7451 }
7452
7453 if (DefKind.isComparison())
7454 UnusedPrivateFields.clear();
7455
7456 if (DefKind.isSpecialMember()
7457 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7458 DefKind.asSpecialMember(),
7459 FD->getDefaultLoc())
7460 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7461 FD->setInvalidDecl();
7462}
7463
7464bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7465 CXXSpecialMember CSM,
7466 SourceLocation DefaultLoc) {
7467 CXXRecordDecl *RD = MD->getParent();
7468
7469 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&(static_cast <bool> (MD->isExplicitlyDefaulted() &&
CSM != CXXInvalid && "not an explicitly-defaulted special member"
) ? void (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7470, __extension__ __PRETTY_FUNCTION__
))
1
Assuming the condition is true
2
Assuming 'CSM' is not equal to CXXInvalid
3
'?' condition is true
7470 "not an explicitly-defaulted special member")(static_cast <bool> (MD->isExplicitlyDefaulted() &&
CSM != CXXInvalid && "not an explicitly-defaulted special member"
) ? void (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7470, __extension__ __PRETTY_FUNCTION__
))
;
7471
7472 // Defer all checking for special members of a dependent type.
7473 if (RD->isDependentType())
4
Assuming the condition is false
5
Taking false branch
7474 return false;
7475
7476 // Whether this was the first-declared instance of the constructor.
7477 // This affects whether we implicitly add an exception spec and constexpr.
7478 bool First = MD == MD->getCanonicalDecl();
6
Assuming the condition is false
7479
7480 bool HadError = false;
7481
7482 // C++11 [dcl.fct.def.default]p1:
7483 // A function that is explicitly defaulted shall
7484 // -- be a special member function [...] (checked elsewhere),
7485 // -- have the same type (except for ref-qualifiers, and except that a
7486 // copy operation can take a non-const reference) as an implicit
7487 // declaration, and
7488 // -- not have default arguments.
7489 // C++2a changes the second bullet to instead delete the function if it's
7490 // defaulted on its first declaration, unless it's "an assignment operator,
7491 // and its return type differs or its parameter type is not a reference".
7492 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7
Assuming field 'CPlusPlus20' is 0
7493 bool ShouldDeleteForTypeMismatch = false;
7494 unsigned ExpectedParams = 1;
7495 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
8
Assuming 'CSM' is not equal to CXXDefaultConstructor
9
Assuming 'CSM' is not equal to CXXDestructor
10
Taking false branch
7496 ExpectedParams = 0;
7497 if (MD->getNumParams() != ExpectedParams) {
11
Assuming the condition is false
12
Taking false branch
7498 // This checks for default arguments: a copy or move constructor with a
7499 // default argument is classified as a default constructor, and assignment
7500 // operations and destructors can't have default arguments.
7501 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7502 << CSM << MD->getSourceRange();
7503 HadError = true;
7504 } else if (MD->isVariadic()) {
13
Assuming the condition is false
14
Taking false branch
7505 if (DeleteOnTypeMismatch)
7506 ShouldDeleteForTypeMismatch = true;
7507 else {
7508 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7509 << CSM << MD->getSourceRange();
7510 HadError = true;
7511 }
7512 }
7513
7514 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
15
Assuming the object is not a 'const class clang::FunctionProtoType *'
16
'Type' initialized to a null pointer value
7515
7516 bool CanHaveConstParam = false;
7517 if (CSM == CXXCopyConstructor)
17
Assuming 'CSM' is not equal to CXXCopyConstructor
18
Taking false branch
7518 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7519 else if (CSM == CXXCopyAssignment)
19
Assuming 'CSM' is not equal to CXXCopyAssignment
20
Taking false branch
7520 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7521
7522 QualType ReturnType = Context.VoidTy;
7523 if (CSM
20.1
'CSM' is not equal to CXXCopyAssignment
== CXXCopyAssignment || CSM == CXXMoveAssignment) {
21
Assuming 'CSM' is not equal to CXXMoveAssignment
7524 // Check for return type matching.
7525 ReturnType = Type->getReturnType();
7526
7527 QualType DeclType = Context.getTypeDeclType(RD);
7528 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7529 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7530
7531 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7532 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7533 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7534 HadError = true;
7535 }
7536
7537 // A defaulted special member cannot have cv-qualifiers.
7538 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7539 if (DeleteOnTypeMismatch)
7540 ShouldDeleteForTypeMismatch = true;
7541 else {
7542 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7543 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7544 HadError = true;
7545 }
7546 }
7547 }
7548
7549 // Check for parameter type matching.
7550 QualType ArgType = ExpectedParams
22.1
'ExpectedParams' is 1
? Type->getParamType(0) : QualType();
22
Taking false branch
23
'?' condition is true
24
Called C++ object pointer is null
7551 bool HasConstParam = false;
7552 if (ExpectedParams && ArgType->isReferenceType()) {
7553 // Argument must be reference to possibly-const T.
7554 QualType ReferentType = ArgType->getPointeeType();
7555 HasConstParam = ReferentType.isConstQualified();
7556
7557 if (ReferentType.isVolatileQualified()) {
7558 if (DeleteOnTypeMismatch)
7559 ShouldDeleteForTypeMismatch = true;
7560 else {
7561 Diag(MD->getLocation(),
7562 diag::err_defaulted_special_member_volatile_param) << CSM;
7563 HadError = true;
7564 }
7565 }
7566
7567 if (HasConstParam && !CanHaveConstParam) {
7568 if (DeleteOnTypeMismatch)
7569 ShouldDeleteForTypeMismatch = true;
7570 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7571 Diag(MD->getLocation(),
7572 diag::err_defaulted_special_member_copy_const_param)
7573 << (CSM == CXXCopyAssignment);
7574 // FIXME: Explain why this special member can't be const.
7575 HadError = true;
7576 } else {
7577 Diag(MD->getLocation(),
7578 diag::err_defaulted_special_member_move_const_param)
7579 << (CSM == CXXMoveAssignment);
7580 HadError = true;
7581 }
7582 }
7583 } else if (ExpectedParams) {
7584 // A copy assignment operator can take its argument by value, but a
7585 // defaulted one cannot.
7586 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument")(static_cast <bool> (CSM == CXXCopyAssignment &&
"unexpected non-ref argument") ? void (0) : __assert_fail ("CSM == CXXCopyAssignment && \"unexpected non-ref argument\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7586, __extension__ __PRETTY_FUNCTION__
))
;
7587 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7588 HadError = true;
7589 }
7590
7591 // C++11 [dcl.fct.def.default]p2:
7592 // An explicitly-defaulted function may be declared constexpr only if it
7593 // would have been implicitly declared as constexpr,
7594 // Do not apply this rule to members of class templates, since core issue 1358
7595 // makes such functions always instantiate to constexpr functions. For
7596 // functions which cannot be constexpr (for non-constructors in C++11 and for
7597 // destructors in C++14 and C++17), this is checked elsewhere.
7598 //
7599 // FIXME: This should not apply if the member is deleted.
7600 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7601 HasConstParam);
7602
7603 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7604 // If the instantiated template specialization of a constexpr function
7605 // template or member function of a class template would fail to satisfy
7606 // the requirements for a constexpr function or constexpr constructor, that
7607 // specialization is still a constexpr function or constexpr constructor,
7608 // even though a call to such a function cannot appear in a constant
7609 // expression.
7610 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7611 Constexpr = true;
7612
7613 if ((getLangOpts().CPlusPlus20 ||
7614 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7615 : isa<CXXConstructorDecl>(MD))) &&
7616 MD->isConstexpr() && !Constexpr &&
7617 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7618 Diag(MD->getBeginLoc(), MD->isConsteval()
7619 ? diag::err_incorrect_defaulted_consteval
7620 : diag::err_incorrect_defaulted_constexpr)
7621 << CSM;
7622 // FIXME: Explain why the special member can't be constexpr.
7623 HadError = true;
7624 }
7625
7626 if (First) {
7627 // C++2a [dcl.fct.def.default]p3:
7628 // If a function is explicitly defaulted on its first declaration, it is
7629 // implicitly considered to be constexpr if the implicit declaration
7630 // would be.
7631 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7632 ? ConstexprSpecKind::Consteval
7633 : ConstexprSpecKind::Constexpr)
7634 : ConstexprSpecKind::Unspecified);
7635
7636 if (!Type->hasExceptionSpec()) {
7637 // C++2a [except.spec]p3:
7638 // If a declaration of a function does not have a noexcept-specifier
7639 // [and] is defaulted on its first declaration, [...] the exception
7640 // specification is as specified below
7641 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7642 EPI.ExceptionSpec.Type = EST_Unevaluated;
7643 EPI.ExceptionSpec.SourceDecl = MD;
7644 MD->setType(Context.getFunctionType(
7645 ReturnType, llvm::ArrayRef(&ArgType, ExpectedParams), EPI));
7646 }
7647 }
7648
7649 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7650 if (First) {
7651 SetDeclDeleted(MD, MD->getLocation());
7652 if (!inTemplateInstantiation() && !HadError) {
7653 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7654 if (ShouldDeleteForTypeMismatch) {
7655 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7656 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr,
7657 /*Diagnose*/ true) &&
7658 DefaultLoc.isValid()) {
7659 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete)
7660 << FixItHint::CreateReplacement(DefaultLoc, "delete");
7661 }
7662 }
7663 if (ShouldDeleteForTypeMismatch && !HadError) {
7664 Diag(MD->getLocation(),
7665 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7666 }
7667 } else {
7668 // C++11 [dcl.fct.def.default]p4:
7669 // [For a] user-provided explicitly-defaulted function [...] if such a
7670 // function is implicitly defined as deleted, the program is ill-formed.
7671 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7672 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl")(static_cast <bool> (!ShouldDeleteForTypeMismatch &&
"deleted non-first decl") ? void (0) : __assert_fail ("!ShouldDeleteForTypeMismatch && \"deleted non-first decl\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7672, __extension__ __PRETTY_FUNCTION__
))
;
7673 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7674 HadError = true;
7675 }
7676 }
7677
7678 return HadError;
7679}
7680
7681namespace {
7682/// Helper class for building and checking a defaulted comparison.
7683///
7684/// Defaulted functions are built in two phases:
7685///
7686/// * First, the set of operations that the function will perform are
7687/// identified, and some of them are checked. If any of the checked
7688/// operations is invalid in certain ways, the comparison function is
7689/// defined as deleted and no body is built.
7690/// * Then, if the function is not defined as deleted, the body is built.
7691///
7692/// This is accomplished by performing two visitation steps over the eventual
7693/// body of the function.
7694template<typename Derived, typename ResultList, typename Result,
7695 typename Subobject>
7696class DefaultedComparisonVisitor {
7697public:
7698 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7699
7700 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7701 DefaultedComparisonKind DCK)
7702 : S(S), RD(RD), FD(FD), DCK(DCK) {
7703 if (auto *Info = FD->getDefaultedFunctionInfo()) {
7704 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7705 // UnresolvedSet to avoid this copy.
7706 Fns.assign(Info->getUnqualifiedLookups().begin(),
7707 Info->getUnqualifiedLookups().end());
7708 }
7709 }
7710
7711 ResultList visit() {
7712 // The type of an lvalue naming a parameter of this function.
7713 QualType ParamLvalType =
7714 FD->getParamDecl(0)->getType().getNonReferenceType();
7715
7716 ResultList Results;
7717
7718 switch (DCK) {
7719 case DefaultedComparisonKind::None:
7720 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "clang/lib/Sema/SemaDeclCXX.cpp", 7720)
;
7721
7722 case DefaultedComparisonKind::Equal:
7723 case DefaultedComparisonKind::ThreeWay:
7724 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7725 return Results;
7726
7727 case DefaultedComparisonKind::NotEqual:
7728 case DefaultedComparisonKind::Relational:
7729 Results.add(getDerived().visitExpandedSubobject(
7730 ParamLvalType, getDerived().getCompleteObject()));
7731 return Results;
7732 }
7733 llvm_unreachable("")::llvm::llvm_unreachable_internal("", "clang/lib/Sema/SemaDeclCXX.cpp"
, 7733)
;
7734 }
7735
7736protected:
7737 Derived &getDerived() { return static_cast<Derived&>(*this); }
7738
7739 /// Visit the expanded list of subobjects of the given type, as specified in
7740 /// C++2a [class.compare.default].
7741 ///
7742 /// \return \c true if the ResultList object said we're done, \c false if not.
7743 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7744 Qualifiers Quals) {
7745 // C++2a [class.compare.default]p4:
7746 // The direct base class subobjects of C
7747 for (CXXBaseSpecifier &Base : Record->bases())
7748 if (Results.add(getDerived().visitSubobject(
7749 S.Context.getQualifiedType(Base.getType(), Quals),
7750 getDerived().getBase(&Base))))
7751 return true;
7752
7753 // followed by the non-static data members of C
7754 for (FieldDecl *Field : Record->fields()) {
7755 // Recursively expand anonymous structs.
7756 if (Field->isAnonymousStructOrUnion()) {
7757 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7758 Quals))
7759 return true;
7760 continue;
7761 }
7762
7763 // Figure out the type of an lvalue denoting this field.
7764 Qualifiers FieldQuals = Quals;
7765 if (Field->isMutable())
7766 FieldQuals.removeConst();
7767 QualType FieldType =
7768 S.Context.getQualifiedType(Field->getType(), FieldQuals);
7769
7770 if (Results.add(getDerived().visitSubobject(
7771 FieldType, getDerived().getField(Field))))
7772 return true;
7773 }
7774
7775 // form a list of subobjects.
7776 return false;
7777 }
7778
7779 Result visitSubobject(QualType Type, Subobject Subobj) {
7780 // In that list, any subobject of array type is recursively expanded
7781 const ArrayType *AT = S.Context.getAsArrayType(Type);
7782 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7783 return getDerived().visitSubobjectArray(CAT->getElementType(),
7784 CAT->getSize(), Subobj);
7785 return getDerived().visitExpandedSubobject(Type, Subobj);
7786 }
7787
7788 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7789 Subobject Subobj) {
7790 return getDerived().visitSubobject(Type, Subobj);
7791 }
7792
7793protected:
7794 Sema &S;
7795 CXXRecordDecl *RD;
7796 FunctionDecl *FD;
7797 DefaultedComparisonKind DCK;
7798 UnresolvedSet<16> Fns;
7799};
7800
7801/// Information about a defaulted comparison, as determined by
7802/// DefaultedComparisonAnalyzer.
7803struct DefaultedComparisonInfo {
7804 bool Deleted = false;
7805 bool Constexpr = true;
7806 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7807
7808 static DefaultedComparisonInfo deleted() {
7809 DefaultedComparisonInfo Deleted;
7810 Deleted.Deleted = true;
7811 return Deleted;
7812 }
7813
7814 bool add(const DefaultedComparisonInfo &R) {
7815 Deleted |= R.Deleted;
7816 Constexpr &= R.Constexpr;
7817 Category = commonComparisonType(Category, R.Category);
7818 return Deleted;
7819 }
7820};
7821
7822/// An element in the expanded list of subobjects of a defaulted comparison, as
7823/// specified in C++2a [class.compare.default]p4.
7824struct DefaultedComparisonSubobject {
7825 enum { CompleteObject, Member, Base } Kind;
7826 NamedDecl *Decl;
7827 SourceLocation Loc;
7828};
7829
7830/// A visitor over the notional body of a defaulted comparison that determines
7831/// whether that body would be deleted or constexpr.
7832class DefaultedComparisonAnalyzer
7833 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7834 DefaultedComparisonInfo,
7835 DefaultedComparisonInfo,
7836 DefaultedComparisonSubobject> {
7837public:
7838 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7839
7840private:
7841 DiagnosticKind Diagnose;
7842
7843public:
7844 using Base = DefaultedComparisonVisitor;
7845 using Result = DefaultedComparisonInfo;
7846 using Subobject = DefaultedComparisonSubobject;
7847
7848 friend Base;
7849
7850 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7851 DefaultedComparisonKind DCK,
7852 DiagnosticKind Diagnose = NoDiagnostics)
7853 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7854
7855 Result visit() {
7856 if ((DCK == DefaultedComparisonKind::Equal ||
7857 DCK == DefaultedComparisonKind::ThreeWay) &&
7858 RD->hasVariantMembers()) {
7859 // C++2a [class.compare.default]p2 [P2002R0]:
7860 // A defaulted comparison operator function for class C is defined as
7861 // deleted if [...] C has variant members.
7862 if (Diagnose == ExplainDeleted) {
7863 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7864 << FD << RD->isUnion() << RD;
7865 }
7866 return Result::deleted();
7867 }
7868
7869 return Base::visit();
7870 }
7871
7872private:
7873 Subobject getCompleteObject() {
7874 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7875 }
7876
7877 Subobject getBase(CXXBaseSpecifier *Base) {
7878 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7879 Base->getBaseTypeLoc()};
7880 }
7881
7882 Subobject getField(FieldDecl *Field) {
7883 return Subobject{Subobject::Member, Field, Field->getLocation()};
7884 }
7885
7886 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7887 // C++2a [class.compare.default]p2 [P2002R0]:
7888 // A defaulted <=> or == operator function for class C is defined as
7889 // deleted if any non-static data member of C is of reference type
7890 if (Type->isReferenceType()) {
7891 if (Diagnose == ExplainDeleted) {
7892 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7893 << FD << RD;
7894 }
7895 return Result::deleted();
7896 }
7897
7898 // [...] Let xi be an lvalue denoting the ith element [...]
7899 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7900 Expr *Args[] = {&Xi, &Xi};
7901
7902 // All operators start by trying to apply that same operator recursively.
7903 OverloadedOperatorKind OO = FD->getOverloadedOperator();
7904 assert(OO != OO_None && "not an overloaded operator!")(static_cast <bool> (OO != OO_None && "not an overloaded operator!"
) ? void (0) : __assert_fail ("OO != OO_None && \"not an overloaded operator!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7904, __extension__ __PRETTY_FUNCTION__
))
;
7905 return visitBinaryOperator(OO, Args, Subobj);
7906 }
7907
7908 Result
7909 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7910 Subobject Subobj,
7911 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7912 // Note that there is no need to consider rewritten candidates here if
7913 // we've already found there is no viable 'operator<=>' candidate (and are
7914 // considering synthesizing a '<=>' from '==' and '<').
7915 OverloadCandidateSet CandidateSet(
7916 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7917 OverloadCandidateSet::OperatorRewriteInfo(
7918 OO, FD->getLocation(),
7919 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7920
7921 /// C++2a [class.compare.default]p1 [P2002R0]:
7922 /// [...] the defaulted function itself is never a candidate for overload
7923 /// resolution [...]
7924 CandidateSet.exclude(FD);
7925
7926 if (Args[0]->getType()->isOverloadableType())
7927 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7928 else
7929 // FIXME: We determine whether this is a valid expression by checking to
7930 // see if there's a viable builtin operator candidate for it. That isn't
7931 // really what the rules ask us to do, but should give the right results.
7932 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7933
7934 Result R;
7935
7936 OverloadCandidateSet::iterator Best;
7937 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7938 case OR_Success: {
7939 // C++2a [class.compare.secondary]p2 [P2002R0]:
7940 // The operator function [...] is defined as deleted if [...] the
7941 // candidate selected by overload resolution is not a rewritten
7942 // candidate.
7943 if ((DCK == DefaultedComparisonKind::NotEqual ||
7944 DCK == DefaultedComparisonKind::Relational) &&
7945 !Best->RewriteKind) {
7946 if (Diagnose == ExplainDeleted) {
7947 if (Best->Function) {
7948 S.Diag(Best->Function->getLocation(),
7949 diag::note_defaulted_comparison_not_rewritten_callee)
7950 << FD;
7951 } else {
7952 assert(Best->Conversions.size() == 2 &&(static_cast <bool> (Best->Conversions.size() == 2 &&
Best->Conversions[0].isUserDefined() && "non-user-defined conversion from class to built-in "
"comparison") ? void (0) : __assert_fail ("Best->Conversions.size() == 2 && Best->Conversions[0].isUserDefined() && \"non-user-defined conversion from class to built-in \" \"comparison\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7955, __extension__ __PRETTY_FUNCTION__
))
7953 Best->Conversions[0].isUserDefined() &&(static_cast <bool> (Best->Conversions.size() == 2 &&
Best->Conversions[0].isUserDefined() && "non-user-defined conversion from class to built-in "
"comparison") ? void (0) : __assert_fail ("Best->Conversions.size() == 2 && Best->Conversions[0].isUserDefined() && \"non-user-defined conversion from class to built-in \" \"comparison\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7955, __extension__ __PRETTY_FUNCTION__
))
7954 "non-user-defined conversion from class to built-in "(static_cast <bool> (Best->Conversions.size() == 2 &&
Best->Conversions[0].isUserDefined() && "non-user-defined conversion from class to built-in "
"comparison") ? void (0) : __assert_fail ("Best->Conversions.size() == 2 && Best->Conversions[0].isUserDefined() && \"non-user-defined conversion from class to built-in \" \"comparison\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7955, __extension__ __PRETTY_FUNCTION__
))
7955 "comparison")(static_cast <bool> (Best->Conversions.size() == 2 &&
Best->Conversions[0].isUserDefined() && "non-user-defined conversion from class to built-in "
"comparison") ? void (0) : __assert_fail ("Best->Conversions.size() == 2 && Best->Conversions[0].isUserDefined() && \"non-user-defined conversion from class to built-in \" \"comparison\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7955, __extension__ __PRETTY_FUNCTION__
))
;
7956 S.Diag(Best->Conversions[0]
7957 .UserDefined.FoundConversionFunction.getDecl()
7958 ->getLocation(),
7959 diag::note_defaulted_comparison_not_rewritten_conversion)
7960 << FD;
7961 }
7962 }
7963 return Result::deleted();
7964 }
7965
7966 // Throughout C++2a [class.compare]: if overload resolution does not
7967 // result in a usable function, the candidate function is defined as
7968 // deleted. This requires that we selected an accessible function.
7969 //
7970 // Note that this only considers the access of the function when named
7971 // within the type of the subobject, and not the access path for any
7972 // derived-to-base conversion.
7973 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7974 if (ArgClass && Best->FoundDecl.getDecl() &&
7975 Best->FoundDecl.getDecl()->isCXXClassMember()) {
7976 QualType ObjectType = Subobj.Kind == Subobject::Member
7977 ? Args[0]->getType()
7978 : S.Context.getRecordType(RD);
7979 if (!S.isMemberAccessibleForDeletion(
7980 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7981 Diagnose == ExplainDeleted
7982 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7983 << FD << Subobj.Kind << Subobj.Decl
7984 : S.PDiag()))
7985 return Result::deleted();
7986 }
7987
7988 bool NeedsDeducing =
7989 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
7990
7991 if (FunctionDecl *BestFD = Best->Function) {
7992 // C++2a [class.compare.default]p3 [P2002R0]:
7993 // A defaulted comparison function is constexpr-compatible if
7994 // [...] no overlod resolution performed [...] results in a
7995 // non-constexpr function.
7996 assert(!BestFD->isDeleted() && "wrong overload resolution result")(static_cast <bool> (!BestFD->isDeleted() &&
"wrong overload resolution result") ? void (0) : __assert_fail
("!BestFD->isDeleted() && \"wrong overload resolution result\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 7996, __extension__ __PRETTY_FUNCTION__
))
;
7997 // If it's not constexpr, explain why not.
7998 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7999 if (Subobj.Kind != Subobject::CompleteObject)
8000 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
8001 << Subobj.Kind << Subobj.Decl;
8002 S.Diag(BestFD->getLocation(),
8003 diag::note_defaulted_comparison_not_constexpr_here);
8004 // Bail out after explaining; we don't want any more notes.
8005 return Result::deleted();
8006 }
8007 R.Constexpr &= BestFD->isConstexpr();
8008
8009 if (NeedsDeducing) {
8010 // If any callee has an undeduced return type, deduce it now.
8011 // FIXME: It's not clear how a failure here should be handled. For
8012 // now, we produce an eager diagnostic, because that is forward
8013 // compatible with most (all?) other reasonable options.
8014 if (BestFD->getReturnType()->isUndeducedType() &&
8015 S.DeduceReturnType(BestFD, FD->getLocation(),
8016 /*Diagnose=*/false)) {
8017 // Don't produce a duplicate error when asked to explain why the
8018 // comparison is deleted: we diagnosed that when initially checking
8019 // the defaulted operator.
8020 if (Diagnose == NoDiagnostics) {
8021 S.Diag(
8022 FD->getLocation(),
8023 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8024 << Subobj.Kind << Subobj.Decl;
8025 S.Diag(
8026 Subobj.Loc,
8027 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8028 << Subobj.Kind << Subobj.Decl;
8029 S.Diag(BestFD->getLocation(),
8030 diag::note_defaulted_comparison_cannot_deduce_callee)
8031 << Subobj.Kind << Subobj.Decl;
8032 }
8033 return Result::deleted();
8034 }
8035 auto *Info = S.Context.CompCategories.lookupInfoForType(
8036 BestFD->getCallResultType());
8037 if (!Info) {
8038 if (Diagnose == ExplainDeleted) {
8039 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
8040 << Subobj.Kind << Subobj.Decl
8041 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8042 S.Diag(BestFD->getLocation(),
8043 diag::note_defaulted_comparison_cannot_deduce_callee)
8044 << Subobj.Kind << Subobj.Decl;
8045 }
8046 return Result::deleted();
8047 }
8048 R.Category = Info->Kind;
8049 }
8050 } else {
8051 QualType T = Best->BuiltinParamTypes[0];
8052 assert(T == Best->BuiltinParamTypes[1] &&(static_cast <bool> (T == Best->BuiltinParamTypes[1]
&& "builtin comparison for different types?") ? void
(0) : __assert_fail ("T == Best->BuiltinParamTypes[1] && \"builtin comparison for different types?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8053, __extension__ __PRETTY_FUNCTION__
))
8053 "builtin comparison for different types?")(static_cast <bool> (T == Best->BuiltinParamTypes[1]
&& "builtin comparison for different types?") ? void
(0) : __assert_fail ("T == Best->BuiltinParamTypes[1] && \"builtin comparison for different types?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8053, __extension__ __PRETTY_FUNCTION__
))
;
8054 assert(Best->BuiltinParamTypes[2].isNull() &&(static_cast <bool> (Best->BuiltinParamTypes[2].isNull
() && "invalid builtin comparison") ? void (0) : __assert_fail
("Best->BuiltinParamTypes[2].isNull() && \"invalid builtin comparison\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8055, __extension__ __PRETTY_FUNCTION__
))
8055 "invalid builtin comparison")(static_cast <bool> (Best->BuiltinParamTypes[2].isNull
() && "invalid builtin comparison") ? void (0) : __assert_fail
("Best->BuiltinParamTypes[2].isNull() && \"invalid builtin comparison\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8055, __extension__ __PRETTY_FUNCTION__
))
;
8056
8057 if (NeedsDeducing) {
8058 Optional<ComparisonCategoryType> Cat =
8059 getComparisonCategoryForBuiltinCmp(T);
8060 assert(Cat && "no category for builtin comparison?")(static_cast <bool> (Cat && "no category for builtin comparison?"
) ? void (0) : __assert_fail ("Cat && \"no category for builtin comparison?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8060, __extension__ __PRETTY_FUNCTION__
))
;
8061 R.Category = *Cat;
8062 }
8063 }
8064
8065 // Note that we might be rewriting to a different operator. That call is
8066 // not considered until we come to actually build the comparison function.
8067 break;
8068 }
8069
8070 case OR_Ambiguous:
8071 if (Diagnose == ExplainDeleted) {
8072 unsigned Kind = 0;
8073 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8074 Kind = OO == OO_EqualEqual ? 1 : 2;
8075 CandidateSet.NoteCandidates(
8076 PartialDiagnosticAt(
8077 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8078 << FD << Kind << Subobj.Kind << Subobj.Decl),
8079 S, OCD_AmbiguousCandidates, Args);
8080 }
8081 R = Result::deleted();
8082 break;
8083
8084 case OR_Deleted:
8085 if (Diagnose == ExplainDeleted) {
8086 if ((DCK == DefaultedComparisonKind::NotEqual ||
8087 DCK == DefaultedComparisonKind::Relational) &&
8088 !Best->RewriteKind) {
8089 S.Diag(Best->Function->getLocation(),
8090 diag::note_defaulted_comparison_not_rewritten_callee)
8091 << FD;
8092 } else {
8093 S.Diag(Subobj.Loc,
8094 diag::note_defaulted_comparison_calls_deleted)
8095 << FD << Subobj.Kind << Subobj.Decl;
8096 S.NoteDeletedFunction(Best->Function);
8097 }
8098 }
8099 R = Result::deleted();
8100 break;
8101
8102 case OR_No_Viable_Function:
8103 // If there's no usable candidate, we're done unless we can rewrite a
8104 // '<=>' in terms of '==' and '<'.
8105 if (OO == OO_Spaceship &&
8106 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
8107 // For any kind of comparison category return type, we need a usable
8108 // '==' and a usable '<'.
8109 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8110 &CandidateSet)))
8111 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8112 break;
8113 }
8114
8115 if (Diagnose == ExplainDeleted) {
8116 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8117 << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl;
8118
8119 // For a three-way comparison, list both the candidates for the
8120 // original operator and the candidates for the synthesized operator.
8121 if (SpaceshipCandidates) {
8122 SpaceshipCandidates->NoteCandidates(
8123 S, Args,
8124 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8125 Args, FD->getLocation()));
8126 S.Diag(Subobj.Loc,
8127 diag::note_defaulted_comparison_no_viable_function_synthesized)
8128 << (OO == OO_EqualEqual ? 0 : 1);
8129 }
8130
8131 CandidateSet.NoteCandidates(
8132 S, Args,
8133 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8134 FD->getLocation()));
8135 }
8136 R = Result::deleted();
8137 break;
8138 }
8139
8140 return R;
8141 }
8142};
8143
8144/// A list of statements.
8145struct StmtListResult {
8146 bool IsInvalid = false;
8147 llvm::SmallVector<Stmt*, 16> Stmts;
8148
8149 bool add(const StmtResult &S) {
8150 IsInvalid |= S.isInvalid();
8151 if (IsInvalid)
8152 return true;
8153 Stmts.push_back(S.get());
8154 return false;
8155 }
8156};
8157
8158/// A visitor over the notional body of a defaulted comparison that synthesizes
8159/// the actual body.
8160class DefaultedComparisonSynthesizer
8161 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8162 StmtListResult, StmtResult,
8163 std::pair<ExprResult, ExprResult>> {
8164 SourceLocation Loc;
8165 unsigned ArrayDepth = 0;
8166
8167public:
8168 using Base = DefaultedComparisonVisitor;
8169 using ExprPair = std::pair<ExprResult, ExprResult>;
8170
8171 friend Base;
8172
8173 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8174 DefaultedComparisonKind DCK,
8175 SourceLocation BodyLoc)
8176 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8177
8178 /// Build a suitable function body for this defaulted comparison operator.
8179 StmtResult build() {
8180 Sema::CompoundScopeRAII CompoundScope(S);
8181
8182 StmtListResult Stmts = visit();
8183 if (Stmts.IsInvalid)
8184 return StmtError();
8185
8186 ExprResult RetVal;
8187 switch (DCK) {
8188 case DefaultedComparisonKind::None:
8189 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8189)
;
8190
8191 case DefaultedComparisonKind::Equal: {
8192 // C++2a [class.eq]p3:
8193 // [...] compar[e] the corresponding elements [...] until the first
8194 // index i where xi == yi yields [...] false. If no such index exists,
8195 // V is true. Otherwise, V is false.
8196 //
8197 // Join the comparisons with '&&'s and return the result. Use a right
8198 // fold (traversing the conditions right-to-left), because that
8199 // short-circuits more naturally.
8200 auto OldStmts = std::move(Stmts.Stmts);
8201 Stmts.Stmts.clear();
8202 ExprResult CmpSoFar;
8203 // Finish a particular comparison chain.
8204 auto FinishCmp = [&] {
8205 if (Expr *Prior = CmpSoFar.get()) {
8206 // Convert the last expression to 'return ...;'
8207 if (RetVal.isUnset() && Stmts.Stmts.empty())
8208 RetVal = CmpSoFar;
8209 // Convert any prior comparison to 'if (!(...)) return false;'
8210 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8211 return true;
8212 CmpSoFar = ExprResult();
8213 }
8214 return false;
8215 };
8216 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8217 Expr *E = dyn_cast<Expr>(EAsStmt);
8218 if (!E) {
8219 // Found an array comparison.
8220 if (FinishCmp() || Stmts.add(EAsStmt))
8221 return StmtError();
8222 continue;
8223 }
8224
8225 if (CmpSoFar.isUnset()) {
8226 CmpSoFar = E;
8227 continue;
8228 }
8229 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8230 if (CmpSoFar.isInvalid())
8231 return StmtError();
8232 }
8233 if (FinishCmp())
8234 return StmtError();
8235 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8236 // If no such index exists, V is true.
8237 if (RetVal.isUnset())
8238 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8239 break;
8240 }
8241
8242 case DefaultedComparisonKind::ThreeWay: {
8243 // Per C++2a [class.spaceship]p3, as a fallback add:
8244 // return static_cast<R>(std::strong_ordering::equal);
8245 QualType StrongOrdering = S.CheckComparisonCategoryType(
8246 ComparisonCategoryType::StrongOrdering, Loc,
8247 Sema::ComparisonCategoryUsage::DefaultedOperator);
8248 if (StrongOrdering.isNull())
8249 return StmtError();
8250 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8251 .getValueInfo(ComparisonCategoryResult::Equal)
8252 ->VD;
8253 RetVal = getDecl(EqualVD);
8254 if (RetVal.isInvalid())
8255 return StmtError();
8256 RetVal = buildStaticCastToR(RetVal.get());
8257 break;
8258 }
8259
8260 case DefaultedComparisonKind::NotEqual:
8261 case DefaultedComparisonKind::Relational:
8262 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8263 break;
8264 }
8265
8266 // Build the final return statement.
8267 if (RetVal.isInvalid())
8268 return StmtError();
8269 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8270 if (ReturnStmt.isInvalid())
8271 return StmtError();
8272 Stmts.Stmts.push_back(ReturnStmt.get());
8273
8274 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8275 }
8276
8277private:
8278 ExprResult getDecl(ValueDecl *VD) {
8279 return S.BuildDeclarationNameExpr(
8280 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8281 }
8282
8283 ExprResult getParam(unsigned I) {
8284 ParmVarDecl *PD = FD->getParamDecl(I);
8285 return getDecl(PD);
8286 }
8287
8288 ExprPair getCompleteObject() {
8289 unsigned Param = 0;
8290 ExprResult LHS;
8291 if (isa<CXXMethodDecl>(FD)) {
8292 // LHS is '*this'.
8293 LHS = S.ActOnCXXThis(Loc);
8294 if (!LHS.isInvalid())
8295 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8296 } else {
8297 LHS = getParam(Param++);
8298 }
8299 ExprResult RHS = getParam(Param++);
8300 assert(Param == FD->getNumParams())(static_cast <bool> (Param == FD->getNumParams()) ? void
(0) : __assert_fail ("Param == FD->getNumParams()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 8300, __extension__ __PRETTY_FUNCTION__))
;
8301 return {LHS, RHS};
8302 }
8303
8304 ExprPair getBase(CXXBaseSpecifier *Base) {
8305 ExprPair Obj = getCompleteObject();
8306 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8307 return {ExprError(), ExprError()};
8308 CXXCastPath Path = {Base};
8309 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8310 CK_DerivedToBase, VK_LValue, &Path),
8311 S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8312 CK_DerivedToBase, VK_LValue, &Path)};
8313 }
8314
8315 ExprPair getField(FieldDecl *Field) {
8316 ExprPair Obj = getCompleteObject();
8317 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8318 return {ExprError(), ExprError()};
8319
8320 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8321 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8322 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8323 CXXScopeSpec(), Field, Found, NameInfo),
8324 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8325 CXXScopeSpec(), Field, Found, NameInfo)};
8326 }
8327
8328 // FIXME: When expanding a subobject, register a note in the code synthesis
8329 // stack to say which subobject we're comparing.
8330
8331 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8332 if (Cond.isInvalid())
8333 return StmtError();
8334
8335 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8336 if (NotCond.isInvalid())
8337 return StmtError();
8338
8339 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8340 assert(!False.isInvalid() && "should never fail")(static_cast <bool> (!False.isInvalid() && "should never fail"
) ? void (0) : __assert_fail ("!False.isInvalid() && \"should never fail\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8340, __extension__ __PRETTY_FUNCTION__
))
;
8341 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8342 if (ReturnFalse.isInvalid())
8343 return StmtError();
8344
8345 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8346 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8347 Sema::ConditionKind::Boolean),
8348 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8349 }
8350
8351 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8352 ExprPair Subobj) {
8353 QualType SizeType = S.Context.getSizeType();
8354 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8355
8356 // Build 'size_t i$n = 0'.
8357 IdentifierInfo *IterationVarName = nullptr;
8358 {
8359 SmallString<8> Str;
8360 llvm::raw_svector_ostream OS(Str);
8361 OS << "i" << ArrayDepth;
8362 IterationVarName = &S.Context.Idents.get(OS.str());
8363 }
8364 VarDecl *IterationVar = VarDecl::Create(
8365 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8366 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8367 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8368 IterationVar->setInit(
8369 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8370 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8371
8372 auto IterRef = [&] {
8373 ExprResult Ref = S.BuildDeclarationNameExpr(
8374 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8375 IterationVar);
8376 assert(!Ref.isInvalid() && "can't reference our own variable?")(static_cast <bool> (!Ref.isInvalid() && "can't reference our own variable?"
) ? void (0) : __assert_fail ("!Ref.isInvalid() && \"can't reference our own variable?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8376, __extension__ __PRETTY_FUNCTION__
))
;
8377 return Ref.get();
8378 };
8379
8380 // Build 'i$n != Size'.
8381 ExprResult Cond = S.CreateBuiltinBinOp(
8382 Loc, BO_NE, IterRef(),
8383 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8384 assert(!Cond.isInvalid() && "should never fail")(static_cast <bool> (!Cond.isInvalid() && "should never fail"
) ? void (0) : __assert_fail ("!Cond.isInvalid() && \"should never fail\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8384, __extension__ __PRETTY_FUNCTION__
))
;
8385
8386 // Build '++i$n'.
8387 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8388 assert(!Inc.isInvalid() && "should never fail")(static_cast <bool> (!Inc.isInvalid() && "should never fail"
) ? void (0) : __assert_fail ("!Inc.isInvalid() && \"should never fail\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8388, __extension__ __PRETTY_FUNCTION__
))
;
8389
8390 // Build 'a[i$n]' and 'b[i$n]'.
8391 auto Index = [&](ExprResult E) {
8392 if (E.isInvalid())
8393 return ExprError();
8394 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8395 };
8396 Subobj.first = Index(Subobj.first);
8397 Subobj.second = Index(Subobj.second);
8398
8399 // Compare the array elements.
8400 ++ArrayDepth;
8401 StmtResult Substmt = visitSubobject(Type, Subobj);
8402 --ArrayDepth;
8403
8404 if (Substmt.isInvalid())
8405 return StmtError();
8406
8407 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8408 // For outer levels or for an 'operator<=>' we already have a suitable
8409 // statement that returns as necessary.
8410 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8411 assert(DCK == DefaultedComparisonKind::Equal &&(static_cast <bool> (DCK == DefaultedComparisonKind::Equal
&& "should have non-expression statement") ? void (0
) : __assert_fail ("DCK == DefaultedComparisonKind::Equal && \"should have non-expression statement\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8412, __extension__ __PRETTY_FUNCTION__
))
8412 "should have non-expression statement")(static_cast <bool> (DCK == DefaultedComparisonKind::Equal
&& "should have non-expression statement") ? void (0
) : __assert_fail ("DCK == DefaultedComparisonKind::Equal && \"should have non-expression statement\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8412, __extension__ __PRETTY_FUNCTION__
))
;
8413 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8414 if (Substmt.isInvalid())
8415 return StmtError();
8416 }
8417
8418 // Build 'for (...) ...'
8419 return S.ActOnForStmt(Loc, Loc, Init,
8420 S.ActOnCondition(nullptr, Loc, Cond.get(),
8421 Sema::ConditionKind::Boolean),
8422 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8423 Substmt.get());
8424 }
8425
8426 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8427 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8428 return StmtError();
8429
8430 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8431 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8432 ExprResult Op;
8433 if (Type->isOverloadableType())
8434 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8435 Obj.second.get(), /*PerformADL=*/true,
8436 /*AllowRewrittenCandidates=*/true, FD);
8437 else
8438 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8439 if (Op.isInvalid())
8440 return StmtError();
8441
8442 switch (DCK) {
8443 case DefaultedComparisonKind::None:
8444 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8444)
;
8445
8446 case DefaultedComparisonKind::Equal:
8447 // Per C++2a [class.eq]p2, each comparison is individually contextually
8448 // converted to bool.
8449 Op = S.PerformContextuallyConvertToBool(Op.get());
8450 if (Op.isInvalid())
8451 return StmtError();
8452 return Op.get();
8453
8454 case DefaultedComparisonKind::ThreeWay: {
8455 // Per C++2a [class.spaceship]p3, form:
8456 // if (R cmp = static_cast<R>(op); cmp != 0)
8457 // return cmp;
8458 QualType R = FD->getReturnType();
8459 Op = buildStaticCastToR(Op.get());
8460 if (Op.isInvalid())
8461 return StmtError();
8462
8463 // R cmp = ...;
8464 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8465 VarDecl *VD =
8466 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8467 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8468 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8469 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8470
8471 // cmp != 0
8472 ExprResult VDRef = getDecl(VD);
8473 if (VDRef.isInvalid())
8474 return StmtError();
8475 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8476 Expr *Zero =
8477 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8478 ExprResult Comp;
8479 if (VDRef.get()->getType()->isOverloadableType())
8480 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8481 true, FD);
8482 else
8483 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8484 if (Comp.isInvalid())
8485 return StmtError();
8486 Sema::ConditionResult Cond = S.ActOnCondition(
8487 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8488 if (Cond.isInvalid())
8489 return StmtError();
8490
8491 // return cmp;
8492 VDRef = getDecl(VD);
8493 if (VDRef.isInvalid())
8494 return StmtError();
8495 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8496 if (ReturnStmt.isInvalid())
8497 return StmtError();
8498
8499 // if (...)
8500 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8501 Loc, ReturnStmt.get(),
8502 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8503 }
8504
8505 case DefaultedComparisonKind::NotEqual:
8506 case DefaultedComparisonKind::Relational:
8507 // C++2a [class.compare.secondary]p2:
8508 // Otherwise, the operator function yields x @ y.
8509 return Op.get();
8510 }
8511 llvm_unreachable("")::llvm::llvm_unreachable_internal("", "clang/lib/Sema/SemaDeclCXX.cpp"
, 8511)
;
8512 }
8513
8514 /// Build "static_cast<R>(E)".
8515 ExprResult buildStaticCastToR(Expr *E) {
8516 QualType R = FD->getReturnType();
8517 assert(!R->isUndeducedType() && "type should have been deduced already")(static_cast <bool> (!R->isUndeducedType() &&
"type should have been deduced already") ? void (0) : __assert_fail
("!R->isUndeducedType() && \"type should have been deduced already\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8517, __extension__ __PRETTY_FUNCTION__
))
;
8518
8519 // Don't bother forming a no-op cast in the common case.
8520 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8521 return E;
8522 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8523 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8524 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8525 }
8526};
8527}
8528
8529/// Perform the unqualified lookups that might be needed to form a defaulted
8530/// comparison function for the given operator.
8531static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8532 UnresolvedSetImpl &Operators,
8533 OverloadedOperatorKind Op) {
8534 auto Lookup = [&](OverloadedOperatorKind OO) {
8535 Self.LookupOverloadedOperatorName(OO, S, Operators);
8536 };
8537
8538 // Every defaulted operator looks up itself.
8539 Lookup(Op);
8540 // ... and the rewritten form of itself, if any.
8541 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8542 Lookup(ExtraOp);
8543
8544 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8545 // synthesize a three-way comparison from '<' and '=='. In a dependent
8546 // context, we also need to look up '==' in case we implicitly declare a
8547 // defaulted 'operator=='.
8548 if (Op == OO_Spaceship) {
8549 Lookup(OO_ExclaimEqual);
8550 Lookup(OO_Less);
8551 Lookup(OO_EqualEqual);
8552 }
8553}
8554
8555bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8556 DefaultedComparisonKind DCK) {
8557 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison")(static_cast <bool> (DCK != DefaultedComparisonKind::None
&& "not a defaulted comparison") ? void (0) : __assert_fail
("DCK != DefaultedComparisonKind::None && \"not a defaulted comparison\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8557, __extension__ __PRETTY_FUNCTION__
))
;
8558
8559 // Perform any unqualified lookups we're going to need to default this
8560 // function.
8561 if (S) {
8562 UnresolvedSet<32> Operators;
8563 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8564 FD->getOverloadedOperator());
8565 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8566 Context, Operators.pairs()));
8567 }
8568
8569 // C++2a [class.compare.default]p1:
8570 // A defaulted comparison operator function for some class C shall be a
8571 // non-template function declared in the member-specification of C that is
8572 // -- a non-static const member of C having one parameter of type
8573 // const C&, or
8574 // -- a friend of C having two parameters of type const C& or two
8575 // parameters of type C.
8576
8577 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8578 bool IsMethod = isa<CXXMethodDecl>(FD);
8579 if (IsMethod) {
8580 auto *MD = cast<CXXMethodDecl>(FD);
8581 assert(!MD->isStatic() && "comparison function cannot be a static member")(static_cast <bool> (!MD->isStatic() && "comparison function cannot be a static member"
) ? void (0) : __assert_fail ("!MD->isStatic() && \"comparison function cannot be a static member\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8581, __extension__ __PRETTY_FUNCTION__
))
;
8582
8583 // If we're out-of-class, this is the class we're comparing.
8584 if (!RD)
8585 RD = MD->getParent();
8586
8587 if (!MD->isConst()) {
8588 SourceLocation InsertLoc;
8589 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8590 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8591 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8592 // corresponding defaulted 'operator<=>' already.
8593 if (!MD->isImplicit()) {
8594 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8595 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8596 }
8597
8598 // Add the 'const' to the type to recover.
8599 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8600 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8601 EPI.TypeQuals.addConst();
8602 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8603 FPT->getParamTypes(), EPI));
8604 }
8605 }
8606
8607 if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
8608 // Let's not worry about using a variadic template pack here -- who would do
8609 // such a thing?
8610 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8611 << int(IsMethod) << int(DCK);
8612 return true;
8613 }
8614
8615 const ParmVarDecl *KnownParm = nullptr;
8616 for (const ParmVarDecl *Param : FD->parameters()) {
8617 QualType ParmTy = Param->getType();
8618 if (ParmTy->isDependentType())
8619 continue;
8620 if (!KnownParm) {
8621 auto CTy = ParmTy;
8622 // Is it `T const &`?
8623 bool Ok = !IsMethod;
8624 QualType ExpectedTy;
8625 if (RD)
8626 ExpectedTy = Context.getRecordType(RD);
8627 if (auto *Ref = CTy->getAs<ReferenceType>()) {
8628 CTy = Ref->getPointeeType();
8629 if (RD)
8630 ExpectedTy.addConst();
8631 Ok = true;
8632 }
8633
8634 // Is T a class?
8635 if (!Ok) {
8636 } else if (RD) {
8637 if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8638 Ok = false;
8639 } else if (auto *CRD = CTy->getAsRecordDecl()) {
8640 RD = cast<CXXRecordDecl>(CRD);
8641 } else {
8642 Ok = false;
8643 }
8644
8645 if (Ok) {
8646 KnownParm = Param;
8647 } else {
8648 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8649 // corresponding defaulted 'operator<=>' already.
8650 if (!FD->isImplicit()) {
8651 if (RD) {
8652 QualType PlainTy = Context.getRecordType(RD);
8653 QualType RefTy =
8654 Context.getLValueReferenceType(PlainTy.withConst());
8655 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8656 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8657 << Param->getSourceRange();
8658 } else {
8659 assert(!IsMethod && "should know expected type for method")(static_cast <bool> (!IsMethod && "should know expected type for method"
) ? void (0) : __assert_fail ("!IsMethod && \"should know expected type for method\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8659, __extension__ __PRETTY_FUNCTION__
))
;
8660 Diag(FD->getLocation(),
8661 diag::err_defaulted_comparison_param_unknown)
8662 << int(DCK) << ParmTy << Param->getSourceRange();
8663 }
8664 }
8665 return true;
8666 }
8667 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8668 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8669 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8670 << ParmTy << Param->getSourceRange();
8671 return true;
8672 }
8673 }
8674
8675 assert(RD && "must have determined class")(static_cast <bool> (RD && "must have determined class"
) ? void (0) : __assert_fail ("RD && \"must have determined class\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8675, __extension__ __PRETTY_FUNCTION__
))
;
8676 if (IsMethod) {
8677 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8678 // In-class, must be a friend decl.
8679 assert(FD->getFriendObjectKind() && "expected a friend declaration")(static_cast <bool> (FD->getFriendObjectKind() &&
"expected a friend declaration") ? void (0) : __assert_fail (
"FD->getFriendObjectKind() && \"expected a friend declaration\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 8679, __extension__ __PRETTY_FUNCTION__
))
;
8680 } else {
8681 // Out of class, require the defaulted comparison to be a friend (of a
8682 // complete type).
8683 if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8684 diag::err_defaulted_comparison_not_friend, int(DCK),
8685 int(1)))
8686 return true;
8687
8688 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8689 return FD->getCanonicalDecl() ==
8690 F->getFriendDecl()->getCanonicalDecl();
8691 })) {
8692 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8693 << int(DCK) << int(0) << RD;
8694 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8695 return true;
8696 }
8697 }
8698
8699 // C++2a [class.eq]p1, [class.rel]p1:
8700 // A [defaulted comparison other than <=>] shall have a declared return
8701 // type bool.
8702 if (DCK != DefaultedComparisonKind::ThreeWay &&
8703 !FD->getDeclaredReturnType()->isDependentType() &&
8704 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8705 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8706 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8707 << FD->getReturnTypeSourceRange();
8708 return true;
8709 }
8710 // C++2a [class.spaceship]p2 [P2002R0]:
8711 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8712 // R shall not contain a placeholder type.
8713 if (QualType RT = FD->getDeclaredReturnType();
8714 DCK == DefaultedComparisonKind::ThreeWay &&
8715 RT->getContainedDeducedType() &&
8716 (!Context.hasSameType(RT, Context.getAutoDeductType()) ||
8717 RT->getContainedAutoType()->isConstrained())) {
8718 Diag(FD->getLocation(),
8719 diag::err_defaulted_comparison_deduced_return_type_not_auto)
8720 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8721 << FD->getReturnTypeSourceRange();
8722 return true;
8723 }
8724
8725 // For a defaulted function in a dependent class, defer all remaining checks
8726 // until instantiation.
8727 if (RD->isDependentType())
8728 return false;
8729
8730 // Determine whether the function should be defined as deleted.
8731 DefaultedComparisonInfo Info =
8732 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8733
8734 bool First = FD == FD->getCanonicalDecl();
8735
8736 // If we want to delete the function, then do so; there's nothing else to
8737 // check in that case.
8738 if (Info.Deleted) {
8739 if (!First) {
8740 // C++11 [dcl.fct.def.default]p4:
8741 // [For a] user-provided explicitly-defaulted function [...] if such a
8742 // function is implicitly defined as deleted, the program is ill-formed.
8743 //
8744 // This is really just a consequence of the general rule that you can
8745 // only delete a function on its first declaration.
8746 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8747 << FD->isImplicit() << (int)DCK;
8748 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8749 DefaultedComparisonAnalyzer::ExplainDeleted)
8750 .visit();
8751 return true;
8752 }
8753
8754 SetDeclDeleted(FD, FD->getLocation());
8755 if (!inTemplateInstantiation() && !FD->isImplicit()) {
8756 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8757 << (int)DCK;
8758 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8759 DefaultedComparisonAnalyzer::ExplainDeleted)
8760 .visit();
8761 if (FD->getDefaultLoc().isValid())
8762 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
8763 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
8764 }
8765 return false;
8766 }
8767
8768 // C++2a [class.spaceship]p2:
8769 // The return type is deduced as the common comparison type of R0, R1, ...
8770 if (DCK == DefaultedComparisonKind::ThreeWay &&
8771 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8772 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8773 if (RetLoc.isInvalid())
8774 RetLoc = FD->getBeginLoc();
8775 // FIXME: Should we really care whether we have the complete type and the
8776 // 'enumerator' constants here? A forward declaration seems sufficient.
8777 QualType Cat = CheckComparisonCategoryType(
8778 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8779 if (Cat.isNull())
8780 return true;
8781 Context.adjustDeducedFunctionResultType(
8782 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8783 }
8784
8785 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8786 // An explicitly-defaulted function that is not defined as deleted may be
8787 // declared constexpr or consteval only if it is constexpr-compatible.
8788 // C++2a [class.compare.default]p3 [P2002R0]:
8789 // A defaulted comparison function is constexpr-compatible if it satisfies
8790 // the requirements for a constexpr function [...]
8791 // The only relevant requirements are that the parameter and return types are
8792 // literal types. The remaining conditions are checked by the analyzer.
8793 if (FD->isConstexpr()) {
8794 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8795 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8796 !Info.Constexpr) {
8797 Diag(FD->getBeginLoc(),
8798 diag::err_incorrect_defaulted_comparison_constexpr)
8799 << FD->isImplicit() << (int)DCK << FD->isConsteval();
8800 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8801 DefaultedComparisonAnalyzer::ExplainConstexpr)
8802 .visit();
8803 }
8804 }
8805
8806 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8807 // If a constexpr-compatible function is explicitly defaulted on its first
8808 // declaration, it is implicitly considered to be constexpr.
8809 // FIXME: Only applying this to the first declaration seems problematic, as
8810 // simple reorderings can affect the meaning of the program.
8811 if (First && !FD->isConstexpr() && Info.Constexpr)
8812 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8813
8814 // C++2a [except.spec]p3:
8815 // If a declaration of a function does not have a noexcept-specifier
8816 // [and] is defaulted on its first declaration, [...] the exception
8817 // specification is as specified below
8818 if (FD->getExceptionSpecType() == EST_None) {
8819 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8820 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8821 EPI.ExceptionSpec.Type = EST_Unevaluated;
8822 EPI.ExceptionSpec.SourceDecl = FD;
8823 FD->setType(Context.getFunctionType(FPT->getReturnType(),
8824 FPT->getParamTypes(), EPI));
8825 }
8826
8827 return false;
8828}
8829
8830void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8831 FunctionDecl *Spaceship) {
8832 Sema::CodeSynthesisContext Ctx;
8833 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8834 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8835 Ctx.Entity = Spaceship;
8836 pushCodeSynthesisContext(Ctx);
8837
8838 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8839 EqualEqual->setImplicit();
8840
8841 popCodeSynthesisContext();
8842}
8843
8844void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8845 DefaultedComparisonKind DCK) {
8846 assert(FD->isDefaulted() && !FD->isDeleted() &&(static_cast <bool> (FD->isDefaulted() && !FD
->isDeleted() && !FD->doesThisDeclarationHaveABody
()) ? void (0) : __assert_fail ("FD->isDefaulted() && !FD->isDeleted() && !FD->doesThisDeclarationHaveABody()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8847, __extension__ __PRETTY_FUNCTION__
))
8847 !FD->doesThisDeclarationHaveABody())(static_cast <bool> (FD->isDefaulted() && !FD
->isDeleted() && !FD->doesThisDeclarationHaveABody
()) ? void (0) : __assert_fail ("FD->isDefaulted() && !FD->isDeleted() && !FD->doesThisDeclarationHaveABody()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8847, __extension__ __PRETTY_FUNCTION__
))
;
8848 if (FD->willHaveBody() || FD->isInvalidDecl())
8849 return;
8850
8851 SynthesizedFunctionScope Scope(*this, FD);
8852
8853 // Add a context note for diagnostics produced after this point.
8854 Scope.addContextNote(UseLoc);
8855
8856 {
8857 // Build and set up the function body.
8858 // The first parameter has type maybe-ref-to maybe-const T, use that to get
8859 // the type of the class being compared.
8860 auto PT = FD->getParamDecl(0)->getType();
8861 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
8862 SourceLocation BodyLoc =
8863 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8864 StmtResult Body =
8865 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8866 if (Body.isInvalid()) {
8867 FD->setInvalidDecl();
8868 return;
8869 }
8870 FD->setBody(Body.get());
8871 FD->markUsed(Context);
8872 }
8873
8874 // The exception specification is needed because we are defining the
8875 // function. Note that this will reuse the body we just built.
8876 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8877
8878 if (ASTMutationListener *L = getASTMutationListener())
8879 L->CompletedImplicitDefinition(FD);
8880}
8881
8882static Sema::ImplicitExceptionSpecification
8883ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8884 FunctionDecl *FD,
8885 Sema::DefaultedComparisonKind DCK) {
8886 ComputingExceptionSpec CES(S, FD, Loc);
8887 Sema::ImplicitExceptionSpecification ExceptSpec(S);
8888
8889 if (FD->isInvalidDecl())
8890 return ExceptSpec;
8891
8892 // The common case is that we just defined the comparison function. In that
8893 // case, just look at whether the body can throw.
8894 if (FD->hasBody()) {
8895 ExceptSpec.CalledStmt(FD->getBody());
8896 } else {
8897 // Otherwise, build a body so we can check it. This should ideally only
8898 // happen when we're not actually marking the function referenced. (This is
8899 // only really important for efficiency: we don't want to build and throw
8900 // away bodies for comparison functions more than we strictly need to.)
8901
8902 // Pretend to synthesize the function body in an unevaluated context.
8903 // Note that we can't actually just go ahead and define the function here:
8904 // we are not permitted to mark its callees as referenced.
8905 Sema::SynthesizedFunctionScope Scope(S, FD);
8906 EnterExpressionEvaluationContext Context(
8907 S, Sema::ExpressionEvaluationContext::Unevaluated);
8908
8909 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8910 SourceLocation BodyLoc =
8911 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8912 StmtResult Body =
8913 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8914 if (!Body.isInvalid())
8915 ExceptSpec.CalledStmt(Body.get());
8916
8917 // FIXME: Can we hold onto this body and just transform it to potentially
8918 // evaluated when we're asked to define the function rather than rebuilding
8919 // it? Either that, or we should only build the bits of the body that we
8920 // need (the expressions, not the statements).
8921 }
8922
8923 return ExceptSpec;
8924}
8925
8926void Sema::CheckDelayedMemberExceptionSpecs() {
8927 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8928 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8929
8930 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8931 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8932
8933 // Perform any deferred checking of exception specifications for virtual
8934 // destructors.
8935 for (auto &Check : Overriding)
8936 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8937
8938 // Perform any deferred checking of exception specifications for befriended
8939 // special members.
8940 for (auto &Check : Equivalent)
8941 CheckEquivalentExceptionSpec(Check.second, Check.first);
8942}
8943
8944namespace {
8945/// CRTP base class for visiting operations performed by a special member
8946/// function (or inherited constructor).
8947template<typename Derived>
8948struct SpecialMemberVisitor {
8949 Sema &S;
8950 CXXMethodDecl *MD;
8951 Sema::CXXSpecialMember CSM;
8952 Sema::InheritedConstructorInfo *ICI;
8953
8954 // Properties of the special member, computed for convenience.
8955 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8956
8957 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8958 Sema::InheritedConstructorInfo *ICI)
8959 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8960 switch (CSM) {
8961 case Sema::CXXDefaultConstructor:
8962 case Sema::CXXCopyConstructor:
8963 case Sema::CXXMoveConstructor:
8964 IsConstructor = true;
8965 break;
8966 case Sema::CXXCopyAssignment:
8967 case Sema::CXXMoveAssignment:
8968 IsAssignment = true;
8969 break;
8970 case Sema::CXXDestructor:
8971 break;
8972 case Sema::CXXInvalid:
8973 llvm_unreachable("invalid special member kind")::llvm::llvm_unreachable_internal("invalid special member kind"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8973)
;
8974 }
8975
8976 if (MD->getNumParams()) {
8977 if (const ReferenceType *RT =
8978 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8979 ConstArg = RT->getPointeeType().isConstQualified();
8980 }
8981 }
8982
8983 Derived &getDerived() { return static_cast<Derived&>(*this); }
8984
8985 /// Is this a "move" special member?
8986 bool isMove() const {
8987 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8988 }
8989
8990 /// Look up the corresponding special member in the given class.
8991 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8992 unsigned Quals, bool IsMutable) {
8993 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8994 ConstArg && !IsMutable);
8995 }
8996
8997 /// Look up the constructor for the specified base class to see if it's
8998 /// overridden due to this being an inherited constructor.
8999 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9000 if (!ICI)
9001 return {};
9002 assert(CSM == Sema::CXXDefaultConstructor)(static_cast <bool> (CSM == Sema::CXXDefaultConstructor
) ? void (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor"
, "clang/lib/Sema/SemaDeclCXX.cpp", 9002, __extension__ __PRETTY_FUNCTION__
))
;
9003 auto *BaseCtor =
9004 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
9005 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
9006 return MD;
9007 return {};
9008 }
9009
9010 /// A base or member subobject.
9011 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9012
9013 /// Get the location to use for a subobject in diagnostics.
9014 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9015 // FIXME: For an indirect virtual base, the direct base leading to
9016 // the indirect virtual base would be a more useful choice.
9017 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
9018 return B->getBaseTypeLoc();
9019 else
9020 return Subobj.get<FieldDecl*>()->getLocation();
9021 }
9022
9023 enum BasesToVisit {
9024 /// Visit all non-virtual (direct) bases.
9025 VisitNonVirtualBases,
9026 /// Visit all direct bases, virtual or not.
9027 VisitDirectBases,
9028 /// Visit all non-virtual bases, and all virtual bases if the class
9029 /// is not abstract.
9030 VisitPotentiallyConstructedBases,
9031 /// Visit all direct or virtual bases.
9032 VisitAllBases
9033 };
9034
9035 // Visit the bases and members of the class.
9036 bool visit(BasesToVisit Bases) {
9037 CXXRecordDecl *RD = MD->getParent();
9038
9039 if (Bases == VisitPotentiallyConstructedBases)
9040 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9041
9042 for (auto &B : RD->bases())
9043 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9044 getDerived().visitBase(&B))
9045 return true;
9046
9047 if (Bases == VisitAllBases)
9048 for (auto &B : RD->vbases())
9049 if (getDerived().visitBase(&B))
9050 return true;
9051
9052 for (auto *F : RD->fields())
9053 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
9054 getDerived().visitField(F))
9055 return true;
9056
9057 return false;
9058 }
9059};
9060}
9061
9062namespace {
9063struct SpecialMemberDeletionInfo
9064 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9065 bool Diagnose;
9066
9067 SourceLocation Loc;
9068
9069 bool AllFieldsAreConst;
9070
9071 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9072 Sema::CXXSpecialMember CSM,
9073 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9074 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9075 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9076
9077 bool inUnion() const { return MD->getParent()->isUnion(); }
9078
9079 Sema::CXXSpecialMember getEffectiveCSM() {
9080 return ICI ? Sema::CXXInvalid : CSM;
9081 }
9082
9083 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9084
9085 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9086 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9087
9088 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9089 bool shouldDeleteForField(FieldDecl *FD);
9090 bool shouldDeleteForAllConstMembers();
9091
9092 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9093 unsigned Quals);
9094 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9095 Sema::SpecialMemberOverloadResult SMOR,
9096 bool IsDtorCallInCtor);
9097
9098 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9099};
9100}
9101
9102/// Is the given special member inaccessible when used on the given
9103/// sub-object.
9104bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9105 CXXMethodDecl *target) {
9106 /// If we're operating on a base class, the object type is the
9107 /// type of this special member.
9108 QualType objectTy;
9109 AccessSpecifier access = target->getAccess();
9110 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9111 objectTy = S.Context.getTypeDeclType(MD->getParent());
9112 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9113
9114 // If we're operating on a field, the object type is the type of the field.
9115 } else {
9116 objectTy = S.Context.getTypeDeclType(target->getParent());
9117 }
9118
9119 return S.isMemberAccessibleForDeletion(
9120 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9121}
9122
9123/// Check whether we should delete a special member due to the implicit
9124/// definition containing a call to a special member of a subobject.
9125bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9126 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9127 bool IsDtorCallInCtor) {
9128 CXXMethodDecl *Decl = SMOR.getMethod();
9129 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9130
9131 int DiagKind = -1;
9132
9133 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9134 DiagKind = !Decl ? 0 : 1;
9135 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9136 DiagKind = 2;
9137 else if (!isAccessible(Subobj, Decl))
9138 DiagKind = 3;
9139 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9140 !Decl->isTrivial()) {
9141 // A member of a union must have a trivial corresponding special member.
9142 // As a weird special case, a destructor call from a union's constructor
9143 // must be accessible and non-deleted, but need not be trivial. Such a
9144 // destructor is never actually called, but is semantically checked as
9145 // if it were.
9146 DiagKind = 4;
9147 }
9148
9149 if (DiagKind == -1)
9150 return false;
9151
9152 if (Diagnose) {
9153 if (Field) {
9154 S.Diag(Field->getLocation(),
9155 diag::note_deleted_special_member_class_subobject)
9156 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9157 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9158 } else {
9159 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9160 S.Diag(Base->getBeginLoc(),
9161 diag::note_deleted_special_member_class_subobject)
9162 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9163 << Base->getType() << DiagKind << IsDtorCallInCtor
9164 << /*IsObjCPtr*/false;
9165 }
9166
9167 if (DiagKind == 1)
9168 S.NoteDeletedFunction(Decl);
9169 // FIXME: Explain inaccessibility if DiagKind == 3.
9170 }
9171
9172 return true;
9173}
9174
9175/// Check whether we should delete a special member function due to having a
9176/// direct or virtual base class or non-static data member of class type M.
9177bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9178 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9179 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9180 bool IsMutable = Field && Field->isMutable();
9181
9182 // C++11 [class.ctor]p5:
9183 // -- any direct or virtual base class, or non-static data member with no
9184 // brace-or-equal-initializer, has class type M (or array thereof) and
9185 // either M has no default constructor or overload resolution as applied
9186 // to M's default constructor results in an ambiguity or in a function
9187 // that is deleted or inaccessible
9188 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9189 // -- a direct or virtual base class B that cannot be copied/moved because
9190 // overload resolution, as applied to B's corresponding special member,
9191 // results in an ambiguity or a function that is deleted or inaccessible
9192 // from the defaulted special member
9193 // C++11 [class.dtor]p5:
9194 // -- any direct or virtual base class [...] has a type with a destructor
9195 // that is deleted or inaccessible
9196 if (!(CSM == Sema::CXXDefaultConstructor &&
9197 Field && Field->hasInClassInitializer()) &&
9198 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9199 false))
9200 return true;
9201
9202 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9203 // -- any direct or virtual base class or non-static data member has a
9204 // type with a destructor that is deleted or inaccessible
9205 if (IsConstructor) {
9206 Sema::SpecialMemberOverloadResult SMOR =
9207 S.LookupSpecialMember(Class, Sema::CXXDestructor,
9208 false, false, false, false, false);
9209 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9210 return true;
9211 }
9212
9213 return false;
9214}
9215
9216bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9217 FieldDecl *FD, QualType FieldType) {
9218 // The defaulted special functions are defined as deleted if this is a variant
9219 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9220 // type under ARC.
9221 if (!FieldType.hasNonTrivialObjCLifetime())
9222 return false;
9223
9224 // Don't make the defaulted default constructor defined as deleted if the
9225 // member has an in-class initializer.
9226 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9227 return false;
9228
9229 if (Diagnose) {
9230 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9231 S.Diag(FD->getLocation(),
9232 diag::note_deleted_special_member_class_subobject)
9233 << getEffectiveCSM() << ParentClass << /*IsField*/true
9234 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9235 }
9236
9237 return true;
9238}
9239
9240/// Check whether we should delete a special member function due to the class
9241/// having a particular direct or virtual base class.
9242bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9243 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9244 // If program is correct, BaseClass cannot be null, but if it is, the error
9245 // must be reported elsewhere.
9246 if (!BaseClass)
9247 return false;
9248 // If we have an inheriting constructor, check whether we're calling an
9249 // inherited constructor instead of a default constructor.
9250 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9251 if (auto *BaseCtor = SMOR.getMethod()) {
9252 // Note that we do not check access along this path; other than that,
9253 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9254 // FIXME: Check that the base has a usable destructor! Sink this into
9255 // shouldDeleteForClassSubobject.
9256 if (BaseCtor->isDeleted() && Diagnose) {
9257 S.Diag(Base->getBeginLoc(),
9258 diag::note_deleted_special_member_class_subobject)
9259 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9260 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9261 << /*IsObjCPtr*/false;
9262 S.NoteDeletedFunction(BaseCtor);
9263 }
9264 return BaseCtor->isDeleted();
9265 }
9266 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9267}
9268
9269/// Check whether we should delete a special member function due to the class
9270/// having a particular non-static data member.
9271bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9272 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9273 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9274
9275 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9276 return true;
9277
9278 if (CSM == Sema::CXXDefaultConstructor) {
9279 // For a default constructor, all references must be initialized in-class
9280 // and, if a union, it must have a non-const member.
9281 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9282 if (Diagnose)
9283 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9284 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9285 return true;
9286 }
9287 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9288 // data member of const-qualified type (or array thereof) with no
9289 // brace-or-equal-initializer is not const-default-constructible.
9290 if (!inUnion() && FieldType.isConstQualified() &&
9291 !FD->hasInClassInitializer() &&
9292 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9293 if (Diagnose)
9294 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9295 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9296 return true;
9297 }
9298
9299 if (inUnion() && !FieldType.isConstQualified())
9300 AllFieldsAreConst = false;
9301 } else if (CSM == Sema::CXXCopyConstructor) {
9302 // For a copy constructor, data members must not be of rvalue reference
9303 // type.
9304 if (FieldType->isRValueReferenceType()) {
9305 if (Diagnose)
9306 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9307 << MD->getParent() << FD << FieldType;
9308 return true;
9309 }
9310 } else if (IsAssignment) {
9311 // For an assignment operator, data members must not be of reference type.
9312 if (FieldType->isReferenceType()) {
9313 if (Diagnose)
9314 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9315 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9316 return true;
9317 }
9318 if (!FieldRecord && FieldType.isConstQualified()) {
9319 // C++11 [class.copy]p23:
9320 // -- a non-static data member of const non-class type (or array thereof)
9321 if (Diagnose)
9322 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9323 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9324 return true;
9325 }
9326 }
9327
9328 if (FieldRecord) {
9329 // Some additional restrictions exist on the variant members.
9330 if (!inUnion() && FieldRecord->isUnion() &&
9331 FieldRecord->isAnonymousStructOrUnion()) {
9332 bool AllVariantFieldsAreConst = true;
9333
9334 // FIXME: Handle anonymous unions declared within anonymous unions.
9335 for (auto *UI : FieldRecord->fields()) {
9336 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9337
9338 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9339 return true;
9340
9341 if (!UnionFieldType.isConstQualified())
9342 AllVariantFieldsAreConst = false;
9343
9344 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9345 if (UnionFieldRecord &&
9346 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9347 UnionFieldType.getCVRQualifiers()))
9348 return true;
9349 }
9350
9351 // At least one member in each anonymous union must be non-const
9352 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9353 !FieldRecord->field_empty()) {
9354 if (Diagnose)
9355 S.Diag(FieldRecord->getLocation(),
9356 diag::note_deleted_default_ctor_all_const)
9357 << !!ICI << MD->getParent() << /*anonymous union*/1;
9358 return true;
9359 }
9360
9361 // Don't check the implicit member of the anonymous union type.
9362 // This is technically non-conformant but supported, and we have a
9363 // diagnostic for this elsewhere.
9364 return false;
9365 }
9366
9367 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9368 FieldType.getCVRQualifiers()))
9369 return true;
9370 }
9371
9372 return false;
9373}
9374
9375/// C++11 [class.ctor] p5:
9376/// A defaulted default constructor for a class X is defined as deleted if
9377/// X is a union and all of its variant members are of const-qualified type.
9378bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9379 // This is a silly definition, because it gives an empty union a deleted
9380 // default constructor. Don't do that.
9381 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9382 bool AnyFields = false;
9383 for (auto *F : MD->getParent()->fields())
9384 if ((AnyFields = !F->isUnnamedBitfield()))
9385 break;
9386 if (!AnyFields)
9387 return false;
9388 if (Diagnose)
9389 S.Diag(MD->getParent()->getLocation(),
9390 diag::note_deleted_default_ctor_all_const)
9391 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9392 return true;
9393 }
9394 return false;
9395}
9396
9397/// Determine whether a defaulted special member function should be defined as
9398/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9399/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9400bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9401 InheritedConstructorInfo *ICI,
9402 bool Diagnose) {
9403 if (MD->isInvalidDecl())
9404 return false;
9405 CXXRecordDecl *RD = MD->getParent();
9406 assert(!RD->isDependentType() && "do deletion after instantiation")(static_cast <bool> (!RD->isDependentType() &&
"do deletion after instantiation") ? void (0) : __assert_fail
("!RD->isDependentType() && \"do deletion after instantiation\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 9406, __extension__ __PRETTY_FUNCTION__
))
;
9407 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9408 return false;
9409
9410 // C++11 [expr.lambda.prim]p19:
9411 // The closure type associated with a lambda-expression has a
9412 // deleted (8.4.3) default constructor and a deleted copy
9413 // assignment operator.
9414 // C++2a adds back these operators if the lambda has no lambda-capture.
9415 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9416 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9417 if (Diagnose)
9418 Diag(RD->getLocation(), diag::note_lambda_decl);
9419 return true;
9420 }
9421
9422 // For an anonymous struct or union, the copy and assignment special members
9423 // will never be used, so skip the check. For an anonymous union declared at
9424 // namespace scope, the constructor and destructor are used.
9425 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9426 RD->isAnonymousStructOrUnion())
9427 return false;
9428
9429 // C++11 [class.copy]p7, p18:
9430 // If the class definition declares a move constructor or move assignment
9431 // operator, an implicitly declared copy constructor or copy assignment
9432 // operator is defined as deleted.
9433 if (MD->isImplicit() &&
9434 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9435 CXXMethodDecl *UserDeclaredMove = nullptr;
9436
9437 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9438 // deletion of the corresponding copy operation, not both copy operations.
9439 // MSVC 2015 has adopted the standards conforming behavior.
9440 bool DeletesOnlyMatchingCopy =
9441 getLangOpts().MSVCCompat &&
9442 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9443
9444 if (RD->hasUserDeclaredMoveConstructor() &&
9445 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9446 if (!Diagnose) return true;
9447
9448 // Find any user-declared move constructor.
9449 for (auto *I : RD->ctors()) {
9450 if (I->isMoveConstructor()) {
9451 UserDeclaredMove = I;
9452 break;
9453 }
9454 }
9455 assert(UserDeclaredMove)(static_cast <bool> (UserDeclaredMove) ? void (0) : __assert_fail
("UserDeclaredMove", "clang/lib/Sema/SemaDeclCXX.cpp", 9455,
__extension__ __PRETTY_FUNCTION__))
;
9456 } else if (RD->hasUserDeclaredMoveAssignment() &&
9457 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9458 if (!Diagnose) return true;
9459
9460 // Find any user-declared move assignment operator.
9461 for (auto *I : RD->methods()) {
9462 if (I->isMoveAssignmentOperator()) {
9463 UserDeclaredMove = I;
9464 break;
9465 }
9466 }
9467 assert(UserDeclaredMove)(static_cast <bool> (UserDeclaredMove) ? void (0) : __assert_fail
("UserDeclaredMove", "clang/lib/Sema/SemaDeclCXX.cpp", 9467,
__extension__ __PRETTY_FUNCTION__))
;
9468 }
9469
9470 if (UserDeclaredMove) {
9471 Diag(UserDeclaredMove->getLocation(),
9472 diag::note_deleted_copy_user_declared_move)
9473 << (CSM == CXXCopyAssignment) << RD
9474 << UserDeclaredMove->isMoveAssignmentOperator();
9475 return true;
9476 }
9477 }
9478
9479 // Do access control from the special member function
9480 ContextRAII MethodContext(*this, MD);
9481
9482 // C++11 [class.dtor]p5:
9483 // -- for a virtual destructor, lookup of the non-array deallocation function
9484 // results in an ambiguity or in a function that is deleted or inaccessible
9485 if (CSM == CXXDestructor && MD->isVirtual()) {
9486 FunctionDecl *OperatorDelete = nullptr;
9487 DeclarationName Name =
9488 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9489 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9490 OperatorDelete, /*Diagnose*/false)) {
9491 if (Diagnose)
9492 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9493 return true;
9494 }
9495 }
9496
9497 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9498
9499 // Per DR1611, do not consider virtual bases of constructors of abstract
9500 // classes, since we are not going to construct them.
9501 // Per DR1658, do not consider virtual bases of destructors of abstract
9502 // classes either.
9503 // Per DR2180, for assignment operators we only assign (and thus only
9504 // consider) direct bases.
9505 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9506 : SMI.VisitPotentiallyConstructedBases))
9507 return true;
9508
9509 if (SMI.shouldDeleteForAllConstMembers())
9510 return true;
9511
9512 if (getLangOpts().CUDA) {
9513 // We should delete the special member in CUDA mode if target inference
9514 // failed.
9515 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9516 // is treated as certain special member, which may not reflect what special
9517 // member MD really is. However inferCUDATargetForImplicitSpecialMember
9518 // expects CSM to match MD, therefore recalculate CSM.
9519 assert(ICI || CSM == getSpecialMember(MD))(static_cast <bool> (ICI || CSM == getSpecialMember(MD)
) ? void (0) : __assert_fail ("ICI || CSM == getSpecialMember(MD)"
, "clang/lib/Sema/SemaDeclCXX.cpp", 9519, __extension__ __PRETTY_FUNCTION__
))
;
9520 auto RealCSM = CSM;
9521 if (ICI)
9522 RealCSM = getSpecialMember(MD);
9523
9524 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9525 SMI.ConstArg, Diagnose);
9526 }
9527
9528 return false;
9529}
9530
9531void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9532 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9533 assert(DFK && "not a defaultable function")(static_cast <bool> (DFK && "not a defaultable function"
) ? void (0) : __assert_fail ("DFK && \"not a defaultable function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 9533, __extension__ __PRETTY_FUNCTION__
))
;
9534 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted")(static_cast <bool> (FD->isDefaulted() && FD
->isDeleted() && "not defaulted and deleted") ? void
(0) : __assert_fail ("FD->isDefaulted() && FD->isDeleted() && \"not defaulted and deleted\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 9534, __extension__ __PRETTY_FUNCTION__
))
;
9535
9536 if (DFK.isSpecialMember()) {
9537 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9538 nullptr, /*Diagnose=*/true);
9539 } else {
9540 DefaultedComparisonAnalyzer(
9541 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9542 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9543 .visit();
9544 }
9545}
9546
9547/// Perform lookup for a special member of the specified kind, and determine
9548/// whether it is trivial. If the triviality can be determined without the
9549/// lookup, skip it. This is intended for use when determining whether a
9550/// special member of a containing object is trivial, and thus does not ever
9551/// perform overload resolution for default constructors.
9552///
9553/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9554/// member that was most likely to be intended to be trivial, if any.
9555///
9556/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9557/// determine whether the special member is trivial.
9558static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9559 Sema::CXXSpecialMember CSM, unsigned Quals,
9560 bool ConstRHS,
9561 Sema::TrivialABIHandling TAH,
9562 CXXMethodDecl **Selected) {
9563 if (Selected)
9564 *Selected = nullptr;
9565
9566 switch (CSM) {
9567 case Sema::CXXInvalid:
9568 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "clang/lib/Sema/SemaDeclCXX.cpp"
, 9568)
;
9569
9570 case Sema::CXXDefaultConstructor:
9571 // C++11 [class.ctor]p5:
9572 // A default constructor is trivial if:
9573 // - all the [direct subobjects] have trivial default constructors
9574 //
9575 // Note, no overload resolution is performed in this case.
9576 if (RD->hasTrivialDefaultConstructor())
9577 return true;
9578
9579 if (Selected) {
9580 // If there's a default constructor which could have been trivial, dig it
9581 // out. Otherwise, if there's any user-provided default constructor, point
9582 // to that as an example of why there's not a trivial one.
9583 CXXConstructorDecl *DefCtor = nullptr;
9584 if (RD->needsImplicitDefaultConstructor())
9585 S.DeclareImplicitDefaultConstructor(RD);
9586 for (auto *CI : RD->ctors()) {
9587 if (!CI->isDefaultConstructor())
9588 continue;
9589 DefCtor = CI;
9590 if (!DefCtor->isUserProvided())
9591 break;
9592 }
9593
9594 *Selected = DefCtor;
9595 }
9596
9597 return false;
9598
9599 case Sema::CXXDestructor:
9600 // C++11 [class.dtor]p5:
9601 // A destructor is trivial if:
9602 // - all the direct [subobjects] have trivial destructors
9603 if (RD->hasTrivialDestructor() ||
9604 (TAH == Sema::TAH_ConsiderTrivialABI &&
9605 RD->hasTrivialDestructorForCall()))
9606 return true;
9607
9608 if (Selected) {
9609 if (RD->needsImplicitDestructor())
9610 S.DeclareImplicitDestructor(RD);
9611 *Selected = RD->getDestructor();
9612 }
9613
9614 return false;
9615
9616 case Sema::CXXCopyConstructor:
9617 // C++11 [class.copy]p12:
9618 // A copy constructor is trivial if:
9619 // - the constructor selected to copy each direct [subobject] is trivial
9620 if (RD->hasTrivialCopyConstructor() ||
9621 (TAH == Sema::TAH_ConsiderTrivialABI &&
9622 RD->hasTrivialCopyConstructorForCall())) {
9623 if (Quals == Qualifiers::Const)
9624 // We must either select the trivial copy constructor or reach an
9625 // ambiguity; no need to actually perform overload resolution.
9626 return true;
9627 } else if (!Selected) {
9628 return false;
9629 }
9630 // In C++98, we are not supposed to perform overload resolution here, but we
9631 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9632 // cases like B as having a non-trivial copy constructor:
9633 // struct A { template<typename T> A(T&); };
9634 // struct B { mutable A a; };
9635 goto NeedOverloadResolution;
9636
9637 case Sema::CXXCopyAssignment:
9638 // C++11 [class.copy]p25:
9639 // A copy assignment operator is trivial if:
9640 // - the assignment operator selected to copy each direct [subobject] is
9641 // trivial
9642 if (RD->hasTrivialCopyAssignment()) {
9643 if (Quals == Qualifiers::Const)
9644 return true;
9645 } else if (!Selected) {
9646 return false;
9647 }
9648 // In C++98, we are not supposed to perform overload resolution here, but we
9649 // treat that as a language defect.
9650 goto NeedOverloadResolution;
9651
9652 case Sema::CXXMoveConstructor:
9653 case Sema::CXXMoveAssignment:
9654 NeedOverloadResolution:
9655 Sema::SpecialMemberOverloadResult SMOR =
9656 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9657
9658 // The standard doesn't describe how to behave if the lookup is ambiguous.
9659 // We treat it as not making the member non-trivial, just like the standard
9660 // mandates for the default constructor. This should rarely matter, because
9661 // the member will also be deleted.
9662 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9663 return true;
9664
9665 if (!SMOR.getMethod()) {
9666 assert(SMOR.getKind() ==(static_cast <bool> (SMOR.getKind() == Sema::SpecialMemberOverloadResult
::NoMemberOrDeleted) ? void (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted"
, "clang/lib/Sema/SemaDeclCXX.cpp", 9667, __extension__ __PRETTY_FUNCTION__
))
9667 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)(static_cast <bool> (SMOR.getKind() == Sema::SpecialMemberOverloadResult
::NoMemberOrDeleted) ? void (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted"
, "clang/lib/Sema/SemaDeclCXX.cpp", 9667, __extension__ __PRETTY_FUNCTION__
))
;
9668 return false;
9669 }
9670
9671 // We deliberately don't check if we found a deleted special member. We're
9672 // not supposed to!
9673 if (Selected)
9674 *Selected = SMOR.getMethod();
9675
9676 if (TAH == Sema::TAH_ConsiderTrivialABI &&
9677 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9678 return SMOR.getMethod()->isTrivialForCall();
9679 return SMOR.getMethod()->isTrivial();
9680 }
9681
9682 llvm_unreachable("unknown special method kind")::llvm::llvm_unreachable_internal("unknown special method kind"
, "clang/lib/Sema/SemaDeclCXX.cpp", 9682)
;
9683}
9684
9685static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9686 for (auto *CI : RD->ctors())
9687 if (!CI->isImplicit())
9688 return CI;
9689
9690 // Look for constructor templates.
9691 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9692 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9693 if (CXXConstructorDecl *CD =
9694 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9695 return CD;
9696 }
9697
9698 return nullptr;
9699}
9700
9701/// The kind of subobject we are checking for triviality. The values of this
9702/// enumeration are used in diagnostics.
9703enum TrivialSubobjectKind {
9704 /// The subobject is a base class.
9705 TSK_BaseClass,
9706 /// The subobject is a non-static data member.
9707 TSK_Field,
9708 /// The object is actually the complete object.
9709 TSK_CompleteObject
9710};
9711
9712/// Check whether the special member selected for a given type would be trivial.
9713static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9714 QualType SubType, bool ConstRHS,
9715 Sema::CXXSpecialMember CSM,
9716 TrivialSubobjectKind Kind,
9717 Sema::TrivialABIHandling TAH, bool Diagnose) {
9718 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9719 if (!SubRD)
9720 return true;
9721
9722 CXXMethodDecl *Selected;
9723 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9724 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9725 return true;
9726
9727 if (Diagnose) {
9728 if (ConstRHS)
9729 SubType.addConst();
9730
9731 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9732 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9733 << Kind << SubType.getUnqualifiedType();
9734 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9735 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9736 } else if (!Selected)
9737 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9738 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9739 else if (Selected->isUserProvided()) {
9740 if (Kind == TSK_CompleteObject)
9741 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9742 << Kind << SubType.getUnqualifiedType() << CSM;
9743 else {
9744 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9745 << Kind << SubType.getUnqualifiedType() << CSM;
9746 S.Diag(Selected->getLocation(), diag::note_declared_at);
9747 }
9748 } else {
9749 if (Kind != TSK_CompleteObject)
9750 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9751 << Kind << SubType.getUnqualifiedType() << CSM;
9752
9753 // Explain why the defaulted or deleted special member isn't trivial.
9754 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9755 Diagnose);
9756 }
9757 }
9758
9759 return false;
9760}
9761
9762/// Check whether the members of a class type allow a special member to be
9763/// trivial.
9764static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9765 Sema::CXXSpecialMember CSM,
9766 bool ConstArg,
9767 Sema::TrivialABIHandling TAH,
9768 bool Diagnose) {
9769 for (const auto *FI : RD->fields()) {
9770 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9771 continue;
9772
9773 QualType FieldType = S.Context.getBaseElementType(FI->getType());
9774
9775 // Pretend anonymous struct or union members are members of this class.
9776 if (FI->isAnonymousStructOrUnion()) {
9777 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9778 CSM, ConstArg, TAH, Diagnose))
9779 return false;
9780 continue;
9781 }
9782
9783 // C++11 [class.ctor]p5:
9784 // A default constructor is trivial if [...]
9785 // -- no non-static data member of its class has a
9786 // brace-or-equal-initializer
9787 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9788 if (Diagnose)
9789 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9790 << FI;
9791 return false;
9792 }
9793
9794 // Objective C ARC 4.3.5:
9795 // [...] nontrivally ownership-qualified types are [...] not trivially
9796 // default constructible, copy constructible, move constructible, copy
9797 // assignable, move assignable, or destructible [...]
9798 if (FieldType.hasNonTrivialObjCLifetime()) {
9799 if (Diagnose)
9800 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9801 << RD << FieldType.getObjCLifetime();
9802 return false;
9803 }
9804
9805 bool ConstRHS = ConstArg && !FI->isMutable();
9806 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9807 CSM, TSK_Field, TAH, Diagnose))
9808 return false;
9809 }
9810
9811 return true;
9812}
9813
9814/// Diagnose why the specified class does not have a trivial special member of
9815/// the given kind.
9816void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9817 QualType Ty = Context.getRecordType(RD);
9818
9819 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9820 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9821 TSK_CompleteObject, TAH_IgnoreTrivialABI,
9822 /*Diagnose*/true);
9823}
9824
9825/// Determine whether a defaulted or deleted special member function is trivial,
9826/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9827/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9828bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9829 TrivialABIHandling TAH, bool Diagnose) {
9830 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough")(static_cast <bool> (!MD->isUserProvided() &&
CSM != CXXInvalid && "not special enough") ? void (0
) : __assert_fail ("!MD->isUserProvided() && CSM != CXXInvalid && \"not special enough\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 9830, __extension__ __PRETTY_FUNCTION__
))
;
9831
9832 CXXRecordDecl *RD = MD->getParent();
9833
9834 bool ConstArg = false;
9835
9836 // C++11 [class.copy]p12, p25: [DR1593]
9837 // A [special member] is trivial if [...] its parameter-type-list is
9838 // equivalent to the parameter-type-list of an implicit declaration [...]
9839 switch (CSM) {
9840 case CXXDefaultConstructor:
9841 case CXXDestructor:
9842 // Trivial default constructors and destructors cannot have parameters.
9843 break;
9844
9845 case CXXCopyConstructor:
9846 case CXXCopyAssignment: {
9847 const ParmVarDecl *Param0 = MD->getParamDecl(0);
9848 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9849
9850 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
9851 // if they are not user-provided and their parameter-type-list is equivalent
9852 // to the parameter-type-list of an implicit declaration. This maintains the
9853 // behavior before dr2171 was implemented.
9854 //
9855 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
9856 // trivial, if they are not user-provided, regardless of the qualifiers on
9857 // the reference type.
9858 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
9859 LangOptions::ClangABI::Ver14;
9860 if (!RT ||
9861 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
9862 ClangABICompat14)) {
9863 if (Diagnose)
9864 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9865 << Param0->getSourceRange() << Param0->getType()
9866 << Context.getLValueReferenceType(
9867 Context.getRecordType(RD).withConst());
9868 return false;
9869 }
9870
9871 ConstArg = RT->getPointeeType().isConstQualified();
9872 break;
9873 }
9874
9875 case CXXMoveConstructor:
9876 case CXXMoveAssignment: {
9877 // Trivial move operations always have non-cv-qualified parameters.
9878 const ParmVarDecl *Param0 = MD->getParamDecl(0);
9879 const RValueReferenceType *RT =
9880 Param0->getType()->getAs<RValueReferenceType>();
9881 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9882 if (Diagnose)
9883 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9884 << Param0->getSourceRange() << Param0->getType()
9885 << Context.getRValueReferenceType(Context.getRecordType(RD));
9886 return false;
9887 }
9888 break;
9889 }
9890
9891 case CXXInvalid:
9892 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "clang/lib/Sema/SemaDeclCXX.cpp"
, 9892)
;
9893 }
9894
9895 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9896 if (Diagnose)
9897 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9898 diag::note_nontrivial_default_arg)
9899 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9900 return false;
9901 }
9902 if (MD->isVariadic()) {
9903 if (Diagnose)
9904 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9905 return false;
9906 }
9907
9908 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9909 // A copy/move [constructor or assignment operator] is trivial if
9910 // -- the [member] selected to copy/move each direct base class subobject
9911 // is trivial
9912 //
9913 // C++11 [class.copy]p12, C++11 [class.copy]p25:
9914 // A [default constructor or destructor] is trivial if
9915 // -- all the direct base classes have trivial [default constructors or
9916 // destructors]
9917 for (const auto &BI : RD->bases())
9918 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9919 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9920 return false;
9921
9922 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9923 // A copy/move [constructor or assignment operator] for a class X is
9924 // trivial if
9925 // -- for each non-static data member of X that is of class type (or array
9926 // thereof), the constructor selected to copy/move that member is
9927 // trivial
9928 //
9929 // C++11 [class.copy]p12, C++11 [class.copy]p25:
9930 // A [default constructor or destructor] is trivial if
9931 // -- for all of the non-static data members of its class that are of class
9932 // type (or array thereof), each such class has a trivial [default
9933 // constructor or destructor]
9934 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9935 return false;
9936
9937 // C++11 [class.dtor]p5:
9938 // A destructor is trivial if [...]
9939 // -- the destructor is not virtual
9940 if (CSM == CXXDestructor && MD->isVirtual()) {
9941 if (Diagnose)
9942 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9943 return false;
9944 }
9945
9946 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9947 // A [special member] for class X is trivial if [...]
9948 // -- class X has no virtual functions and no virtual base classes
9949 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9950 if (!Diagnose)
9951 return false;
9952
9953 if (RD->getNumVBases()) {
9954 // Check for virtual bases. We already know that the corresponding
9955 // member in all bases is trivial, so vbases must all be direct.
9956 CXXBaseSpecifier &BS = *RD->vbases_begin();
9957 assert(BS.isVirtual())(static_cast <bool> (BS.isVirtual()) ? void (0) : __assert_fail
("BS.isVirtual()", "clang/lib/Sema/SemaDeclCXX.cpp", 9957, __extension__
__PRETTY_FUNCTION__))
;
9958 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9959 return false;
9960 }
9961
9962 // Must have a virtual method.
9963 for (const auto *MI : RD->methods()) {
9964 if (MI->isVirtual()) {
9965 SourceLocation MLoc = MI->getBeginLoc();
9966 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9967 return false;
9968 }
9969 }
9970
9971 llvm_unreachable("dynamic class with no vbases and no virtual functions")::llvm::llvm_unreachable_internal("dynamic class with no vbases and no virtual functions"
, "clang/lib/Sema/SemaDeclCXX.cpp", 9971)
;
9972 }
9973
9974 // Looks like it's trivial!
9975 return true;
9976}
9977
9978namespace {
9979struct FindHiddenVirtualMethod {
9980 Sema *S;
9981 CXXMethodDecl *Method;
9982 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9983 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9984
9985private:
9986 /// Check whether any most overridden method from MD in Methods
9987 static bool CheckMostOverridenMethods(
9988 const CXXMethodDecl *MD,
9989 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9990 if (MD->size_overridden_methods() == 0)
9991 return Methods.count(MD->getCanonicalDecl());
9992 for (const CXXMethodDecl *O : MD->overridden_methods())
9993 if (CheckMostOverridenMethods(O, Methods))
9994 return true;
9995 return false;
9996 }
9997
9998public:
9999 /// Member lookup function that determines whether a given C++
10000 /// method overloads virtual methods in a base class without overriding any,
10001 /// to be used with CXXRecordDecl::lookupInBases().
10002 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10003 RecordDecl *BaseRecord =
10004 Specifier->getType()->castAs<RecordType>()->getDecl();
10005
10006 DeclarationName Name = Method->getDeclName();
10007 assert(Name.getNameKind() == DeclarationName::Identifier)(static_cast <bool> (Name.getNameKind() == DeclarationName
::Identifier) ? void (0) : __assert_fail ("Name.getNameKind() == DeclarationName::Identifier"
, "clang/lib/Sema/SemaDeclCXX.cpp", 10007, __extension__ __PRETTY_FUNCTION__
))
;
10008
10009 bool foundSameNameMethod = false;
10010 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10011 for (Path.Decls = BaseRecord->lookup(Name).begin();
10012 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10013 NamedDecl *D = *Path.Decls;
10014 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
10015 MD = MD->getCanonicalDecl();
10016 foundSameNameMethod = true;
10017 // Interested only in hidden virtual methods.
10018 if (!MD->isVirtual())
10019 continue;
10020 // If the method we are checking overrides a method from its base
10021 // don't warn about the other overloaded methods. Clang deviates from
10022 // GCC by only diagnosing overloads of inherited virtual functions that
10023 // do not override any other virtual functions in the base. GCC's
10024 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10025 // function from a base class. These cases may be better served by a
10026 // warning (not specific to virtual functions) on call sites when the
10027 // call would select a different function from the base class, were it
10028 // visible.
10029 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10030 if (!S->IsOverload(Method, MD, false))
10031 return true;
10032 // Collect the overload only if its hidden.
10033 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
10034 overloadedMethods.push_back(MD);
10035 }
10036 }
10037
10038 if (foundSameNameMethod)
10039 OverloadedMethods.append(overloadedMethods.begin(),
10040 overloadedMethods.end());
10041 return foundSameNameMethod;
10042 }
10043};
10044} // end anonymous namespace
10045
10046/// Add the most overridden methods from MD to Methods
10047static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10048 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10049 if (MD->size_overridden_methods() == 0)
10050 Methods.insert(MD->getCanonicalDecl());
10051 else
10052 for (const CXXMethodDecl *O : MD->overridden_methods())
10053 AddMostOverridenMethods(O, Methods);
10054}
10055
10056/// Check if a method overloads virtual methods in a base class without
10057/// overriding any.
10058void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10059 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10060 if (!MD->getDeclName().isIdentifier())
10061 return;
10062
10063 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10064 /*bool RecordPaths=*/false,
10065 /*bool DetectVirtual=*/false);
10066 FindHiddenVirtualMethod FHVM;
10067 FHVM.Method = MD;
10068 FHVM.S = this;
10069
10070 // Keep the base methods that were overridden or introduced in the subclass
10071 // by 'using' in a set. A base method not in this set is hidden.
10072 CXXRecordDecl *DC = MD->getParent();
10073 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
10074 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10075 NamedDecl *ND = *I;
10076 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10077 ND = shad->getTargetDecl();
10078 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10079 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10080 }
10081
10082 if (DC->lookupInBases(FHVM, Paths))
10083 OverloadedMethods = FHVM.OverloadedMethods;
10084}
10085
10086void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10087 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10088 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10089 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10090 PartialDiagnostic PD = PDiag(
10091 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10092 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10093 Diag(overloadedMD->getLocation(), PD);
10094 }
10095}
10096
10097/// Diagnose methods which overload virtual methods in a base class
10098/// without overriding any.
10099void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10100 if (MD->isInvalidDecl())
10101 return;
10102
10103 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10104 return;
10105
10106 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10107 FindHiddenVirtualMethods(MD, OverloadedMethods);
10108 if (!OverloadedMethods.empty()) {
10109 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10110 << MD << (OverloadedMethods.size() > 1);
10111
10112 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10113 }
10114}
10115
10116void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10117 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10118 // No diagnostics if this is a template instantiation.
10119 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
10120 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10121 diag::ext_cannot_use_trivial_abi) << &RD;
10122 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10123 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10124 }
10125 RD.dropAttr<TrivialABIAttr>();
10126 };
10127
10128 // Ill-formed if the copy and move constructors are deleted.
10129 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10130 // If the type is dependent, then assume it might have
10131 // implicit copy or move ctor because we won't know yet at this point.
10132 if (RD.isDependentType())
10133 return true;
10134 if (RD.needsImplicitCopyConstructor() &&
10135 !RD.defaultedCopyConstructorIsDeleted())
10136 return true;
10137 if (RD.needsImplicitMoveConstructor() &&
10138 !RD.defaultedMoveConstructorIsDeleted())
10139 return true;
10140 for (const CXXConstructorDecl *CD : RD.ctors())
10141 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10142 return true;
10143 return false;
10144 };
10145
10146 if (!HasNonDeletedCopyOrMoveConstructor()) {
10147 PrintDiagAndRemoveAttr(0);
10148 return;
10149 }
10150
10151 // Ill-formed if the struct has virtual functions.
10152 if (RD.isPolymorphic()) {
10153 PrintDiagAndRemoveAttr(1);
10154 return;
10155 }
10156
10157 for (const auto &B : RD.bases()) {
10158 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10159 // virtual base.
10160 if (!B.getType()->isDependentType() &&
10161 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10162 PrintDiagAndRemoveAttr(2);
10163 return;
10164 }
10165
10166 if (B.isVirtual()) {
10167 PrintDiagAndRemoveAttr(3);
10168 return;
10169 }
10170 }
10171
10172 for (const auto *FD : RD.fields()) {
10173 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10174 // non-trivial for the purpose of calls.
10175 QualType FT = FD->getType();
10176 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10177 PrintDiagAndRemoveAttr(4);
10178 return;
10179 }
10180
10181 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10182 if (!RT->isDependentType() &&
10183 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10184 PrintDiagAndRemoveAttr(5);
10185 return;
10186 }
10187 }
10188}
10189
10190void Sema::ActOnFinishCXXMemberSpecification(
10191 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10192 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10193 if (!TagDecl)
10194 return;
10195
10196 AdjustDeclIfTemplate(TagDecl);
10197
10198 for (const ParsedAttr &AL : AttrList) {
10199 if (AL.getKind() != ParsedAttr::AT_Visibility)
10200 continue;
10201 AL.setInvalid();
10202 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10203 }
10204
10205 ActOnFields(S, RLoc, TagDecl,
10206 llvm::ArrayRef(
10207 // strict aliasing violation!
10208 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10209 FieldCollector->getCurNumFields()),
10210 LBrac, RBrac, AttrList);
10211
10212 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10213}
10214
10215/// Find the equality comparison functions that should be implicitly declared
10216/// in a given class definition, per C++2a [class.compare.default]p3.
10217static void findImplicitlyDeclaredEqualityComparisons(
10218 ASTContext &Ctx, CXXRecordDecl *RD,
10219 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10220 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10221 if (!RD->lookup(EqEq).empty())
10222 // Member operator== explicitly declared: no implicit operator==s.
10223 return;
10224
10225 // Traverse friends looking for an '==' or a '<=>'.
10226 for (FriendDecl *Friend : RD->friends()) {
10227 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10228 if (!FD) continue;
10229
10230 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10231 // Friend operator== explicitly declared: no implicit operator==s.
10232 Spaceships.clear();
10233 return;
10234 }
10235
10236 if (FD->getOverloadedOperator() == OO_Spaceship &&
10237 FD->isExplicitlyDefaulted())
10238 Spaceships.push_back(FD);
10239 }
10240
10241 // Look for members named 'operator<=>'.
10242 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10243 for (NamedDecl *ND : RD->lookup(Cmp)) {
10244 // Note that we could find a non-function here (either a function template
10245 // or a using-declaration). Neither case results in an implicit
10246 // 'operator=='.
10247 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10248 if (FD->isExplicitlyDefaulted())
10249 Spaceships.push_back(FD);
10250 }
10251}
10252
10253/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10254/// special functions, such as the default constructor, copy
10255/// constructor, or destructor, to the given C++ class (C++
10256/// [special]p1). This routine can only be executed just before the
10257/// definition of the class is complete.
10258void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10259 // Don't add implicit special members to templated classes.
10260 // FIXME: This means unqualified lookups for 'operator=' within a class
10261 // template don't work properly.
10262 if (!ClassDecl->isDependentType()) {
10263 if (ClassDecl->needsImplicitDefaultConstructor()) {
10264 ++getASTContext().NumImplicitDefaultConstructors;
10265
10266 if (ClassDecl->hasInheritedConstructor())
10267 DeclareImplicitDefaultConstructor(ClassDecl);
10268 }
10269
10270 if (ClassDecl->needsImplicitCopyConstructor()) {
10271 ++getASTContext().NumImplicitCopyConstructors;
10272
10273 // If the properties or semantics of the copy constructor couldn't be
10274 // determined while the class was being declared, force a declaration
10275 // of it now.
10276 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10277 ClassDecl->hasInheritedConstructor())
10278 DeclareImplicitCopyConstructor(ClassDecl);
10279 // For the MS ABI we need to know whether the copy ctor is deleted. A
10280 // prerequisite for deleting the implicit copy ctor is that the class has
10281 // a move ctor or move assignment that is either user-declared or whose
10282 // semantics are inherited from a subobject. FIXME: We should provide a
10283 // more direct way for CodeGen to ask whether the constructor was deleted.
10284 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10285 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10286 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10287 ClassDecl->hasUserDeclaredMoveAssignment() ||
10288 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10289 DeclareImplicitCopyConstructor(ClassDecl);
10290 }
10291
10292 if (getLangOpts().CPlusPlus11 &&
10293 ClassDecl->needsImplicitMoveConstructor()) {
10294 ++getASTContext().NumImplicitMoveConstructors;
10295
10296 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10297 ClassDecl->hasInheritedConstructor())
10298 DeclareImplicitMoveConstructor(ClassDecl);
10299 }
10300
10301 if (ClassDecl->needsImplicitCopyAssignment()) {
10302 ++getASTContext().NumImplicitCopyAssignmentOperators;
10303
10304 // If we have a dynamic class, then the copy assignment operator may be
10305 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10306 // it shows up in the right place in the vtable and that we diagnose
10307 // problems with the implicit exception specification.
10308 if (ClassDecl->isDynamicClass() ||
10309 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10310 ClassDecl->hasInheritedAssignment())
10311 DeclareImplicitCopyAssignment(ClassDecl);
10312 }
10313
10314 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10315 ++getASTContext().NumImplicitMoveAssignmentOperators;
10316
10317 // Likewise for the move assignment operator.
10318 if (ClassDecl->isDynamicClass() ||
10319 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10320 ClassDecl->hasInheritedAssignment())
10321 DeclareImplicitMoveAssignment(ClassDecl);
10322 }
10323
10324 if (ClassDecl->needsImplicitDestructor()) {
10325 ++getASTContext().NumImplicitDestructors;
10326
10327 // If we have a dynamic class, then the destructor may be virtual, so we
10328 // have to declare the destructor immediately. This ensures that, e.g., it
10329 // shows up in the right place in the vtable and that we diagnose problems
10330 // with the implicit exception specification.
10331 if (ClassDecl->isDynamicClass() ||
10332 ClassDecl->needsOverloadResolutionForDestructor())
10333 DeclareImplicitDestructor(ClassDecl);
10334 }
10335 }
10336
10337 // C++2a [class.compare.default]p3:
10338 // If the member-specification does not explicitly declare any member or
10339 // friend named operator==, an == operator function is declared implicitly
10340 // for each defaulted three-way comparison operator function defined in
10341 // the member-specification
10342 // FIXME: Consider doing this lazily.
10343 // We do this during the initial parse for a class template, not during
10344 // instantiation, so that we can handle unqualified lookups for 'operator=='
10345 // when parsing the template.
10346 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10347 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10348 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10349 DefaultedSpaceships);
10350 for (auto *FD : DefaultedSpaceships)
10351 DeclareImplicitEqualityComparison(ClassDecl, FD);
10352 }
10353}
10354
10355unsigned
10356Sema::ActOnReenterTemplateScope(Decl *D,
10357 llvm::function_ref<Scope *()> EnterScope) {
10358 if (!D)
10359 return 0;
10360 AdjustDeclIfTemplate(D);
10361
10362 // In order to get name lookup right, reenter template scopes in order from
10363 // outermost to innermost.
10364 SmallVector<TemplateParameterList *, 4> ParameterLists;
10365 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10366
10367 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10368 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10369 ParameterLists.push_back(DD->getTemplateParameterList(i));
10370
10371 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10372 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10373 ParameterLists.push_back(FTD->getTemplateParameters());
10374 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10375 LookupDC = VD->getDeclContext();
10376
10377 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10378 ParameterLists.push_back(VTD->getTemplateParameters());
10379 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10380 ParameterLists.push_back(PSD->getTemplateParameters());
10381 }
10382 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10383 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10384 ParameterLists.push_back(TD->getTemplateParameterList(i));
10385
10386 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10387 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10388 ParameterLists.push_back(CTD->getTemplateParameters());
10389 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10390 ParameterLists.push_back(PSD->getTemplateParameters());
10391 }
10392 }
10393 // FIXME: Alias declarations and concepts.
10394
10395 unsigned Count = 0;
10396 Scope *InnermostTemplateScope = nullptr;
10397 for (TemplateParameterList *Params : ParameterLists) {
10398 // Ignore explicit specializations; they don't contribute to the template
10399 // depth.
10400 if (Params->size() == 0)
10401 continue;
10402
10403 InnermostTemplateScope = EnterScope();
10404 for (NamedDecl *Param : *Params) {
10405 if (Param->getDeclName()) {
10406 InnermostTemplateScope->AddDecl(Param);
10407 IdResolver.AddDecl(Param);
10408 }
10409 }
10410 ++Count;
10411 }
10412
10413 // Associate the new template scopes with the corresponding entities.
10414 if (InnermostTemplateScope) {
10415 assert(LookupDC && "no enclosing DeclContext for template lookup")(static_cast <bool> (LookupDC && "no enclosing DeclContext for template lookup"
) ? void (0) : __assert_fail ("LookupDC && \"no enclosing DeclContext for template lookup\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 10415, __extension__ __PRETTY_FUNCTION__
))
;
10416 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10417 }
10418
10419 return Count;
10420}
10421
10422void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10423 if (!RecordD) return;
10424 AdjustDeclIfTemplate(RecordD);
10425 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10426 PushDeclContext(S, Record);
10427}
10428
10429void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10430 if (!RecordD) return;
10431 PopDeclContext();
10432}
10433
10434/// This is used to implement the constant expression evaluation part of the
10435/// attribute enable_if extension. There is nothing in standard C++ which would
10436/// require reentering parameters.
10437void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10438 if (!Param)
10439 return;
10440
10441 S->AddDecl(Param);
10442 if (Param->getDeclName())
10443 IdResolver.AddDecl(Param);
10444}
10445
10446/// ActOnStartDelayedCXXMethodDeclaration - We have completed
10447/// parsing a top-level (non-nested) C++ class, and we are now
10448/// parsing those parts of the given Method declaration that could
10449/// not be parsed earlier (C++ [class.mem]p2), such as default
10450/// arguments. This action should enter the scope of the given
10451/// Method declaration as if we had just parsed the qualified method
10452/// name. However, it should not bring the parameters into scope;
10453/// that will be performed by ActOnDelayedCXXMethodParameter.
10454void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10455}
10456
10457/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10458/// C++ method declaration. We're (re-)introducing the given
10459/// function parameter into scope for use in parsing later parts of
10460/// the method declaration. For example, we could see an
10461/// ActOnParamDefaultArgument event for this parameter.
10462void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10463 if (!ParamD)
10464 return;
10465
10466 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10467
10468 S->AddDecl(Param);
10469 if (Param->getDeclName())
10470 IdResolver.AddDecl(Param);
10471}
10472
10473/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10474/// processing the delayed method declaration for Method. The method
10475/// declaration is now considered finished. There may be a separate
10476/// ActOnStartOfFunctionDef action later (not necessarily
10477/// immediately!) for this method, if it was also defined inside the
10478/// class body.
10479void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10480 if (!MethodD)
10481 return;
10482
10483 AdjustDeclIfTemplate(MethodD);
10484
10485 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10486
10487 // Now that we have our default arguments, check the constructor
10488 // again. It could produce additional diagnostics or affect whether
10489 // the class has implicitly-declared destructors, among other
10490 // things.
10491 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10492 CheckConstructor(Constructor);
10493
10494 // Check the default arguments, which we may have added.
10495 if (!Method->isInvalidDecl())
10496 CheckCXXDefaultArguments(Method);
10497}
10498
10499// Emit the given diagnostic for each non-address-space qualifier.
10500// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10501static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10502 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10503 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10504 bool DiagOccured = false;
10505 FTI.MethodQualifiers->forEachQualifier(
10506 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10507 SourceLocation SL) {
10508 // This diagnostic should be emitted on any qualifier except an addr
10509 // space qualifier. However, forEachQualifier currently doesn't visit
10510 // addr space qualifiers, so there's no way to write this condition
10511 // right now; we just diagnose on everything.
10512 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10513 DiagOccured = true;
10514 });
10515 if (DiagOccured)
10516 D.setInvalidType();
10517 }
10518}
10519
10520/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10521/// the well-formedness of the constructor declarator @p D with type @p
10522/// R. If there are any errors in the declarator, this routine will
10523/// emit diagnostics and set the invalid bit to true. In any case, the type
10524/// will be updated to reflect a well-formed type for the constructor and
10525/// returned.
10526QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10527 StorageClass &SC) {
10528 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10529
10530 // C++ [class.ctor]p3:
10531 // A constructor shall not be virtual (10.3) or static (9.4). A
10532 // constructor can be invoked for a const, volatile or const
10533 // volatile object. A constructor shall not be declared const,
10534 // volatile, or const volatile (9.3.2).
10535 if (isVirtual) {
10536 if (!D.isInvalidType())
10537 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10538 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10539 << SourceRange(D.getIdentifierLoc());
10540 D.setInvalidType();
10541 }
10542 if (SC == SC_Static) {
10543 if (!D.isInvalidType())
10544 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10545 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10546 << SourceRange(D.getIdentifierLoc());
10547 D.setInvalidType();
10548 SC = SC_None;
10549 }
10550
10551 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10552 diagnoseIgnoredQualifiers(
10553 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10554 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10555 D.getDeclSpec().getRestrictSpecLoc(),
10556 D.getDeclSpec().getAtomicSpecLoc());
10557 D.setInvalidType();
10558 }
10559
10560 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10561
10562 // C++0x [class.ctor]p4:
10563 // A constructor shall not be declared with a ref-qualifier.
10564 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10565 if (FTI.hasRefQualifier()) {
10566 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10567 << FTI.RefQualifierIsLValueRef
10568 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10569 D.setInvalidType();
10570 }
10571
10572 // Rebuild the function type "R" without any type qualifiers (in
10573 // case any of the errors above fired) and with "void" as the
10574 // return type, since constructors don't have return types.
10575 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10576 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10577 return R;
10578
10579 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10580 EPI.TypeQuals = Qualifiers();
10581 EPI.RefQualifier = RQ_None;
10582
10583 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10584}
10585
10586/// CheckConstructor - Checks a fully-formed constructor for
10587/// well-formedness, issuing any diagnostics required. Returns true if
10588/// the constructor declarator is invalid.
10589void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10590 CXXRecordDecl *ClassDecl
10591 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10592 if (!ClassDecl)
10593 return Constructor->setInvalidDecl();
10594
10595 // C++ [class.copy]p3:
10596 // A declaration of a constructor for a class X is ill-formed if
10597 // its first parameter is of type (optionally cv-qualified) X and
10598 // either there are no other parameters or else all other
10599 // parameters have default arguments.
10600 if (!Constructor->isInvalidDecl() &&
10601 Constructor->hasOneParamOrDefaultArgs() &&
10602 Constructor->getTemplateSpecializationKind() !=
10603 TSK_ImplicitInstantiation) {
10604 QualType ParamType = Constructor->getParamDecl(0)->getType();
10605 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10606 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10607 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10608 const char *ConstRef
10609 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10610 : " const &";
10611 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10612 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10613
10614 // FIXME: Rather that making the constructor invalid, we should endeavor
10615 // to fix the type.
10616 Constructor->setInvalidDecl();
10617 }
10618 }
10619}
10620
10621/// CheckDestructor - Checks a fully-formed destructor definition for
10622/// well-formedness, issuing any diagnostics required. Returns true
10623/// on error.
10624bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10625 CXXRecordDecl *RD = Destructor->getParent();
10626
10627 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10628 SourceLocation Loc;
10629
10630 if (!Destructor->isImplicit())
10631 Loc = Destructor->getLocation();
10632 else
10633 Loc = RD->getLocation();
10634
10635 // If we have a virtual destructor, look up the deallocation function
10636 if (FunctionDecl *OperatorDelete =
10637 FindDeallocationFunctionForDestructor(Loc, RD)) {
10638 Expr *ThisArg = nullptr;
10639
10640 // If the notional 'delete this' expression requires a non-trivial
10641 // conversion from 'this' to the type of a destroying operator delete's
10642 // first parameter, perform that conversion now.
10643 if (OperatorDelete->isDestroyingOperatorDelete()) {
10644 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10645 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10646 // C++ [class.dtor]p13:
10647 // ... as if for the expression 'delete this' appearing in a
10648 // non-virtual destructor of the destructor's class.
10649 ContextRAII SwitchContext(*this, Destructor);
10650 ExprResult This =
10651 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10652 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?")(static_cast <bool> (!This.isInvalid() && "couldn't form 'this' expr in dtor?"
) ? void (0) : __assert_fail ("!This.isInvalid() && \"couldn't form 'this' expr in dtor?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 10652, __extension__ __PRETTY_FUNCTION__
))
;
10653 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10654 if (This.isInvalid()) {
10655 // FIXME: Register this as a context note so that it comes out
10656 // in the right order.
10657 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10658 return true;
10659 }
10660 ThisArg = This.get();
10661 }
10662 }
10663
10664 DiagnoseUseOfDecl(OperatorDelete, Loc);
10665 MarkFunctionReferenced(Loc, OperatorDelete);
10666 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10667 }
10668 }
10669
10670 return false;
10671}
10672
10673/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10674/// the well-formednes of the destructor declarator @p D with type @p
10675/// R. If there are any errors in the declarator, this routine will
10676/// emit diagnostics and set the declarator to invalid. Even if this happens,
10677/// will be updated to reflect a well-formed type for the destructor and
10678/// returned.
10679QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10680 StorageClass& SC) {
10681 // C++ [class.dtor]p1:
10682 // [...] A typedef-name that names a class is a class-name
10683 // (7.1.3); however, a typedef-name that names a class shall not
10684 // be used as the identifier in the declarator for a destructor
10685 // declaration.
10686 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10687 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10688 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10689 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10690 else if (const TemplateSpecializationType *TST =
10691 DeclaratorType->getAs<TemplateSpecializationType>())
10692 if (TST->isTypeAlias())
10693 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10694 << DeclaratorType << 1;
10695
10696 // C++ [class.dtor]p2:
10697 // A destructor is used to destroy objects of its class type. A
10698 // destructor takes no parameters, and no return type can be
10699 // specified for it (not even void). The address of a destructor
10700 // shall not be taken. A destructor shall not be static. A
10701 // destructor can be invoked for a const, volatile or const
10702 // volatile object. A destructor shall not be declared const,
10703 // volatile or const volatile (9.3.2).
10704 if (SC == SC_Static) {
10705 if (!D.isInvalidType())
10706 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10707 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10708 << SourceRange(D.getIdentifierLoc())
10709 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10710
10711 SC = SC_None;
10712 }
10713 if (!D.isInvalidType()) {
10714 // Destructors don't have return types, but the parser will
10715 // happily parse something like:
10716 //
10717 // class X {
10718 // float ~X();
10719 // };
10720 //
10721 // The return type will be eliminated later.
10722 if (D.getDeclSpec().hasTypeSpecifier())
10723 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10724 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10725 << SourceRange(D.getIdentifierLoc());
10726 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10727 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10728 SourceLocation(),
10729 D.getDeclSpec().getConstSpecLoc(),
10730 D.getDeclSpec().getVolatileSpecLoc(),
10731 D.getDeclSpec().getRestrictSpecLoc(),
10732 D.getDeclSpec().getAtomicSpecLoc());
10733 D.setInvalidType();
10734 }
10735 }
10736
10737 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10738
10739 // C++0x [class.dtor]p2:
10740 // A destructor shall not be declared with a ref-qualifier.
10741 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10742 if (FTI.hasRefQualifier()) {
10743 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10744 << FTI.RefQualifierIsLValueRef
10745 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10746 D.setInvalidType();
10747 }
10748
10749 // Make sure we don't have any parameters.
10750 if (FTIHasNonVoidParameters(FTI)) {
10751 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10752
10753 // Delete the parameters.
10754 FTI.freeParams();
10755 D.setInvalidType();
10756 }
10757
10758 // Make sure the destructor isn't variadic.
10759 if (FTI.isVariadic) {
10760 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10761 D.setInvalidType();
10762 }
10763
10764 // Rebuild the function type "R" without any type qualifiers or
10765 // parameters (in case any of the errors above fired) and with
10766 // "void" as the return type, since destructors don't have return
10767 // types.
10768 if (!D.isInvalidType())
10769 return R;
10770
10771 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10772 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10773 EPI.Variadic = false;
10774 EPI.TypeQuals = Qualifiers();
10775 EPI.RefQualifier = RQ_None;
10776 return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI);
10777}
10778
10779static void extendLeft(SourceRange &R, SourceRange Before) {
10780 if (Before.isInvalid())
10781 return;
10782 R.setBegin(Before.getBegin());
10783 if (R.getEnd().isInvalid())
10784 R.setEnd(Before.getEnd());
10785}
10786
10787static void extendRight(SourceRange &R, SourceRange After) {
10788 if (After.isInvalid())
10789 return;
10790 if (R.getBegin().isInvalid())
10791 R.setBegin(After.getBegin());
10792 R.setEnd(After.getEnd());
10793}
10794
10795/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10796/// well-formednes of the conversion function declarator @p D with
10797/// type @p R. If there are any errors in the declarator, this routine
10798/// will emit diagnostics and return true. Otherwise, it will return
10799/// false. Either way, the type @p R will be updated to reflect a
10800/// well-formed type for the conversion operator.
10801void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10802 StorageClass& SC) {
10803 // C++ [class.conv.fct]p1:
10804 // Neither parameter types nor return type can be specified. The
10805 // type of a conversion function (8.3.5) is "function taking no
10806 // parameter returning conversion-type-id."
10807 if (SC == SC_Static) {
10808 if (!D.isInvalidType())
10809 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10810 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10811 << D.getName().getSourceRange();
10812 D.setInvalidType();
10813 SC = SC_None;
10814 }
10815
10816 TypeSourceInfo *ConvTSI = nullptr;
10817 QualType ConvType =
10818 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10819
10820 const DeclSpec &DS = D.getDeclSpec();
10821 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10822 // Conversion functions don't have return types, but the parser will
10823 // happily parse something like:
10824 //
10825 // class X {
10826 // float operator bool();
10827 // };
10828 //
10829 // The return type will be changed later anyway.
10830 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10831 << SourceRange(DS.getTypeSpecTypeLoc())
10832 << SourceRange(D.getIdentifierLoc());
10833 D.setInvalidType();
10834 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10835 // It's also plausible that the user writes type qualifiers in the wrong
10836 // place, such as:
10837 // struct S { const operator int(); };
10838 // FIXME: we could provide a fixit to move the qualifiers onto the
10839 // conversion type.
10840 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10841 << SourceRange(D.getIdentifierLoc()) << 0;
10842 D.setInvalidType();
10843 }
10844
10845 const auto *Proto = R->castAs<FunctionProtoType>();
10846
10847 // Make sure we don't have any parameters.
10848 if (Proto->getNumParams() > 0) {
10849 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10850
10851 // Delete the parameters.
10852 D.getFunctionTypeInfo().freeParams();
10853 D.setInvalidType();
10854 } else if (Proto->isVariadic()) {
10855 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10856 D.setInvalidType();
10857 }
10858
10859 // Diagnose "&operator bool()" and other such nonsense. This
10860 // is actually a gcc extension which we don't support.
10861 if (Proto->getReturnType() != ConvType) {
10862 bool NeedsTypedef = false;
10863 SourceRange Before, After;
10864
10865 // Walk the chunks and extract information on them for our diagnostic.
10866 bool PastFunctionChunk = false;
10867 for (auto &Chunk : D.type_objects()) {
10868 switch (Chunk.Kind) {
10869 case DeclaratorChunk::Function:
10870 if (!PastFunctionChunk) {
10871 if (Chunk.Fun.HasTrailingReturnType) {
10872 TypeSourceInfo *TRT = nullptr;
10873 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10874 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10875 }
10876 PastFunctionChunk = true;
10877 break;
10878 }
10879 [[fallthrough]];
10880 case DeclaratorChunk::Array:
10881 NeedsTypedef = true;
10882 extendRight(After, Chunk.getSourceRange());
10883 break;
10884
10885 case DeclaratorChunk::Pointer:
10886 case DeclaratorChunk::BlockPointer:
10887 case DeclaratorChunk::Reference:
10888 case DeclaratorChunk::MemberPointer:
10889 case DeclaratorChunk::Pipe:
10890 extendLeft(Before, Chunk.getSourceRange());
10891 break;
10892
10893 case DeclaratorChunk::Paren:
10894 extendLeft(Before, Chunk.Loc);
10895 extendRight(After, Chunk.EndLoc);
10896 break;
10897 }
10898 }
10899
10900 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10901 After.isValid() ? After.getBegin() :
10902 D.getIdentifierLoc();
10903 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10904 DB << Before << After;
10905
10906 if (!NeedsTypedef) {
10907 DB << /*don't need a typedef*/0;
10908
10909 // If we can provide a correct fix-it hint, do so.
10910 if (After.isInvalid() && ConvTSI) {
10911 SourceLocation InsertLoc =
10912 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10913 DB << FixItHint::CreateInsertion(InsertLoc, " ")
10914 << FixItHint::CreateInsertionFromRange(
10915 InsertLoc, CharSourceRange::getTokenRange(Before))
10916 << FixItHint::CreateRemoval(Before);
10917 }
10918 } else if (!Proto->getReturnType()->isDependentType()) {
10919 DB << /*typedef*/1 << Proto->getReturnType();
10920 } else if (getLangOpts().CPlusPlus11) {
10921 DB << /*alias template*/2 << Proto->getReturnType();
10922 } else {
10923 DB << /*might not be fixable*/3;
10924 }
10925
10926 // Recover by incorporating the other type chunks into the result type.
10927 // Note, this does *not* change the name of the function. This is compatible
10928 // with the GCC extension:
10929 // struct S { &operator int(); } s;
10930 // int &r = s.operator int(); // ok in GCC
10931 // S::operator int&() {} // error in GCC, function name is 'operator int'.
10932 ConvType = Proto->getReturnType();
10933 }
10934
10935 // C++ [class.conv.fct]p4:
10936 // The conversion-type-id shall not represent a function type nor
10937 // an array type.
10938 if (ConvType->isArrayType()) {
10939 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10940 ConvType = Context.getPointerType(ConvType);
10941 D.setInvalidType();
10942 } else if (ConvType->isFunctionType()) {
10943 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10944 ConvType = Context.getPointerType(ConvType);
10945 D.setInvalidType();
10946 }
10947
10948 // Rebuild the function type "R" without any parameters (in case any
10949 // of the errors above fired) and with the conversion type as the
10950 // return type.
10951 if (D.isInvalidType())
10952 R = Context.getFunctionType(ConvType, std::nullopt,
10953 Proto->getExtProtoInfo());
10954
10955 // C++0x explicit conversion operators.
10956 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10957 Diag(DS.getExplicitSpecLoc(),
10958 getLangOpts().CPlusPlus11
10959 ? diag::warn_cxx98_compat_explicit_conversion_functions
10960 : diag::ext_explicit_conversion_functions)
10961 << SourceRange(DS.getExplicitSpecRange());
10962}
10963
10964/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10965/// the declaration of the given C++ conversion function. This routine
10966/// is responsible for recording the conversion function in the C++
10967/// class, if possible.
10968Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10969 assert(Conversion && "Expected to receive a conversion function declaration")(static_cast <bool> (Conversion && "Expected to receive a conversion function declaration"
) ? void (0) : __assert_fail ("Conversion && \"Expected to receive a conversion function declaration\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 10969, __extension__ __PRETTY_FUNCTION__
))
;
10970
10971 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10972
10973 // Make sure we aren't redeclaring the conversion function.
10974 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10975 // C++ [class.conv.fct]p1:
10976 // [...] A conversion function is never used to convert a
10977 // (possibly cv-qualified) object to the (possibly cv-qualified)
10978 // same object type (or a reference to it), to a (possibly
10979 // cv-qualified) base class of that type (or a reference to it),
10980 // or to (possibly cv-qualified) void.
10981 QualType ClassType
10982 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10983 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10984 ConvType = ConvTypeRef->getPointeeType();
10985 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10986 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10987 /* Suppress diagnostics for instantiations. */;
10988 else if (Conversion->size_overridden_methods() != 0)
10989 /* Suppress diagnostics for overriding virtual function in a base class. */;
10990 else if (ConvType->isRecordType()) {
10991 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10992 if (ConvType == ClassType)
10993 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10994 << ClassType;
10995 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10996 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10997 << ClassType << ConvType;
10998 } else if (ConvType->isVoidType()) {
10999 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
11000 << ClassType << ConvType;
11001 }
11002
11003 if (FunctionTemplateDecl *ConversionTemplate
11004 = Conversion->getDescribedFunctionTemplate())
11005 return ConversionTemplate;
11006
11007 return Conversion;
11008}
11009
11010namespace {
11011/// Utility class to accumulate and print a diagnostic listing the invalid
11012/// specifier(s) on a declaration.
11013struct BadSpecifierDiagnoser {
11014 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11015 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11016 ~BadSpecifierDiagnoser() {
11017 Diagnostic << Specifiers;
11018 }
11019
11020 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11021 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11022 }
11023 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11024 return check(SpecLoc,
11025 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
11026 }
11027 void check(SourceLocation SpecLoc, const char *Spec) {
11028 if (SpecLoc.isInvalid()) return;
11029 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11030 if (!Specifiers.empty()) Specifiers += " ";
11031 Specifiers += Spec;
11032 }
11033
11034 Sema &S;
11035 Sema::SemaDiagnosticBuilder Diagnostic;
11036 std::string Specifiers;
11037};
11038}
11039
11040/// Check the validity of a declarator that we parsed for a deduction-guide.
11041/// These aren't actually declarators in the grammar, so we need to check that
11042/// the user didn't specify any pieces that are not part of the deduction-guide
11043/// grammar.
11044void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11045 StorageClass &SC) {
11046 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11047 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11048 assert(GuidedTemplateDecl && "missing template decl for deduction guide")(static_cast <bool> (GuidedTemplateDecl && "missing template decl for deduction guide"
) ? void (0) : __assert_fail ("GuidedTemplateDecl && \"missing template decl for deduction guide\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11048, __extension__ __PRETTY_FUNCTION__
))
;
11049
11050 // C++ [temp.deduct.guide]p3:
11051 // A deduction-gide shall be declared in the same scope as the
11052 // corresponding class template.
11053 if (!CurContext->getRedeclContext()->Equals(
11054 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11055 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11056 << GuidedTemplateDecl;
11057 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
11058 }
11059
11060 auto &DS = D.getMutableDeclSpec();
11061 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11062 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11063 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11064 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11065 BadSpecifierDiagnoser Diagnoser(
11066 *this, D.getIdentifierLoc(),
11067 diag::err_deduction_guide_invalid_specifier);
11068
11069 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11070 DS.ClearStorageClassSpecs();
11071 SC = SC_None;
11072
11073 // 'explicit' is permitted.
11074 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11075 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11076 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11077 DS.ClearConstexprSpec();
11078
11079 Diagnoser.check(DS.getConstSpecLoc(), "const");
11080 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11081 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11082 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11083 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11084 DS.ClearTypeQualifiers();
11085
11086 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11087 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11088 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11089 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11090 DS.ClearTypeSpecType();
11091 }
11092
11093 if (D.isInvalidType())
11094 return;
11095
11096 // Check the declarator is simple enough.
11097 bool FoundFunction = false;
11098 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11099 if (Chunk.Kind == DeclaratorChunk::Paren)
11100 continue;
11101 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11102 Diag(D.getDeclSpec().getBeginLoc(),
11103 diag::err_deduction_guide_with_complex_decl)
11104 << D.getSourceRange();
11105 break;
11106 }
11107 if (!Chunk.Fun.hasTrailingReturnType()) {
11108 Diag(D.getName().getBeginLoc(),
11109 diag::err_deduction_guide_no_trailing_return_type);
11110 break;
11111 }
11112
11113 // Check that the return type is written as a specialization of
11114 // the template specified as the deduction-guide's name.
11115 // The template name may not be qualified. [temp.deduct.guide]
11116 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11117 TypeSourceInfo *TSI = nullptr;
11118 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11119 assert(TSI && "deduction guide has valid type but invalid return type?")(static_cast <bool> (TSI && "deduction guide has valid type but invalid return type?"
) ? void (0) : __assert_fail ("TSI && \"deduction guide has valid type but invalid return type?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11119, __extension__ __PRETTY_FUNCTION__
))
;
11120 bool AcceptableReturnType = false;
11121 bool MightInstantiateToSpecialization = false;
11122 if (auto RetTST =
11123 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11124 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11125 bool TemplateMatches =
11126 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11127 auto TKind = SpecifiedName.getKind();
11128 // A Using TemplateName can't actually be valid (either it's qualified, or
11129 // we're in the wrong scope). But we have diagnosed these problems
11130 // already.
11131 bool SimplyWritten = TKind == TemplateName::Template ||
11132 TKind == TemplateName::UsingTemplate;
11133 if (SimplyWritten && TemplateMatches)
11134 AcceptableReturnType = true;
11135 else {
11136 // This could still instantiate to the right type, unless we know it
11137 // names the wrong class template.
11138 auto *TD = SpecifiedName.getAsTemplateDecl();
11139 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11140 !TemplateMatches);
11141 }
11142 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11143 MightInstantiateToSpecialization = true;
11144 }
11145
11146 if (!AcceptableReturnType) {
11147 Diag(TSI->getTypeLoc().getBeginLoc(),
11148 diag::err_deduction_guide_bad_trailing_return_type)
11149 << GuidedTemplate << TSI->getType()
11150 << MightInstantiateToSpecialization
11151 << TSI->getTypeLoc().getSourceRange();
11152 }
11153
11154 // Keep going to check that we don't have any inner declarator pieces (we
11155 // could still have a function returning a pointer to a function).
11156 FoundFunction = true;
11157 }
11158
11159 if (D.isFunctionDefinition())
11160 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11161}
11162
11163//===----------------------------------------------------------------------===//
11164// Namespace Handling
11165//===----------------------------------------------------------------------===//
11166
11167/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11168/// reopened.
11169static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11170 SourceLocation Loc,
11171 IdentifierInfo *II, bool *IsInline,
11172 NamespaceDecl *PrevNS) {
11173 assert(*IsInline != PrevNS->isInline())(static_cast <bool> (*IsInline != PrevNS->isInline()
) ? void (0) : __assert_fail ("*IsInline != PrevNS->isInline()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 11173, __extension__ __PRETTY_FUNCTION__
))
;
11174
11175 // 'inline' must appear on the original definition, but not necessarily
11176 // on all extension definitions, so the note should point to the first
11177 // definition to avoid confusion.
11178 PrevNS = PrevNS->getFirstDecl();
11179
11180 if (PrevNS->isInline())
11181 // The user probably just forgot the 'inline', so suggest that it
11182 // be added back.
11183 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11184 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11185 else
11186 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11187
11188 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11189 *IsInline = PrevNS->isInline();
11190}
11191
11192/// ActOnStartNamespaceDef - This is called at the start of a namespace
11193/// definition.
11194Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11195 SourceLocation InlineLoc,
11196 SourceLocation NamespaceLoc,
11197 SourceLocation IdentLoc, IdentifierInfo *II,
11198 SourceLocation LBrace,
11199 const ParsedAttributesView &AttrList,
11200 UsingDirectiveDecl *&UD, bool IsNested) {
11201 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11202 // For anonymous namespace, take the location of the left brace.
11203 SourceLocation Loc = II ? IdentLoc : LBrace;
11204 bool IsInline = InlineLoc.isValid();
11205 bool IsInvalid = false;
11206 bool IsStd = false;
11207 bool AddToKnown = false;
11208 Scope *DeclRegionScope = NamespcScope->getParent();
11209
11210 NamespaceDecl *PrevNS = nullptr;
11211 if (II) {
11212 // C++ [namespace.def]p2:
11213 // The identifier in an original-namespace-definition shall not
11214 // have been previously defined in the declarative region in
11215 // which the original-namespace-definition appears. The
11216 // identifier in an original-namespace-definition is the name of
11217 // the namespace. Subsequently in that declarative region, it is
11218 // treated as an original-namespace-name.
11219 //
11220 // Since namespace names are unique in their scope, and we don't
11221 // look through using directives, just look for any ordinary names
11222 // as if by qualified name lookup.
11223 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11224 ForExternalRedeclaration);
11225 LookupQualifiedName(R, CurContext->getRedeclContext());
11226 NamedDecl *PrevDecl =
11227 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11228 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11229
11230 if (PrevNS) {
11231 // This is an extended namespace definition.
11232 if (IsInline != PrevNS->isInline())
11233 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11234 &IsInline, PrevNS);
11235 } else if (PrevDecl) {
11236 // This is an invalid name redefinition.
11237 Diag(Loc, diag::err_redefinition_different_kind)
11238 << II;
11239 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11240 IsInvalid = true;
11241 // Continue on to push Namespc as current DeclContext and return it.
11242 } else if (II->isStr("std") &&
11243 CurContext->getRedeclContext()->isTranslationUnit()) {
11244 // This is the first "real" definition of the namespace "std", so update
11245 // our cache of the "std" namespace to point at this definition.
11246 PrevNS = getStdNamespace();
11247 IsStd = true;
11248 AddToKnown = !IsInline;
11249 } else {
11250 // We've seen this namespace for the first time.
11251 AddToKnown = !IsInline;
11252 }
11253 } else {
11254 // Anonymous namespaces.
11255
11256 // Determine whether the parent already has an anonymous namespace.
11257 DeclContext *Parent = CurContext->getRedeclContext();
11258 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11259 PrevNS = TU->getAnonymousNamespace();
11260 } else {
11261 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11262 PrevNS = ND->getAnonymousNamespace();
11263 }
11264
11265 if (PrevNS && IsInline != PrevNS->isInline())
11266 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11267 &IsInline, PrevNS);
11268 }
11269
11270 NamespaceDecl *Namespc = NamespaceDecl::Create(
11271 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested);
11272 if (IsInvalid)
11273 Namespc->setInvalidDecl();
11274
11275 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11276 AddPragmaAttributes(DeclRegionScope, Namespc);
11277
11278 // FIXME: Should we be merging attributes?
11279 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11280 PushNamespaceVisibilityAttr(Attr, Loc);
11281
11282 if (IsStd)
11283 StdNamespace = Namespc;
11284 if (AddToKnown)
11285 KnownNamespaces[Namespc] = false;
11286
11287 if (II) {
11288 PushOnScopeChains(Namespc, DeclRegionScope);
11289 } else {
11290 // Link the anonymous namespace into its parent.
11291 DeclContext *Parent = CurContext->getRedeclContext();
11292 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11293 TU->setAnonymousNamespace(Namespc);
11294 } else {
11295 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11296 }
11297
11298 CurContext->addDecl(Namespc);
11299
11300 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11301 // behaves as if it were replaced by
11302 // namespace unique { /* empty body */ }
11303 // using namespace unique;
11304 // namespace unique { namespace-body }
11305 // where all occurrences of 'unique' in a translation unit are
11306 // replaced by the same identifier and this identifier differs
11307 // from all other identifiers in the entire program.
11308
11309 // We just create the namespace with an empty name and then add an
11310 // implicit using declaration, just like the standard suggests.
11311 //
11312 // CodeGen enforces the "universally unique" aspect by giving all
11313 // declarations semantically contained within an anonymous
11314 // namespace internal linkage.
11315
11316 if (!PrevNS) {
11317 UD = UsingDirectiveDecl::Create(Context, Parent,
11318 /* 'using' */ LBrace,
11319 /* 'namespace' */ SourceLocation(),
11320 /* qualifier */ NestedNameSpecifierLoc(),
11321 /* identifier */ SourceLocation(),
11322 Namespc,
11323 /* Ancestor */ Parent);
11324 UD->setImplicit();
11325 Parent->addDecl(UD);
11326 }
11327 }
11328
11329 ActOnDocumentableDecl(Namespc);
11330
11331 // Although we could have an invalid decl (i.e. the namespace name is a
11332 // redefinition), push it as current DeclContext and try to continue parsing.
11333 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11334 // for the namespace has the declarations that showed up in that particular
11335 // namespace definition.
11336 PushDeclContext(NamespcScope, Namespc);
11337 return Namespc;
11338}
11339
11340/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11341/// is a namespace alias, returns the namespace it points to.
11342static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11343 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11344 return AD->getNamespace();
11345 return dyn_cast_or_null<NamespaceDecl>(D);
11346}
11347
11348/// ActOnFinishNamespaceDef - This callback is called after a namespace is
11349/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11350void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11351 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11352 assert(Namespc && "Invalid parameter, expected NamespaceDecl")(static_cast <bool> (Namespc && "Invalid parameter, expected NamespaceDecl"
) ? void (0) : __assert_fail ("Namespc && \"Invalid parameter, expected NamespaceDecl\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11352, __extension__ __PRETTY_FUNCTION__
))
;
11353 Namespc->setRBraceLoc(RBrace);
11354 PopDeclContext();
11355 if (Namespc->hasAttr<VisibilityAttr>())
11356 PopPragmaVisibility(true, RBrace);
11357 // If this namespace contains an export-declaration, export it now.
11358 if (DeferredExportedNamespaces.erase(Namespc))
11359 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11360}
11361
11362CXXRecordDecl *Sema::getStdBadAlloc() const {
11363 return cast_or_null<CXXRecordDecl>(
11364 StdBadAlloc.get(Context.getExternalSource()));
11365}
11366
11367EnumDecl *Sema::getStdAlignValT() const {
11368 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11369}
11370
11371NamespaceDecl *Sema::getStdNamespace() const {
11372 return cast_or_null<NamespaceDecl>(
11373 StdNamespace.get(Context.getExternalSource()));
11374}
11375
11376NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11377 if (!StdExperimentalNamespaceCache) {
11378 if (auto Std = getStdNamespace()) {
11379 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11380 SourceLocation(), LookupNamespaceName);
11381 if (!LookupQualifiedName(Result, Std) ||
11382 !(StdExperimentalNamespaceCache =
11383 Result.getAsSingle<NamespaceDecl>()))
11384 Result.suppressDiagnostics();
11385 }
11386 }
11387 return StdExperimentalNamespaceCache;
11388}
11389
11390namespace {
11391
11392enum UnsupportedSTLSelect {
11393 USS_InvalidMember,
11394 USS_MissingMember,
11395 USS_NonTrivial,
11396 USS_Other
11397};
11398
11399struct InvalidSTLDiagnoser {
11400 Sema &S;
11401 SourceLocation Loc;
11402 QualType TyForDiags;
11403
11404 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11405 const VarDecl *VD = nullptr) {
11406 {
11407 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11408 << TyForDiags << ((int)Sel);
11409 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11410 assert(!Name.empty())(static_cast <bool> (!Name.empty()) ? void (0) : __assert_fail
("!Name.empty()", "clang/lib/Sema/SemaDeclCXX.cpp", 11410, __extension__
__PRETTY_FUNCTION__))
;
11411 D << Name;
11412 }
11413 }
11414 if (Sel == USS_InvalidMember) {
11415 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11416 << VD << VD->getSourceRange();
11417 }
11418 return QualType();
11419 }
11420};
11421} // namespace
11422
11423QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11424 SourceLocation Loc,
11425 ComparisonCategoryUsage Usage) {
11426 assert(getLangOpts().CPlusPlus &&(static_cast <bool> (getLangOpts().CPlusPlus &&
"Looking for comparison category type outside of C++.") ? void
(0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for comparison category type outside of C++.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11427, __extension__ __PRETTY_FUNCTION__
))
11427 "Looking for comparison category type outside of C++.")(static_cast <bool> (getLangOpts().CPlusPlus &&
"Looking for comparison category type outside of C++.") ? void
(0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for comparison category type outside of C++.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11427, __extension__ __PRETTY_FUNCTION__
))
;
11428
11429 // Use an elaborated type for diagnostics which has a name containing the
11430 // prepended 'std' namespace but not any inline namespace names.
11431 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11432 auto *NNS =
11433 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11434 return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11435 };
11436
11437 // Check if we've already successfully checked the comparison category type
11438 // before. If so, skip checking it again.
11439 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11440 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11441 // The only thing we need to check is that the type has a reachable
11442 // definition in the current context.
11443 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11444 return QualType();
11445
11446 return Info->getType();
11447 }
11448
11449 // If lookup failed
11450 if (!Info) {
11451 std::string NameForDiags = "std::";
11452 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11453 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11454 << NameForDiags << (int)Usage;
11455 return QualType();
11456 }
11457
11458 assert(Info->Kind == Kind)(static_cast <bool> (Info->Kind == Kind) ? void (0) :
__assert_fail ("Info->Kind == Kind", "clang/lib/Sema/SemaDeclCXX.cpp"
, 11458, __extension__ __PRETTY_FUNCTION__))
;
11459 assert(Info->Record)(static_cast <bool> (Info->Record) ? void (0) : __assert_fail
("Info->Record", "clang/lib/Sema/SemaDeclCXX.cpp", 11459,
__extension__ __PRETTY_FUNCTION__))
;
11460
11461 // Update the Record decl in case we encountered a forward declaration on our
11462 // first pass. FIXME: This is a bit of a hack.
11463 if (Info->Record->hasDefinition())
11464 Info->Record = Info->Record->getDefinition();
11465
11466 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11467 return QualType();
11468
11469 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11470
11471 if (!Info->Record->isTriviallyCopyable())
11472 return UnsupportedSTLError(USS_NonTrivial);
11473
11474 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11475 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11476 // Tolerate empty base classes.
11477 if (Base->isEmpty())
11478 continue;
11479 // Reject STL implementations which have at least one non-empty base.
11480 return UnsupportedSTLError();
11481 }
11482
11483 // Check that the STL has implemented the types using a single integer field.
11484 // This expectation allows better codegen for builtin operators. We require:
11485 // (1) The class has exactly one field.
11486 // (2) The field is an integral or enumeration type.
11487 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11488 if (std::distance(FIt, FEnd) != 1 ||
11489 !FIt->getType()->isIntegralOrEnumerationType()) {
11490 return UnsupportedSTLError();
11491 }
11492
11493 // Build each of the require values and store them in Info.
11494 for (ComparisonCategoryResult CCR :
11495 ComparisonCategories::getPossibleResultsForType(Kind)) {
11496 StringRef MemName = ComparisonCategories::getResultString(CCR);
11497 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11498
11499 if (!ValInfo)
11500 return UnsupportedSTLError(USS_MissingMember, MemName);
11501
11502 VarDecl *VD = ValInfo->VD;
11503 assert(VD && "should not be null!")(static_cast <bool> (VD && "should not be null!"
) ? void (0) : __assert_fail ("VD && \"should not be null!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11503, __extension__ __PRETTY_FUNCTION__
))
;
11504
11505 // Attempt to diagnose reasons why the STL definition of this type
11506 // might be foobar, including it failing to be a constant expression.
11507 // TODO Handle more ways the lookup or result can be invalid.
11508 if (!VD->isStaticDataMember() ||
11509 !VD->isUsableInConstantExpressions(Context))
11510 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11511
11512 // Attempt to evaluate the var decl as a constant expression and extract
11513 // the value of its first field as a ICE. If this fails, the STL
11514 // implementation is not supported.
11515 if (!ValInfo->hasValidIntValue())
11516 return UnsupportedSTLError();
11517
11518 MarkVariableReferenced(Loc, VD);
11519 }
11520
11521 // We've successfully built the required types and expressions. Update
11522 // the cache and return the newly cached value.
11523 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11524 return Info->getType();
11525}
11526
11527/// Retrieve the special "std" namespace, which may require us to
11528/// implicitly define the namespace.
11529NamespaceDecl *Sema::getOrCreateStdNamespace() {
11530 if (!StdNamespace) {
11531 // The "std" namespace has not yet been defined, so build one implicitly.
11532 StdNamespace = NamespaceDecl::Create(
11533 Context, Context.getTranslationUnitDecl(),
11534 /*Inline=*/false, SourceLocation(), SourceLocation(),
11535 &PP.getIdentifierTable().get("std"),
11536 /*PrevDecl=*/nullptr, /*Nested=*/false);
11537 getStdNamespace()->setImplicit(true);
11538 }
11539
11540 return getStdNamespace();
11541}
11542
11543bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11544 assert(getLangOpts().CPlusPlus &&(static_cast <bool> (getLangOpts().CPlusPlus &&
"Looking for std::initializer_list outside of C++.") ? void (
0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for std::initializer_list outside of C++.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11545, __extension__ __PRETTY_FUNCTION__
))
11545 "Looking for std::initializer_list outside of C++.")(static_cast <bool> (getLangOpts().CPlusPlus &&
"Looking for std::initializer_list outside of C++.") ? void (
0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for std::initializer_list outside of C++.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11545, __extension__ __PRETTY_FUNCTION__
))
;
11546
11547 // We're looking for implicit instantiations of
11548 // template <typename E> class std::initializer_list.
11549
11550 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11551 return false;
11552
11553 ClassTemplateDecl *Template = nullptr;
11554 const TemplateArgument *Arguments = nullptr;
11555
11556 if (const RecordType *RT = Ty->getAs<RecordType>()) {
11557
11558 ClassTemplateSpecializationDecl *Specialization =
11559 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11560 if (!Specialization)
11561 return false;
11562
11563 Template = Specialization->getSpecializedTemplate();
11564 Arguments = Specialization->getTemplateArgs().data();
11565 } else if (const TemplateSpecializationType *TST =
11566 Ty->getAs<TemplateSpecializationType>()) {
11567 Template = dyn_cast_or_null<ClassTemplateDecl>(
11568 TST->getTemplateName().getAsTemplateDecl());
11569 Arguments = TST->template_arguments().begin();
11570 }
11571 if (!Template)
11572 return false;
11573
11574 if (!StdInitializerList) {
11575 // Haven't recognized std::initializer_list yet, maybe this is it.
11576 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11577 if (TemplateClass->getIdentifier() !=
11578 &PP.getIdentifierTable().get("initializer_list") ||
11579 !getStdNamespace()->InEnclosingNamespaceSetOf(
11580 TemplateClass->getDeclContext()))
11581 return false;
11582 // This is a template called std::initializer_list, but is it the right
11583 // template?
11584 TemplateParameterList *Params = Template->getTemplateParameters();
11585 if (Params->getMinRequiredArguments() != 1)
11586 return false;
11587 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11588 return false;
11589
11590 // It's the right template.
11591 StdInitializerList = Template;
11592 }
11593
11594 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11595 return false;
11596
11597 // This is an instance of std::initializer_list. Find the argument type.
11598 if (Element)
11599 *Element = Arguments[0].getAsType();
11600 return true;
11601}
11602
11603static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11604 NamespaceDecl *Std = S.getStdNamespace();
11605 if (!Std) {
11606 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11607 return nullptr;
11608 }
11609
11610 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11611 Loc, Sema::LookupOrdinaryName);
11612 if (!S.LookupQualifiedName(Result, Std)) {
11613 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11614 return nullptr;
11615 }
11616 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11617 if (!Template) {
11618 Result.suppressDiagnostics();
11619 // We found something weird. Complain about the first thing we found.
11620 NamedDecl *Found = *Result.begin();
11621 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11622 return nullptr;
11623 }
11624
11625 // We found some template called std::initializer_list. Now verify that it's
11626 // correct.
11627 TemplateParameterList *Params = Template->getTemplateParameters();
11628 if (Params->getMinRequiredArguments() != 1 ||
11629 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11630 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11631 return nullptr;
11632 }
11633
11634 return Template;
11635}
11636
11637QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11638 if (!StdInitializerList) {
11639 StdInitializerList = LookupStdInitializerList(*this, Loc);
11640 if (!StdInitializerList)
11641 return QualType();
11642 }
11643
11644 TemplateArgumentListInfo Args(Loc, Loc);
11645 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11646 Context.getTrivialTypeSourceInfo(Element,
11647 Loc)));
11648 return Context.getElaboratedType(
11649 ElaboratedTypeKeyword::ETK_None,
11650 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()),
11651 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11652}
11653
11654bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11655 // C++ [dcl.init.list]p2:
11656 // A constructor is an initializer-list constructor if its first parameter
11657 // is of type std::initializer_list<E> or reference to possibly cv-qualified
11658 // std::initializer_list<E> for some type E, and either there are no other
11659 // parameters or else all other parameters have default arguments.
11660 if (!Ctor->hasOneParamOrDefaultArgs())
11661 return false;
11662
11663 QualType ArgType = Ctor->getParamDecl(0)->getType();
11664 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11665 ArgType = RT->getPointeeType().getUnqualifiedType();
11666
11667 return isStdInitializerList(ArgType, nullptr);
11668}
11669
11670/// Determine whether a using statement is in a context where it will be
11671/// apply in all contexts.
11672static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11673 switch (CurContext->getDeclKind()) {
11674 case Decl::TranslationUnit:
11675 return true;
11676 case Decl::LinkageSpec:
11677 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11678 default:
11679 return false;
11680 }
11681}
11682
11683namespace {
11684
11685// Callback to only accept typo corrections that are namespaces.
11686class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11687public:
11688 bool ValidateCandidate(const TypoCorrection &candidate) override {
11689 if (NamedDecl *ND = candidate.getCorrectionDecl())
11690 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11691 return false;
11692 }
11693
11694 std::unique_ptr<CorrectionCandidateCallback> clone() override {
11695 return std::make_unique<NamespaceValidatorCCC>(*this);
11696 }
11697};
11698
11699}
11700
11701static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11702 CXXScopeSpec &SS,
11703 SourceLocation IdentLoc,
11704 IdentifierInfo *Ident) {
11705 R.clear();
11706 NamespaceValidatorCCC CCC{};
11707 if (TypoCorrection Corrected =
11708 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11709 Sema::CTK_ErrorRecovery)) {
11710 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11711 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11712 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11713 Ident->getName().equals(CorrectedStr);
11714 S.diagnoseTypo(Corrected,
11715 S.PDiag(diag::err_using_directive_member_suggest)
11716 << Ident << DC << DroppedSpecifier << SS.getRange(),
11717 S.PDiag(diag::note_namespace_defined_here));
11718 } else {
11719 S.diagnoseTypo(Corrected,
11720 S.PDiag(diag::err_using_directive_suggest) << Ident,
11721 S.PDiag(diag::note_namespace_defined_here));
11722 }
11723 R.addDecl(Corrected.getFoundDecl());
11724 return true;
11725 }
11726 return false;
11727}
11728
11729Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11730 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11731 SourceLocation IdentLoc,
11732 IdentifierInfo *NamespcName,
11733 const ParsedAttributesView &AttrList) {
11734 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")(static_cast <bool> (!SS.isInvalid() && "Invalid CXXScopeSpec."
) ? void (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11734, __extension__ __PRETTY_FUNCTION__
))
;
11735 assert(NamespcName && "Invalid NamespcName.")(static_cast <bool> (NamespcName && "Invalid NamespcName."
) ? void (0) : __assert_fail ("NamespcName && \"Invalid NamespcName.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11735, __extension__ __PRETTY_FUNCTION__
))
;
11736 assert(IdentLoc.isValid() && "Invalid NamespceName location.")(static_cast <bool> (IdentLoc.isValid() && "Invalid NamespceName location."
) ? void (0) : __assert_fail ("IdentLoc.isValid() && \"Invalid NamespceName location.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11736, __extension__ __PRETTY_FUNCTION__
))
;
11737
11738 // This can only happen along a recovery path.
11739 while (S->isTemplateParamScope())
11740 S = S->getParent();
11741 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")(static_cast <bool> (S->getFlags() & Scope::DeclScope
&& "Invalid Scope.") ? void (0) : __assert_fail ("S->getFlags() & Scope::DeclScope && \"Invalid Scope.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11741, __extension__ __PRETTY_FUNCTION__
))
;
11742
11743 UsingDirectiveDecl *UDir = nullptr;
11744 NestedNameSpecifier *Qualifier = nullptr;
11745 if (SS.isSet())
11746 Qualifier = SS.getScopeRep();
11747
11748 // Lookup namespace name.
11749 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11750 LookupParsedName(R, S, &SS);
11751 if (R.isAmbiguous())
11752 return nullptr;
11753
11754 if (R.empty()) {
11755 R.clear();
11756 // Allow "using namespace std;" or "using namespace ::std;" even if
11757 // "std" hasn't been defined yet, for GCC compatibility.
11758 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11759 NamespcName->isStr("std")) {
11760 Diag(IdentLoc, diag::ext_using_undefined_std);
11761 R.addDecl(getOrCreateStdNamespace());
11762 R.resolveKind();
11763 }
11764 // Otherwise, attempt typo correction.
11765 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11766 }
11767
11768 if (!R.empty()) {
11769 NamedDecl *Named = R.getRepresentativeDecl();
11770 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11771 assert(NS && "expected namespace decl")(static_cast <bool> (NS && "expected namespace decl"
) ? void (0) : __assert_fail ("NS && \"expected namespace decl\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11771, __extension__ __PRETTY_FUNCTION__
))
;
11772
11773 // The use of a nested name specifier may trigger deprecation warnings.
11774 DiagnoseUseOfDecl(Named, IdentLoc);
11775
11776 // C++ [namespace.udir]p1:
11777 // A using-directive specifies that the names in the nominated
11778 // namespace can be used in the scope in which the
11779 // using-directive appears after the using-directive. During
11780 // unqualified name lookup (3.4.1), the names appear as if they
11781 // were declared in the nearest enclosing namespace which
11782 // contains both the using-directive and the nominated
11783 // namespace. [Note: in this context, "contains" means "contains
11784 // directly or indirectly". ]
11785
11786 // Find enclosing context containing both using-directive and
11787 // nominated namespace.
11788 DeclContext *CommonAncestor = NS;
11789 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11790 CommonAncestor = CommonAncestor->getParent();
11791
11792 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11793 SS.getWithLocInContext(Context),
11794 IdentLoc, Named, CommonAncestor);
11795
11796 if (IsUsingDirectiveInToplevelContext(CurContext) &&
11797 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11798 Diag(IdentLoc, diag::warn_using_directive_in_header);
11799 }
11800
11801 PushUsingDirective(S, UDir);
11802 } else {
11803 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11804 }
11805
11806 if (UDir)
11807 ProcessDeclAttributeList(S, UDir, AttrList);
11808
11809 return UDir;
11810}
11811
11812void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11813 // If the scope has an associated entity and the using directive is at
11814 // namespace or translation unit scope, add the UsingDirectiveDecl into
11815 // its lookup structure so qualified name lookup can find it.
11816 DeclContext *Ctx = S->getEntity();
11817 if (Ctx && !Ctx->isFunctionOrMethod())
11818 Ctx->addDecl(UDir);
11819 else
11820 // Otherwise, it is at block scope. The using-directives will affect lookup
11821 // only to the end of the scope.
11822 S->PushUsingDirective(UDir);
11823}
11824
11825Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11826 SourceLocation UsingLoc,
11827 SourceLocation TypenameLoc, CXXScopeSpec &SS,
11828 UnqualifiedId &Name,
11829 SourceLocation EllipsisLoc,
11830 const ParsedAttributesView &AttrList) {
11831 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")(static_cast <bool> (S->getFlags() & Scope::DeclScope
&& "Invalid Scope.") ? void (0) : __assert_fail ("S->getFlags() & Scope::DeclScope && \"Invalid Scope.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11831, __extension__ __PRETTY_FUNCTION__
))
;
11832
11833 if (SS.isEmpty()) {
11834 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11835 return nullptr;
11836 }
11837
11838 switch (Name.getKind()) {
11839 case UnqualifiedIdKind::IK_ImplicitSelfParam:
11840 case UnqualifiedIdKind::IK_Identifier:
11841 case UnqualifiedIdKind::IK_OperatorFunctionId:
11842 case UnqualifiedIdKind::IK_LiteralOperatorId:
11843 case UnqualifiedIdKind::IK_ConversionFunctionId:
11844 break;
11845
11846 case UnqualifiedIdKind::IK_ConstructorName:
11847 case UnqualifiedIdKind::IK_ConstructorTemplateId:
11848 // C++11 inheriting constructors.
11849 Diag(Name.getBeginLoc(),
11850 getLangOpts().CPlusPlus11
11851 ? diag::warn_cxx98_compat_using_decl_constructor
11852 : diag::err_using_decl_constructor)
11853 << SS.getRange();
11854
11855 if (getLangOpts().CPlusPlus11) break;
11856
11857 return nullptr;
11858
11859 case UnqualifiedIdKind::IK_DestructorName:
11860 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11861 return nullptr;
11862
11863 case UnqualifiedIdKind::IK_TemplateId:
11864 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11865 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11866 return nullptr;
11867
11868 case UnqualifiedIdKind::IK_DeductionGuideName:
11869 llvm_unreachable("cannot parse qualified deduction guide name")::llvm::llvm_unreachable_internal("cannot parse qualified deduction guide name"
, "clang/lib/Sema/SemaDeclCXX.cpp", 11869)
;
11870 }
11871
11872 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11873 DeclarationName TargetName = TargetNameInfo.getName();
11874 if (!TargetName)
11875 return nullptr;
11876
11877 // Warn about access declarations.
11878 if (UsingLoc.isInvalid()) {
11879 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11880 ? diag::err_access_decl
11881 : diag::warn_access_decl_deprecated)
11882 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11883 }
11884
11885 if (EllipsisLoc.isInvalid()) {
11886 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11887 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11888 return nullptr;
11889 } else {
11890 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11891 !TargetNameInfo.containsUnexpandedParameterPack()) {
11892 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11893 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11894 EllipsisLoc = SourceLocation();
11895 }
11896 }
11897
11898 NamedDecl *UD =
11899 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11900 SS, TargetNameInfo, EllipsisLoc, AttrList,
11901 /*IsInstantiation*/ false,
11902 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
11903 if (UD)
11904 PushOnScopeChains(UD, S, /*AddToContext*/ false);
11905
11906 return UD;
11907}
11908
11909Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
11910 SourceLocation UsingLoc,
11911 SourceLocation EnumLoc,
11912 SourceLocation IdentLoc,
11913 IdentifierInfo &II, CXXScopeSpec *SS) {
11914 assert(!SS->isInvalid() && "ScopeSpec is invalid")(static_cast <bool> (!SS->isInvalid() && "ScopeSpec is invalid"
) ? void (0) : __assert_fail ("!SS->isInvalid() && \"ScopeSpec is invalid\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11914, __extension__ __PRETTY_FUNCTION__
))
;
11915 TypeSourceInfo *TSI = nullptr;
11916 QualType EnumTy = GetTypeFromParser(
11917 getTypeName(II, IdentLoc, S, SS, /*isClassName=*/false,
11918 /*HasTrailingDot=*/false,
11919 /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false,
11920 /*WantNontrivialTypeSourceInfo=*/true),
11921 &TSI);
11922 if (EnumTy.isNull()) {
11923 Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS)
11924 ? diag::err_using_enum_is_dependent
11925 : diag::err_unknown_typename)
11926 << II.getName()
11927 << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, IdentLoc);
11928 return nullptr;
11929 }
11930
11931 auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl());
11932 if (!Enum) {
11933 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy;
11934 return nullptr;
11935 }
11936
11937 if (auto *Def = Enum->getDefinition())
11938 Enum = Def;
11939
11940 if (TSI == nullptr)
11941 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc);
11942
11943 auto *UD =
11944 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum);
11945
11946 if (UD)
11947 PushOnScopeChains(UD, S, /*AddToContext*/ false);
11948
11949 return UD;
11950}
11951
11952/// Determine whether a using declaration considers the given
11953/// declarations as "equivalent", e.g., if they are redeclarations of
11954/// the same entity or are both typedefs of the same type.
11955static bool
11956IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11957 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11958 return true;
11959
11960 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11961 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11962 return Context.hasSameType(TD1->getUnderlyingType(),
11963 TD2->getUnderlyingType());
11964
11965 // Two using_if_exists using-declarations are equivalent if both are
11966 // unresolved.
11967 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11968 isa<UnresolvedUsingIfExistsDecl>(D2))
11969 return true;
11970
11971 return false;
11972}
11973
11974
11975/// Determines whether to create a using shadow decl for a particular
11976/// decl, given the set of decls existing prior to this using lookup.
11977bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
11978 const LookupResult &Previous,
11979 UsingShadowDecl *&PrevShadow) {
11980 // Diagnose finding a decl which is not from a base class of the
11981 // current class. We do this now because there are cases where this
11982 // function will silently decide not to build a shadow decl, which
11983 // will pre-empt further diagnostics.
11984 //
11985 // We don't need to do this in C++11 because we do the check once on
11986 // the qualifier.
11987 //
11988 // FIXME: diagnose the following if we care enough:
11989 // struct A { int foo; };
11990 // struct B : A { using A::foo; };
11991 // template <class T> struct C : A {};
11992 // template <class T> struct D : C<T> { using B::foo; } // <---
11993 // This is invalid (during instantiation) in C++03 because B::foo
11994 // resolves to the using decl in B, which is not a base class of D<T>.
11995 // We can't diagnose it immediately because C<T> is an unknown
11996 // specialization. The UsingShadowDecl in D<T> then points directly
11997 // to A::foo, which will look well-formed when we instantiate.
11998 // The right solution is to not collapse the shadow-decl chain.
11999 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12000 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
12001 DeclContext *OrigDC = Orig->getDeclContext();
12002
12003 // Handle enums and anonymous structs.
12004 if (isa<EnumDecl>(OrigDC))
12005 OrigDC = OrigDC->getParent();
12006 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
12007 while (OrigRec->isAnonymousStructOrUnion())
12008 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
12009
12010 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
12011 if (OrigDC == CurContext) {
12012 Diag(Using->getLocation(),
12013 diag::err_using_decl_nested_name_specifier_is_current_class)
12014 << Using->getQualifierLoc().getSourceRange();
12015 Diag(Orig->getLocation(), diag::note_using_decl_target);
12016 Using->setInvalidDecl();
12017 return true;
12018 }
12019
12020 Diag(Using->getQualifierLoc().getBeginLoc(),
12021 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12022 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
12023 << Using->getQualifierLoc().getSourceRange();
12024 Diag(Orig->getLocation(), diag::note_using_decl_target);
12025 Using->setInvalidDecl();
12026 return true;
12027 }
12028 }
12029
12030 if (Previous.empty()) return false;
12031
12032 NamedDecl *Target = Orig;
12033 if (isa<UsingShadowDecl>(Target))
12034 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12035
12036 // If the target happens to be one of the previous declarations, we
12037 // don't have a conflict.
12038 //
12039 // FIXME: but we might be increasing its access, in which case we
12040 // should redeclare it.
12041 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12042 bool FoundEquivalentDecl = false;
12043 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
12044 I != E; ++I) {
12045 NamedDecl *D = (*I)->getUnderlyingDecl();
12046 // We can have UsingDecls in our Previous results because we use the same
12047 // LookupResult for checking whether the UsingDecl itself is a valid
12048 // redeclaration.
12049 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
12050 continue;
12051
12052 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
12053 // C++ [class.mem]p19:
12054 // If T is the name of a class, then [every named member other than
12055 // a non-static data member] shall have a name different from T
12056 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
12057 !isa<IndirectFieldDecl>(Target) &&
12058 !isa<UnresolvedUsingValueDecl>(Target) &&
12059 DiagnoseClassNameShadow(
12060 CurContext,
12061 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12062 return true;
12063 }
12064
12065 if (IsEquivalentForUsingDecl(Context, D, Target)) {
12066 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
12067 PrevShadow = Shadow;
12068 FoundEquivalentDecl = true;
12069 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
12070 // We don't conflict with an existing using shadow decl of an equivalent
12071 // declaration, but we're not a redeclaration of it.
12072 FoundEquivalentDecl = true;
12073 }
12074
12075 if (isVisible(D))
12076 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12077 }
12078
12079 if (FoundEquivalentDecl)
12080 return false;
12081
12082 // Always emit a diagnostic for a mismatch between an unresolved
12083 // using_if_exists and a resolved using declaration in either direction.
12084 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12085 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12086 if (!NonTag && !Tag)
12087 return false;
12088 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12089 Diag(Target->getLocation(), diag::note_using_decl_target);
12090 Diag((NonTag ? NonTag : Tag)->getLocation(),
12091 diag::note_using_decl_conflict);
12092 BUD->setInvalidDecl();
12093 return true;
12094 }
12095
12096 if (FunctionDecl *FD = Target->getAsFunction()) {
12097 NamedDecl *OldDecl = nullptr;
12098 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12099 /*IsForUsingDecl*/ true)) {
12100 case Ovl_Overload:
12101 return false;
12102
12103 case Ovl_NonFunction:
12104 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12105 break;
12106
12107 // We found a decl with the exact signature.
12108 case Ovl_Match:
12109 // If we're in a record, we want to hide the target, so we
12110 // return true (without a diagnostic) to tell the caller not to
12111 // build a shadow decl.
12112 if (CurContext->isRecord())
12113 return true;
12114
12115 // If we're not in a record, this is an error.
12116 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12117 break;
12118 }
12119
12120 Diag(Target->getLocation(), diag::note_using_decl_target);
12121 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12122 BUD->setInvalidDecl();
12123 return true;
12124 }
12125
12126 // Target is not a function.
12127
12128 if (isa<TagDecl>(Target)) {
12129 // No conflict between a tag and a non-tag.
12130 if (!Tag) return false;
12131
12132 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12133 Diag(Target->getLocation(), diag::note_using_decl_target);
12134 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12135 BUD->setInvalidDecl();
12136 return true;
12137 }
12138
12139 // No conflict between a tag and a non-tag.
12140 if (!NonTag) return false;
12141
12142 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12143 Diag(Target->getLocation(), diag::note_using_decl_target);
12144 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12145 BUD->setInvalidDecl();
12146 return true;
12147}
12148
12149/// Determine whether a direct base class is a virtual base class.
12150static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12151 if (!Derived->getNumVBases())
12152 return false;
12153 for (auto &B : Derived->bases())
12154 if (B.getType()->getAsCXXRecordDecl() == Base)
12155 return B.isVirtual();
12156 llvm_unreachable("not a direct base class")::llvm::llvm_unreachable_internal("not a direct base class", "clang/lib/Sema/SemaDeclCXX.cpp"
, 12156)
;
12157}
12158
12159/// Builds a shadow declaration corresponding to a 'using' declaration.
12160UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12161 NamedDecl *Orig,
12162 UsingShadowDecl *PrevDecl) {
12163 // If we resolved to another shadow declaration, just coalesce them.
12164 NamedDecl *Target = Orig;
12165 if (isa<UsingShadowDecl>(Target)) {
12166 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12167 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration")(static_cast <bool> (!isa<UsingShadowDecl>(Target
) && "nested shadow declaration") ? void (0) : __assert_fail
("!isa<UsingShadowDecl>(Target) && \"nested shadow declaration\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12167, __extension__ __PRETTY_FUNCTION__
))
;
12168 }
12169
12170 NamedDecl *NonTemplateTarget = Target;
12171 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12172 NonTemplateTarget = TargetTD->getTemplatedDecl();
12173
12174 UsingShadowDecl *Shadow;
12175 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12176 UsingDecl *Using = cast<UsingDecl>(BUD);
12177 bool IsVirtualBase =
12178 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12179 Using->getQualifier()->getAsRecordDecl());
12180 Shadow = ConstructorUsingShadowDecl::Create(
12181 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12182 } else {
12183 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12184 Target->getDeclName(), BUD, Target);
12185 }
12186 BUD->addShadowDecl(Shadow);
12187
12188 Shadow->setAccess(BUD->getAccess());
12189 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12190 Shadow->setInvalidDecl();
12191
12192 Shadow->setPreviousDecl(PrevDecl);
12193
12194 if (S)
12195 PushOnScopeChains(Shadow, S);
12196 else
12197 CurContext->addDecl(Shadow);
12198
12199
12200 return Shadow;
12201}
12202
12203/// Hides a using shadow declaration. This is required by the current
12204/// using-decl implementation when a resolvable using declaration in a
12205/// class is followed by a declaration which would hide or override
12206/// one or more of the using decl's targets; for example:
12207///
12208/// struct Base { void foo(int); };
12209/// struct Derived : Base {
12210/// using Base::foo;
12211/// void foo(int);
12212/// };
12213///
12214/// The governing language is C++03 [namespace.udecl]p12:
12215///
12216/// When a using-declaration brings names from a base class into a
12217/// derived class scope, member functions in the derived class
12218/// override and/or hide member functions with the same name and
12219/// parameter types in a base class (rather than conflicting).
12220///
12221/// There are two ways to implement this:
12222/// (1) optimistically create shadow decls when they're not hidden
12223/// by existing declarations, or
12224/// (2) don't create any shadow decls (or at least don't make them
12225/// visible) until we've fully parsed/instantiated the class.
12226/// The problem with (1) is that we might have to retroactively remove
12227/// a shadow decl, which requires several O(n) operations because the
12228/// decl structures are (very reasonably) not designed for removal.
12229/// (2) avoids this but is very fiddly and phase-dependent.
12230void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12231 if (Shadow->getDeclName().getNameKind() ==
12232 DeclarationName::CXXConversionFunctionName)
12233 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12234
12235 // Remove it from the DeclContext...
12236 Shadow->getDeclContext()->removeDecl(Shadow);
12237
12238 // ...and the scope, if applicable...
12239 if (S) {
12240 S->RemoveDecl(Shadow);
12241 IdResolver.RemoveDecl(Shadow);
12242 }
12243
12244 // ...and the using decl.
12245 Shadow->getIntroducer()->removeShadowDecl(Shadow);
12246
12247 // TODO: complain somehow if Shadow was used. It shouldn't
12248 // be possible for this to happen, because...?
12249}
12250
12251/// Find the base specifier for a base class with the given type.
12252static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12253 QualType DesiredBase,
12254 bool &AnyDependentBases) {
12255 // Check whether the named type is a direct base class.
12256 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12257 .getUnqualifiedType();
12258 for (auto &Base : Derived->bases()) {
12259 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12260 if (CanonicalDesiredBase == BaseType)
12261 return &Base;
12262 if (BaseType->isDependentType())
12263 AnyDependentBases = true;
12264 }
12265 return nullptr;
12266}
12267
12268namespace {
12269class UsingValidatorCCC final : public CorrectionCandidateCallback {
12270public:
12271 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12272 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12273 : HasTypenameKeyword(HasTypenameKeyword),
12274 IsInstantiation(IsInstantiation), OldNNS(NNS),
12275 RequireMemberOf(RequireMemberOf) {}
12276
12277 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12278 NamedDecl *ND = Candidate.getCorrectionDecl();
12279
12280 // Keywords are not valid here.
12281 if (!ND || isa<NamespaceDecl>(ND))
12282 return false;
12283
12284 // Completely unqualified names are invalid for a 'using' declaration.
12285 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12286 return false;
12287
12288 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12289 // reject.
12290
12291 if (RequireMemberOf) {
12292 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12293 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12294 // No-one ever wants a using-declaration to name an injected-class-name
12295 // of a base class, unless they're declaring an inheriting constructor.
12296 ASTContext &Ctx = ND->getASTContext();
12297 if (!Ctx.getLangOpts().CPlusPlus11)
12298 return false;
12299 QualType FoundType = Ctx.getRecordType(FoundRecord);
12300
12301 // Check that the injected-class-name is named as a member of its own
12302 // type; we don't want to suggest 'using Derived::Base;', since that
12303 // means something else.
12304 NestedNameSpecifier *Specifier =
12305 Candidate.WillReplaceSpecifier()
12306 ? Candidate.getCorrectionSpecifier()
12307 : OldNNS;
12308 if (!Specifier->getAsType() ||
12309 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12310 return false;
12311
12312 // Check that this inheriting constructor declaration actually names a
12313 // direct base class of the current class.
12314 bool AnyDependentBases = false;
12315 if (!findDirectBaseWithType(RequireMemberOf,
12316 Ctx.getRecordType(FoundRecord),
12317 AnyDependentBases) &&
12318 !AnyDependentBases)
12319 return false;
12320 } else {
12321 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12322 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12323 return false;
12324
12325 // FIXME: Check that the base class member is accessible?
12326 }
12327 } else {
12328 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12329 if (FoundRecord && FoundRecord->isInjectedClassName())
12330 return false;
12331 }
12332
12333 if (isa<TypeDecl>(ND))
12334 return HasTypenameKeyword || !IsInstantiation;
12335
12336 return !HasTypenameKeyword;
12337 }
12338
12339 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12340 return std::make_unique<UsingValidatorCCC>(*this);
12341 }
12342
12343private:
12344 bool HasTypenameKeyword;
12345 bool IsInstantiation;
12346 NestedNameSpecifier *OldNNS;
12347 CXXRecordDecl *RequireMemberOf;
12348};
12349} // end anonymous namespace
12350
12351/// Remove decls we can't actually see from a lookup being used to declare
12352/// shadow using decls.
12353///
12354/// \param S - The scope of the potential shadow decl
12355/// \param Previous - The lookup of a potential shadow decl's name.
12356void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12357 // It is really dumb that we have to do this.
12358 LookupResult::Filter F = Previous.makeFilter();
12359 while (F.hasNext()) {
12360 NamedDecl *D = F.next();
12361 if (!isDeclInScope(D, CurContext, S))
12362 F.erase();
12363 // If we found a local extern declaration that's not ordinarily visible,
12364 // and this declaration is being added to a non-block scope, ignore it.
12365 // We're only checking for scope conflicts here, not also for violations
12366 // of the linkage rules.
12367 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12368 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12369 F.erase();
12370 }
12371 F.done();
12372}
12373
12374/// Builds a using declaration.
12375///
12376/// \param IsInstantiation - Whether this call arises from an
12377/// instantiation of an unresolved using declaration. We treat
12378/// the lookup differently for these declarations.
12379NamedDecl *Sema::BuildUsingDeclaration(
12380 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12381 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12382 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12383 const ParsedAttributesView &AttrList, bool IsInstantiation,
12384 bool IsUsingIfExists) {
12385 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")(static_cast <bool> (!SS.isInvalid() && "Invalid CXXScopeSpec."
) ? void (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12385, __extension__ __PRETTY_FUNCTION__
))
;
12386 SourceLocation IdentLoc = NameInfo.getLoc();
12387 assert(IdentLoc.isValid() && "Invalid TargetName location.")(static_cast <bool> (IdentLoc.isValid() && "Invalid TargetName location."
) ? void (0) : __assert_fail ("IdentLoc.isValid() && \"Invalid TargetName location.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12387, __extension__ __PRETTY_FUNCTION__
))
;
12388
12389 // FIXME: We ignore attributes for now.
12390
12391 // For an inheriting constructor declaration, the name of the using
12392 // declaration is the name of a constructor in this class, not in the
12393 // base class.
12394 DeclarationNameInfo UsingName = NameInfo;
12395 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12396 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12397 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12398 Context.getCanonicalType(Context.getRecordType(RD))));
12399
12400 // Do the redeclaration lookup in the current scope.
12401 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12402 ForVisibleRedeclaration);
12403 Previous.setHideTags(false);
12404 if (S) {
12405 LookupName(Previous, S);
12406
12407 FilterUsingLookup(S, Previous);
12408 } else {
12409 assert(IsInstantiation && "no scope in non-instantiation")(static_cast <bool> (IsInstantiation && "no scope in non-instantiation"
) ? void (0) : __assert_fail ("IsInstantiation && \"no scope in non-instantiation\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12409, __extension__ __PRETTY_FUNCTION__
))
;
12410 if (CurContext->isRecord())
12411 LookupQualifiedName(Previous, CurContext);
12412 else {
12413 // No redeclaration check is needed here; in non-member contexts we
12414 // diagnosed all possible conflicts with other using-declarations when
12415 // building the template:
12416 //
12417 // For a dependent non-type using declaration, the only valid case is
12418 // if we instantiate to a single enumerator. We check for conflicts
12419 // between shadow declarations we introduce, and we check in the template
12420 // definition for conflicts between a non-type using declaration and any
12421 // other declaration, which together covers all cases.
12422 //
12423 // A dependent typename using declaration will never successfully
12424 // instantiate, since it will always name a class member, so we reject
12425 // that in the template definition.
12426 }
12427 }
12428
12429 // Check for invalid redeclarations.
12430 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12431 SS, IdentLoc, Previous))
12432 return nullptr;
12433
12434 // 'using_if_exists' doesn't make sense on an inherited constructor.
12435 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12436 DeclarationName::CXXConstructorName) {
12437 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12438 return nullptr;
12439 }
12440
12441 DeclContext *LookupContext = computeDeclContext(SS);
12442 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12443 if (!LookupContext || EllipsisLoc.isValid()) {
12444 NamedDecl *D;
12445 // Dependent scope, or an unexpanded pack
12446 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12447 SS, NameInfo, IdentLoc))
12448 return nullptr;
12449
12450 if (HasTypenameKeyword) {
12451 // FIXME: not all declaration name kinds are legal here
12452 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12453 UsingLoc, TypenameLoc,
12454 QualifierLoc,
12455 IdentLoc, NameInfo.getName(),
12456 EllipsisLoc);
12457 } else {
12458 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12459 QualifierLoc, NameInfo, EllipsisLoc);
12460 }
12461 D->setAccess(AS);
12462 CurContext->addDecl(D);
12463 ProcessDeclAttributeList(S, D, AttrList);
12464 return D;
12465 }
12466
12467 auto Build = [&](bool Invalid) {
12468 UsingDecl *UD =
12469 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12470 UsingName, HasTypenameKeyword);
12471 UD->setAccess(AS);
12472 CurContext->addDecl(UD);
12473 ProcessDeclAttributeList(S, UD, AttrList);
12474 UD->setInvalidDecl(Invalid);
12475 return UD;
12476 };
12477 auto BuildInvalid = [&]{ return Build(true); };
12478 auto BuildValid = [&]{ return Build(false); };
12479
12480 if (RequireCompleteDeclContext(SS, LookupContext))
12481 return BuildInvalid();
12482
12483 // Look up the target name.
12484 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12485
12486 // Unlike most lookups, we don't always want to hide tag
12487 // declarations: tag names are visible through the using declaration
12488 // even if hidden by ordinary names, *except* in a dependent context
12489 // where they may be used by two-phase lookup.
12490 if (!IsInstantiation)
12491 R.setHideTags(false);
12492
12493 // For the purposes of this lookup, we have a base object type
12494 // equal to that of the current context.
12495 if (CurContext->isRecord()) {
12496 R.setBaseObjectType(
12497 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12498 }
12499
12500 LookupQualifiedName(R, LookupContext);
12501
12502 // Validate the context, now we have a lookup
12503 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12504 IdentLoc, &R))
12505 return nullptr;
12506
12507 if (R.empty() && IsUsingIfExists)
12508 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12509 UsingName.getName()),
12510 AS_public);
12511
12512 // Try to correct typos if possible. If constructor name lookup finds no
12513 // results, that means the named class has no explicit constructors, and we
12514 // suppressed declaring implicit ones (probably because it's dependent or
12515 // invalid).
12516 if (R.empty() &&
12517 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12518 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12519 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12520 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12521 auto *II = NameInfo.getName().getAsIdentifierInfo();
12522 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12523 CurContext->isStdNamespace() &&
12524 isa<TranslationUnitDecl>(LookupContext) &&
12525 getSourceManager().isInSystemHeader(UsingLoc))
12526 return nullptr;
12527 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12528 dyn_cast<CXXRecordDecl>(CurContext));
12529 if (TypoCorrection Corrected =
12530 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12531 CTK_ErrorRecovery)) {
12532 // We reject candidates where DroppedSpecifier == true, hence the
12533 // literal '0' below.
12534 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12535 << NameInfo.getName() << LookupContext << 0
12536 << SS.getRange());
12537
12538 // If we picked a correction with no attached Decl we can't do anything
12539 // useful with it, bail out.
12540 NamedDecl *ND = Corrected.getCorrectionDecl();
12541 if (!ND)
12542 return BuildInvalid();
12543
12544 // If we corrected to an inheriting constructor, handle it as one.
12545 auto *RD = dyn_cast<CXXRecordDecl>(ND);
12546 if (RD && RD->isInjectedClassName()) {
12547 // The parent of the injected class name is the class itself.
12548 RD = cast<CXXRecordDecl>(RD->getParent());
12549
12550 // Fix up the information we'll use to build the using declaration.
12551 if (Corrected.WillReplaceSpecifier()) {
12552 NestedNameSpecifierLocBuilder Builder;
12553 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12554 QualifierLoc.getSourceRange());
12555 QualifierLoc = Builder.getWithLocInContext(Context);
12556 }
12557
12558 // In this case, the name we introduce is the name of a derived class
12559 // constructor.
12560 auto *CurClass = cast<CXXRecordDecl>(CurContext);
12561 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12562 Context.getCanonicalType(Context.getRecordType(CurClass))));
12563 UsingName.setNamedTypeInfo(nullptr);
12564 for (auto *Ctor : LookupConstructors(RD))
12565 R.addDecl(Ctor);
12566 R.resolveKind();
12567 } else {
12568 // FIXME: Pick up all the declarations if we found an overloaded
12569 // function.
12570 UsingName.setName(ND->getDeclName());
12571 R.addDecl(ND);
12572 }
12573 } else {
12574 Diag(IdentLoc, diag::err_no_member)
12575 << NameInfo.getName() << LookupContext << SS.getRange();
12576 return BuildInvalid();
12577 }
12578 }
12579
12580 if (R.isAmbiguous())
12581 return BuildInvalid();
12582
12583 if (HasTypenameKeyword) {
12584 // If we asked for a typename and got a non-type decl, error out.
12585 if (!R.getAsSingle<TypeDecl>() &&
12586 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12587 Diag(IdentLoc, diag::err_using_typename_non_type);
12588 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12589 Diag((*I)->getUnderlyingDecl()->getLocation(),
12590 diag::note_using_decl_target);
12591 return BuildInvalid();
12592 }
12593 } else {
12594 // If we asked for a non-typename and we got a type, error out,
12595 // but only if this is an instantiation of an unresolved using
12596 // decl. Otherwise just silently find the type name.
12597 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12598 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12599 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12600 return BuildInvalid();
12601 }
12602 }
12603
12604 // C++14 [namespace.udecl]p6:
12605 // A using-declaration shall not name a namespace.
12606 if (R.getAsSingle<NamespaceDecl>()) {
12607 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12608 << SS.getRange();
12609 return BuildInvalid();
12610 }
12611
12612 UsingDecl *UD = BuildValid();
12613
12614 // Some additional rules apply to inheriting constructors.
12615 if (UsingName.getName().getNameKind() ==
12616 DeclarationName::CXXConstructorName) {
12617 // Suppress access diagnostics; the access check is instead performed at the
12618 // point of use for an inheriting constructor.
12619 R.suppressDiagnostics();
12620 if (CheckInheritingConstructorUsingDecl(UD))
12621 return UD;
12622 }
12623
12624 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12625 UsingShadowDecl *PrevDecl = nullptr;
12626 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12627 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12628 }
12629
12630 return UD;
12631}
12632
12633NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12634 SourceLocation UsingLoc,
12635 SourceLocation EnumLoc,
12636 SourceLocation NameLoc,
12637 TypeSourceInfo *EnumType,
12638 EnumDecl *ED) {
12639 bool Invalid = false;
12640
12641 if (CurContext->getRedeclContext()->isRecord()) {
12642 /// In class scope, check if this is a duplicate, for better a diagnostic.
12643 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12644 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12645 ForVisibleRedeclaration);
12646
12647 LookupName(Previous, S);
12648
12649 for (NamedDecl *D : Previous)
12650 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12651 if (UED->getEnumDecl() == ED) {
12652 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12653 << SourceRange(EnumLoc, NameLoc);
12654 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12655 Invalid = true;
12656 break;
12657 }
12658 }
12659
12660 if (RequireCompleteEnumDecl(ED, NameLoc))
12661 Invalid = true;
12662
12663 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12664 EnumLoc, NameLoc, EnumType);
12665 UD->setAccess(AS);
12666 CurContext->addDecl(UD);
12667
12668 if (Invalid) {
12669 UD->setInvalidDecl();
12670 return UD;
12671 }
12672
12673 // Create the shadow decls for each enumerator
12674 for (EnumConstantDecl *EC : ED->enumerators()) {
12675 UsingShadowDecl *PrevDecl = nullptr;
12676 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12677 LookupResult Previous(*this, DNI, LookupOrdinaryName,
12678 ForVisibleRedeclaration);
12679 LookupName(Previous, S);
12680 FilterUsingLookup(S, Previous);
12681
12682 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12683 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12684 }
12685
12686 return UD;
12687}
12688
12689NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12690 ArrayRef<NamedDecl *> Expansions) {
12691 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||(static_cast <bool> (isa<UnresolvedUsingValueDecl>
(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(
InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom
)) ? void (0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "clang/lib/Sema/SemaDeclCXX.cpp", 12693, __extension__ __PRETTY_FUNCTION__
))
12692 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||(static_cast <bool> (isa<UnresolvedUsingValueDecl>
(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(
InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom
)) ? void (0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "clang/lib/Sema/SemaDeclCXX.cpp", 12693, __extension__ __PRETTY_FUNCTION__
))
12693 isa<UsingPackDecl>(InstantiatedFrom))(static_cast <bool> (isa<UnresolvedUsingValueDecl>
(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(
InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom
)) ? void (0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)"
, "clang/lib/Sema/SemaDeclCXX.cpp", 12693, __extension__ __PRETTY_FUNCTION__
))
;
12694
12695 auto *UPD =
12696 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12697 UPD->setAccess(InstantiatedFrom->getAccess());
12698 CurContext->addDecl(UPD);
12699 return UPD;
12700}
12701
12702/// Additional checks for a using declaration referring to a constructor name.
12703bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12704 assert(!UD->hasTypename() && "expecting a constructor name")(static_cast <bool> (!UD->hasTypename() && "expecting a constructor name"
) ? void (0) : __assert_fail ("!UD->hasTypename() && \"expecting a constructor name\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12704, __extension__ __PRETTY_FUNCTION__
))
;
12705
12706 const Type *SourceType = UD->getQualifier()->getAsType();
12707 assert(SourceType &&(static_cast <bool> (SourceType && "Using decl naming constructor doesn't have type in scope spec."
) ? void (0) : __assert_fail ("SourceType && \"Using decl naming constructor doesn't have type in scope spec.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12708, __extension__ __PRETTY_FUNCTION__
))
12708 "Using decl naming constructor doesn't have type in scope spec.")(static_cast <bool> (SourceType && "Using decl naming constructor doesn't have type in scope spec."
) ? void (0) : __assert_fail ("SourceType && \"Using decl naming constructor doesn't have type in scope spec.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12708, __extension__ __PRETTY_FUNCTION__
))
;
12709 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12710
12711 // Check whether the named type is a direct base class.
12712 bool AnyDependentBases = false;
12713 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12714 AnyDependentBases);
12715 if (!Base && !AnyDependentBases) {
12716 Diag(UD->getUsingLoc(),
12717 diag::err_using_decl_constructor_not_in_direct_base)
12718 << UD->getNameInfo().getSourceRange()
12719 << QualType(SourceType, 0) << TargetClass;
12720 UD->setInvalidDecl();
12721 return true;
12722 }
12723
12724 if (Base)
12725 Base->setInheritConstructors();
12726
12727 return false;
12728}
12729
12730/// Checks that the given using declaration is not an invalid
12731/// redeclaration. Note that this is checking only for the using decl
12732/// itself, not for any ill-formedness among the UsingShadowDecls.
12733bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12734 bool HasTypenameKeyword,
12735 const CXXScopeSpec &SS,
12736 SourceLocation NameLoc,
12737 const LookupResult &Prev) {
12738 NestedNameSpecifier *Qual = SS.getScopeRep();
12739
12740 // C++03 [namespace.udecl]p8:
12741 // C++0x [namespace.udecl]p10:
12742 // A using-declaration is a declaration and can therefore be used
12743 // repeatedly where (and only where) multiple declarations are
12744 // allowed.
12745 //
12746 // That's in non-member contexts.
12747 if (!CurContext->getRedeclContext()->isRecord()) {
12748 // A dependent qualifier outside a class can only ever resolve to an
12749 // enumeration type. Therefore it conflicts with any other non-type
12750 // declaration in the same scope.
12751 // FIXME: How should we check for dependent type-type conflicts at block
12752 // scope?
12753 if (Qual->isDependent() && !HasTypenameKeyword) {
12754 for (auto *D : Prev) {
12755 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12756 bool OldCouldBeEnumerator =
12757 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12758 Diag(NameLoc,
12759 OldCouldBeEnumerator ? diag::err_redefinition
12760 : diag::err_redefinition_different_kind)
12761 << Prev.getLookupName();
12762 Diag(D->getLocation(), diag::note_previous_definition);
12763 return true;
12764 }
12765 }
12766 }
12767 return false;
12768 }
12769
12770 const NestedNameSpecifier *CNNS =
12771 Context.getCanonicalNestedNameSpecifier(Qual);
12772 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12773 NamedDecl *D = *I;
12774
12775 bool DTypename;
12776 NestedNameSpecifier *DQual;
12777 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12778 DTypename = UD->hasTypename();
12779 DQual = UD->getQualifier();
12780 } else if (UnresolvedUsingValueDecl *UD
12781 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12782 DTypename = false;
12783 DQual = UD->getQualifier();
12784 } else if (UnresolvedUsingTypenameDecl *UD
12785 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12786 DTypename = true;
12787 DQual = UD->getQualifier();
12788 } else continue;
12789
12790 // using decls differ if one says 'typename' and the other doesn't.
12791 // FIXME: non-dependent using decls?
12792 if (HasTypenameKeyword != DTypename) continue;
12793
12794 // using decls differ if they name different scopes (but note that
12795 // template instantiation can cause this check to trigger when it
12796 // didn't before instantiation).
12797 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
12798 continue;
12799
12800 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12801 Diag(D->getLocation(), diag::note_using_decl) << 1;
12802 return true;
12803 }
12804
12805 return false;
12806}
12807
12808/// Checks that the given nested-name qualifier used in a using decl
12809/// in the current context is appropriately related to the current
12810/// scope. If an error is found, diagnoses it and returns true.
12811/// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12812/// result of that lookup. UD is likewise nullptr, except when we have an
12813/// already-populated UsingDecl whose shadow decls contain the same information
12814/// (i.e. we're instantiating a UsingDecl with non-dependent scope).
12815bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
12816 const CXXScopeSpec &SS,
12817 const DeclarationNameInfo &NameInfo,
12818 SourceLocation NameLoc,
12819 const LookupResult *R, const UsingDecl *UD) {
12820 DeclContext *NamedContext = computeDeclContext(SS);
12821 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&(static_cast <bool> (bool(NamedContext) == (R || UD) &&
!(R && UD) && "resolvable context must have exactly one set of decls"
) ? void (0) : __assert_fail ("bool(NamedContext) == (R || UD) && !(R && UD) && \"resolvable context must have exactly one set of decls\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12822, __extension__ __PRETTY_FUNCTION__
))
12822 "resolvable context must have exactly one set of decls")(static_cast <bool> (bool(NamedContext) == (R || UD) &&
!(R && UD) && "resolvable context must have exactly one set of decls"
) ? void (0) : __assert_fail ("bool(NamedContext) == (R || UD) && !(R && UD) && \"resolvable context must have exactly one set of decls\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 12822, __extension__ __PRETTY_FUNCTION__
))
;
12823
12824 // C++ 20 permits using an enumerator that does not have a class-hierarchy
12825 // relationship.
12826 bool Cxx20Enumerator = false;
12827 if (NamedContext) {
12828 EnumConstantDecl *EC = nullptr;
12829 if (R)
12830 EC = R->getAsSingle<EnumConstantDecl>();
12831 else if (UD && UD->shadow_size() == 1)
12832 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
12833 if (EC)
12834 Cxx20Enumerator = getLangOpts().CPlusPlus20;
12835
12836 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12837 // C++14 [namespace.udecl]p7:
12838 // A using-declaration shall not name a scoped enumerator.
12839 // C++20 p1099 permits enumerators.
12840 if (EC && R && ED->isScoped())
12841 Diag(SS.getBeginLoc(),
12842 getLangOpts().CPlusPlus20
12843 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12844 : diag::ext_using_decl_scoped_enumerator)
12845 << SS.getRange();
12846
12847 // We want to consider the scope of the enumerator
12848 NamedContext = ED->getDeclContext();
12849 }
12850 }
12851
12852 if (!CurContext->isRecord()) {
12853 // C++03 [namespace.udecl]p3:
12854 // C++0x [namespace.udecl]p8:
12855 // A using-declaration for a class member shall be a member-declaration.
12856 // C++20 [namespace.udecl]p7
12857 // ... other than an enumerator ...
12858
12859 // If we weren't able to compute a valid scope, it might validly be a
12860 // dependent class or enumeration scope. If we have a 'typename' keyword,
12861 // the scope must resolve to a class type.
12862 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
12863 : !HasTypename)
12864 return false; // OK
12865
12866 Diag(NameLoc,
12867 Cxx20Enumerator
12868 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12869 : diag::err_using_decl_can_not_refer_to_class_member)
12870 << SS.getRange();
12871
12872 if (Cxx20Enumerator)
12873 return false; // OK
12874
12875 auto *RD = NamedContext
12876 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12877 : nullptr;
12878 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
12879 // See if there's a helpful fixit
12880
12881 if (!R) {
12882 // We will have already diagnosed the problem on the template
12883 // definition, Maybe we should do so again?
12884 } else if (R->getAsSingle<TypeDecl>()) {
12885 if (getLangOpts().CPlusPlus11) {
12886 // Convert 'using X::Y;' to 'using Y = X::Y;'.
12887 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12888 << 0 // alias declaration
12889 << FixItHint::CreateInsertion(SS.getBeginLoc(),
12890 NameInfo.getName().getAsString() +
12891 " = ");
12892 } else {
12893 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12894 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12895 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12896 << 1 // typedef declaration
12897 << FixItHint::CreateReplacement(UsingLoc, "typedef")
12898 << FixItHint::CreateInsertion(
12899 InsertLoc, " " + NameInfo.getName().getAsString());
12900 }
12901 } else if (R->getAsSingle<VarDecl>()) {
12902 // Don't provide a fixit outside C++11 mode; we don't want to suggest
12903 // repeating the type of the static data member here.
12904 FixItHint FixIt;
12905 if (getLangOpts().CPlusPlus11) {
12906 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12907 FixIt = FixItHint::CreateReplacement(
12908 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12909 }
12910
12911 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12912 << 2 // reference declaration
12913 << FixIt;
12914 } else if (R->getAsSingle<EnumConstantDecl>()) {
12915 // Don't provide a fixit outside C++11 mode; we don't want to suggest
12916 // repeating the type of the enumeration here, and we can't do so if
12917 // the type is anonymous.
12918 FixItHint FixIt;
12919 if (getLangOpts().CPlusPlus11) {
12920 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12921 FixIt = FixItHint::CreateReplacement(
12922 UsingLoc,
12923 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12924 }
12925
12926 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12927 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12928 << FixIt;
12929 }
12930 }
12931
12932 return true; // Fail
12933 }
12934
12935 // If the named context is dependent, we can't decide much.
12936 if (!NamedContext) {
12937 // FIXME: in C++0x, we can diagnose if we can prove that the
12938 // nested-name-specifier does not refer to a base class, which is
12939 // still possible in some cases.
12940
12941 // Otherwise we have to conservatively report that things might be
12942 // okay.
12943 return false;
12944 }
12945
12946 // The current scope is a record.
12947 if (!NamedContext->isRecord()) {
12948 // Ideally this would point at the last name in the specifier,
12949 // but we don't have that level of source info.
12950 Diag(SS.getBeginLoc(),
12951 Cxx20Enumerator
12952 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12953 : diag::err_using_decl_nested_name_specifier_is_not_class)
12954 << SS.getScopeRep() << SS.getRange();
12955
12956 if (Cxx20Enumerator)
12957 return false; // OK
12958
12959 return true;
12960 }
12961
12962 if (!NamedContext->isDependentContext() &&
12963 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12964 return true;
12965
12966 if (getLangOpts().CPlusPlus11) {
12967 // C++11 [namespace.udecl]p3:
12968 // In a using-declaration used as a member-declaration, the
12969 // nested-name-specifier shall name a base class of the class
12970 // being defined.
12971
12972 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12973 cast<CXXRecordDecl>(NamedContext))) {
12974
12975 if (Cxx20Enumerator) {
12976 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12977 << SS.getRange();
12978 return false;
12979 }
12980
12981 if (CurContext == NamedContext) {
12982 Diag(SS.getBeginLoc(),
12983 diag::err_using_decl_nested_name_specifier_is_current_class)
12984 << SS.getRange();
12985 return !getLangOpts().CPlusPlus20;
12986 }
12987
12988 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12989 Diag(SS.getBeginLoc(),
12990 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12991 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
12992 << SS.getRange();
12993 }
12994 return true;
12995 }
12996
12997 return false;
12998 }
12999
13000 // C++03 [namespace.udecl]p4:
13001 // A using-declaration used as a member-declaration shall refer
13002 // to a member of a base class of the class being defined [etc.].
13003
13004 // Salient point: SS doesn't have to name a base class as long as
13005 // lookup only finds members from base classes. Therefore we can
13006 // diagnose here only if we can prove that can't happen,
13007 // i.e. if the class hierarchies provably don't intersect.
13008
13009 // TODO: it would be nice if "definitely valid" results were cached
13010 // in the UsingDecl and UsingShadowDecl so that these checks didn't
13011 // need to be repeated.
13012
13013 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
13014 auto Collect = [&Bases](const CXXRecordDecl *Base) {
13015 Bases.insert(Base);
13016 return true;
13017 };
13018
13019 // Collect all bases. Return false if we find a dependent base.
13020 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
13021 return false;
13022
13023 // Returns true if the base is dependent or is one of the accumulated base
13024 // classes.
13025 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
13026 return !Bases.count(Base);
13027 };
13028
13029 // Return false if the class has a dependent base or if it or one
13030 // of its bases is present in the base set of the current context.
13031 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
13032 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
13033 return false;
13034
13035 Diag(SS.getRange().getBegin(),
13036 diag::err_using_decl_nested_name_specifier_is_not_base_class)
13037 << SS.getScopeRep()
13038 << cast<CXXRecordDecl>(CurContext)
13039 << SS.getRange();
13040
13041 return true;
13042}
13043
13044Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13045 MultiTemplateParamsArg TemplateParamLists,
13046 SourceLocation UsingLoc, UnqualifiedId &Name,
13047 const ParsedAttributesView &AttrList,
13048 TypeResult Type, Decl *DeclFromDeclSpec) {
13049 // Skip up to the relevant declaration scope.
13050 while (S->isTemplateParamScope())
13051 S = S->getParent();
13052 assert((S->getFlags() & Scope::DeclScope) &&(static_cast <bool> ((S->getFlags() & Scope::DeclScope
) && "got alias-declaration outside of declaration scope"
) ? void (0) : __assert_fail ("(S->getFlags() & Scope::DeclScope) && \"got alias-declaration outside of declaration scope\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13053, __extension__ __PRETTY_FUNCTION__
))
13053 "got alias-declaration outside of declaration scope")(static_cast <bool> ((S->getFlags() & Scope::DeclScope
) && "got alias-declaration outside of declaration scope"
) ? void (0) : __assert_fail ("(S->getFlags() & Scope::DeclScope) && \"got alias-declaration outside of declaration scope\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13053, __extension__ __PRETTY_FUNCTION__
))
;
13054
13055 if (Type.isInvalid())
13056 return nullptr;
13057
13058 bool Invalid = false;
13059 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13060 TypeSourceInfo *TInfo = nullptr;
13061 GetTypeFromParser(Type.get(), &TInfo);
13062
13063 if (DiagnoseClassNameShadow(CurContext, NameInfo))
13064 return nullptr;
13065
13066 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
13067 UPPC_DeclarationType)) {
13068 Invalid = true;
13069 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13070 TInfo->getTypeLoc().getBeginLoc());
13071 }
13072
13073 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13074 TemplateParamLists.size()
13075 ? forRedeclarationInCurContext()
13076 : ForVisibleRedeclaration);
13077 LookupName(Previous, S);
13078
13079 // Warn about shadowing the name of a template parameter.
13080 if (Previous.isSingleResult() &&
13081 Previous.getFoundDecl()->isTemplateParameter()) {
13082 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13083 Previous.clear();
13084 }
13085
13086 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&(static_cast <bool> (Name.getKind() == UnqualifiedIdKind
::IK_Identifier && "name in alias declaration must be an identifier"
) ? void (0) : __assert_fail ("Name.getKind() == UnqualifiedIdKind::IK_Identifier && \"name in alias declaration must be an identifier\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13087, __extension__ __PRETTY_FUNCTION__
))
13087 "name in alias declaration must be an identifier")(static_cast <bool> (Name.getKind() == UnqualifiedIdKind
::IK_Identifier && "name in alias declaration must be an identifier"
) ? void (0) : __assert_fail ("Name.getKind() == UnqualifiedIdKind::IK_Identifier && \"name in alias declaration must be an identifier\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13087, __extension__ __PRETTY_FUNCTION__
))
;
13088 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
13089 Name.StartLocation,
13090 Name.Identifier, TInfo);
13091
13092 NewTD->setAccess(AS);
13093
13094 if (Invalid)
13095 NewTD->setInvalidDecl();
13096
13097 ProcessDeclAttributeList(S, NewTD, AttrList);
13098 AddPragmaAttributes(S, NewTD);
13099
13100 CheckTypedefForVariablyModifiedType(S, NewTD);
13101 Invalid |= NewTD->isInvalidDecl();
13102
13103 bool Redeclaration = false;
13104
13105 NamedDecl *NewND;
13106 if (TemplateParamLists.size()) {
13107 TypeAliasTemplateDecl *OldDecl = nullptr;
13108 TemplateParameterList *OldTemplateParams = nullptr;
13109
13110 if (TemplateParamLists.size() != 1) {
13111 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13112 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13113 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13114 }
13115 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13116
13117 // Check that we can declare a template here.
13118 if (CheckTemplateDeclScope(S, TemplateParams))
13119 return nullptr;
13120
13121 // Only consider previous declarations in the same scope.
13122 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13123 /*ExplicitInstantiationOrSpecialization*/false);
13124 if (!Previous.empty()) {
13125 Redeclaration = true;
13126
13127 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13128 if (!OldDecl && !Invalid) {
13129 Diag(UsingLoc, diag::err_redefinition_different_kind)
13130 << Name.Identifier;
13131
13132 NamedDecl *OldD = Previous.getRepresentativeDecl();
13133 if (OldD->getLocation().isValid())
13134 Diag(OldD->getLocation(), diag::note_previous_definition);
13135
13136 Invalid = true;
13137 }
13138
13139 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13140 if (TemplateParameterListsAreEqual(TemplateParams,
13141 OldDecl->getTemplateParameters(),
13142 /*Complain=*/true,
13143 TPL_TemplateMatch))
13144 OldTemplateParams =
13145 OldDecl->getMostRecentDecl()->getTemplateParameters();
13146 else
13147 Invalid = true;
13148
13149 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13150 if (!Invalid &&
13151 !Context.hasSameType(OldTD->getUnderlyingType(),
13152 NewTD->getUnderlyingType())) {
13153 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13154 // but we can't reasonably accept it.
13155 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13156 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13157 if (OldTD->getLocation().isValid())
13158 Diag(OldTD->getLocation(), diag::note_previous_definition);
13159 Invalid = true;
13160 }
13161 }
13162 }
13163
13164 // Merge any previous default template arguments into our parameters,
13165 // and check the parameter list.
13166 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13167 TPC_TypeAliasTemplate))
13168 return nullptr;
13169
13170 TypeAliasTemplateDecl *NewDecl =
13171 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13172 Name.Identifier, TemplateParams,
13173 NewTD);
13174 NewTD->setDescribedAliasTemplate(NewDecl);
13175
13176 NewDecl->setAccess(AS);
13177
13178 if (Invalid)
13179 NewDecl->setInvalidDecl();
13180 else if (OldDecl) {
13181 NewDecl->setPreviousDecl(OldDecl);
13182 CheckRedeclarationInModule(NewDecl, OldDecl);
13183 }
13184
13185 NewND = NewDecl;
13186 } else {
13187 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13188 setTagNameForLinkagePurposes(TD, NewTD);
13189 handleTagNumbering(TD, S);
13190 }
13191 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13192 NewND = NewTD;
13193 }
13194
13195 PushOnScopeChains(NewND, S);
13196 ActOnDocumentableDecl(NewND);
13197 return NewND;
13198}
13199
13200Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13201 SourceLocation AliasLoc,
13202 IdentifierInfo *Alias, CXXScopeSpec &SS,
13203 SourceLocation IdentLoc,
13204 IdentifierInfo *Ident) {
13205
13206 // Lookup the namespace name.
13207 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13208 LookupParsedName(R, S, &SS);
13209
13210 if (R.isAmbiguous())
13211 return nullptr;
13212
13213 if (R.empty()) {
13214 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13215 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13216 return nullptr;
13217 }
13218 }
13219 assert(!R.isAmbiguous() && !R.empty())(static_cast <bool> (!R.isAmbiguous() && !R.empty
()) ? void (0) : __assert_fail ("!R.isAmbiguous() && !R.empty()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 13219, __extension__ __PRETTY_FUNCTION__
))
;
13220 NamedDecl *ND = R.getRepresentativeDecl();
13221
13222 // Check if we have a previous declaration with the same name.
13223 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13224 ForVisibleRedeclaration);
13225 LookupName(PrevR, S);
13226
13227 // Check we're not shadowing a template parameter.
13228 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13229 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13230 PrevR.clear();
13231 }
13232
13233 // Filter out any other lookup result from an enclosing scope.
13234 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13235 /*AllowInlineNamespace*/false);
13236
13237 // Find the previous declaration and check that we can redeclare it.
13238 NamespaceAliasDecl *Prev = nullptr;
13239 if (PrevR.isSingleResult()) {
13240 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13241 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13242 // We already have an alias with the same name that points to the same
13243 // namespace; check that it matches.
13244 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13245 Prev = AD;
13246 } else if (isVisible(PrevDecl)) {
13247 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13248 << Alias;
13249 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13250 << AD->getNamespace();
13251 return nullptr;
13252 }
13253 } else if (isVisible(PrevDecl)) {
13254 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13255 ? diag::err_redefinition
13256 : diag::err_redefinition_different_kind;
13257 Diag(AliasLoc, DiagID) << Alias;
13258 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13259 return nullptr;
13260 }
13261 }
13262
13263 // The use of a nested name specifier may trigger deprecation warnings.
13264 DiagnoseUseOfDecl(ND, IdentLoc);
13265
13266 NamespaceAliasDecl *AliasDecl =
13267 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13268 Alias, SS.getWithLocInContext(Context),
13269 IdentLoc, ND);
13270 if (Prev)
13271 AliasDecl->setPreviousDecl(Prev);
13272
13273 PushOnScopeChains(AliasDecl, S);
13274 return AliasDecl;
13275}
13276
13277namespace {
13278struct SpecialMemberExceptionSpecInfo
13279 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13280 SourceLocation Loc;
13281 Sema::ImplicitExceptionSpecification ExceptSpec;
13282
13283 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13284 Sema::CXXSpecialMember CSM,
13285 Sema::InheritedConstructorInfo *ICI,
13286 SourceLocation Loc)
13287 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13288
13289 bool visitBase(CXXBaseSpecifier *Base);
13290 bool visitField(FieldDecl *FD);
13291
13292 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13293 unsigned Quals);
13294
13295 void visitSubobjectCall(Subobject Subobj,
13296 Sema::SpecialMemberOverloadResult SMOR);
13297};
13298}
13299
13300bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13301 auto *RT = Base->getType()->getAs<RecordType>();
13302 if (!RT)
13303 return false;
13304
13305 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13306 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13307 if (auto *BaseCtor = SMOR.getMethod()) {
13308 visitSubobjectCall(Base, BaseCtor);
13309 return false;
13310 }
13311
13312 visitClassSubobject(BaseClass, Base, 0);
13313 return false;
13314}
13315
13316bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13317 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13318 Expr *E = FD->getInClassInitializer();
13319 if (!E)
13320 // FIXME: It's a little wasteful to build and throw away a
13321 // CXXDefaultInitExpr here.
13322 // FIXME: We should have a single context note pointing at Loc, and
13323 // this location should be MD->getLocation() instead, since that's
13324 // the location where we actually use the default init expression.
13325 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13326 if (E)
13327 ExceptSpec.CalledExpr(E);
13328 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13329 ->getAs<RecordType>()) {
13330 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13331 FD->getType().getCVRQualifiers());
13332 }
13333 return false;
13334}
13335
13336void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13337 Subobject Subobj,
13338 unsigned Quals) {
13339 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13340 bool IsMutable = Field && Field->isMutable();
13341 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13342}
13343
13344void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13345 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13346 // Note, if lookup fails, it doesn't matter what exception specification we
13347 // choose because the special member will be deleted.
13348 if (CXXMethodDecl *MD = SMOR.getMethod())
13349 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13350}
13351
13352bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13353 llvm::APSInt Result;
13354 ExprResult Converted = CheckConvertedConstantExpression(
13355 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13356 ExplicitSpec.setExpr(Converted.get());
13357 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13358 ExplicitSpec.setKind(Result.getBoolValue()
13359 ? ExplicitSpecKind::ResolvedTrue
13360 : ExplicitSpecKind::ResolvedFalse);
13361 return true;
13362 }
13363 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13364 return false;
13365}
13366
13367ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13368 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13369 if (!ExplicitExpr->isTypeDependent())
13370 tryResolveExplicitSpecifier(ES);
13371 return ES;
13372}
13373
13374static Sema::ImplicitExceptionSpecification
13375ComputeDefaultedSpecialMemberExceptionSpec(
13376 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13377 Sema::InheritedConstructorInfo *ICI) {
13378 ComputingExceptionSpec CES(S, MD, Loc);
13379
13380 CXXRecordDecl *ClassDecl = MD->getParent();
13381
13382 // C++ [except.spec]p14:
13383 // An implicitly declared special member function (Clause 12) shall have an
13384 // exception-specification. [...]
13385 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13386 if (ClassDecl->isInvalidDecl())
13387 return Info.ExceptSpec;
13388
13389 // FIXME: If this diagnostic fires, we're probably missing a check for
13390 // attempting to resolve an exception specification before it's known
13391 // at a higher level.
13392 if (S.RequireCompleteType(MD->getLocation(),
13393 S.Context.getRecordType(ClassDecl),
13394 diag::err_exception_spec_incomplete_type))
13395 return Info.ExceptSpec;
13396
13397 // C++1z [except.spec]p7:
13398 // [Look for exceptions thrown by] a constructor selected [...] to
13399 // initialize a potentially constructed subobject,
13400 // C++1z [except.spec]p8:
13401 // The exception specification for an implicitly-declared destructor, or a
13402 // destructor without a noexcept-specifier, is potentially-throwing if and
13403 // only if any of the destructors for any of its potentially constructed
13404 // subojects is potentially throwing.
13405 // FIXME: We respect the first rule but ignore the "potentially constructed"
13406 // in the second rule to resolve a core issue (no number yet) that would have
13407 // us reject:
13408 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13409 // struct B : A {};
13410 // struct C : B { void f(); };
13411 // ... due to giving B::~B() a non-throwing exception specification.
13412 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13413 : Info.VisitAllBases);
13414
13415 return Info.ExceptSpec;
13416}
13417
13418namespace {
13419/// RAII object to register a special member as being currently declared.
13420struct DeclaringSpecialMember {
13421 Sema &S;
13422 Sema::SpecialMemberDecl D;
13423 Sema::ContextRAII SavedContext;
13424 bool WasAlreadyBeingDeclared;
13425
13426 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13427 : S(S), D(RD, CSM), SavedContext(S, RD) {
13428 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13429 if (WasAlreadyBeingDeclared)
13430 // This almost never happens, but if it does, ensure that our cache
13431 // doesn't contain a stale result.
13432 S.SpecialMemberCache.clear();
13433 else {
13434 // Register a note to be produced if we encounter an error while
13435 // declaring the special member.
13436 Sema::CodeSynthesisContext Ctx;
13437 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13438 // FIXME: We don't have a location to use here. Using the class's
13439 // location maintains the fiction that we declare all special members
13440 // with the class, but (1) it's not clear that lying about that helps our
13441 // users understand what's going on, and (2) there may be outer contexts
13442 // on the stack (some of which are relevant) and printing them exposes
13443 // our lies.
13444 Ctx.PointOfInstantiation = RD->getLocation();
13445 Ctx.Entity = RD;
13446 Ctx.SpecialMember = CSM;
13447 S.pushCodeSynthesisContext(Ctx);
13448 }
13449 }
13450 ~DeclaringSpecialMember() {
13451 if (!WasAlreadyBeingDeclared) {
13452 S.SpecialMembersBeingDeclared.erase(D);
13453 S.popCodeSynthesisContext();
13454 }
13455 }
13456
13457 /// Are we already trying to declare this special member?
13458 bool isAlreadyBeingDeclared() const {
13459 return WasAlreadyBeingDeclared;
13460 }
13461};
13462}
13463
13464void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13465 // Look up any existing declarations, but don't trigger declaration of all
13466 // implicit special members with this name.
13467 DeclarationName Name = FD->getDeclName();
13468 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13469 ForExternalRedeclaration);
13470 for (auto *D : FD->getParent()->lookup(Name))
13471 if (auto *Acceptable = R.getAcceptableDecl(D))
13472 R.addDecl(Acceptable);
13473 R.resolveKind();
13474 R.suppressDiagnostics();
13475
13476 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13477 FD->isThisDeclarationADefinition());
13478}
13479
13480void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13481 QualType ResultTy,
13482 ArrayRef<QualType> Args) {
13483 // Build an exception specification pointing back at this constructor.
13484 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13485
13486 LangAS AS = getDefaultCXXMethodAddrSpace();
13487 if (AS != LangAS::Default) {
13488 EPI.TypeQuals.addAddressSpace(AS);
13489 }
13490
13491 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13492 SpecialMem->setType(QT);
13493
13494 // During template instantiation of implicit special member functions we need
13495 // a reliable TypeSourceInfo for the function prototype in order to allow
13496 // functions to be substituted.
13497 if (inTemplateInstantiation() &&
13498 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13499 TypeSourceInfo *TSI =
13500 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13501 SpecialMem->setTypeSourceInfo(TSI);
13502 }
13503}
13504
13505CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13506 CXXRecordDecl *ClassDecl) {
13507 // C++ [class.ctor]p5:
13508 // A default constructor for a class X is a constructor of class X
13509 // that can be called without an argument. If there is no
13510 // user-declared constructor for class X, a default constructor is
13511 // implicitly declared. An implicitly-declared default constructor
13512 // is an inline public member of its class.
13513 assert(ClassDecl->needsImplicitDefaultConstructor() &&(static_cast <bool> (ClassDecl->needsImplicitDefaultConstructor
() && "Should not build implicit default constructor!"
) ? void (0) : __assert_fail ("ClassDecl->needsImplicitDefaultConstructor() && \"Should not build implicit default constructor!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13514, __extension__ __PRETTY_FUNCTION__
))
13514 "Should not build implicit default constructor!")(static_cast <bool> (ClassDecl->needsImplicitDefaultConstructor
() && "Should not build implicit default constructor!"
) ? void (0) : __assert_fail ("ClassDecl->needsImplicitDefaultConstructor() && \"Should not build implicit default constructor!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13514, __extension__ __PRETTY_FUNCTION__
))
;
13515
13516 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13517 if (DSM.isAlreadyBeingDeclared())
13518 return nullptr;
13519
13520 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13521 CXXDefaultConstructor,
13522 false);
13523
13524 // Create the actual constructor declaration.
13525 CanQualType ClassType
13526 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13527 SourceLocation ClassLoc = ClassDecl->getLocation();
13528 DeclarationName Name
13529 = Context.DeclarationNames.getCXXConstructorName(ClassType);
13530 DeclarationNameInfo NameInfo(Name, ClassLoc);
13531 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13532 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13533 /*TInfo=*/nullptr, ExplicitSpecifier(),
13534 getCurFPFeatures().isFPConstrained(),
13535 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13536 Constexpr ? ConstexprSpecKind::Constexpr
13537 : ConstexprSpecKind::Unspecified);
13538 DefaultCon->setAccess(AS_public);
13539 DefaultCon->setDefaulted();
13540
13541 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt);
13542
13543 if (getLangOpts().CUDA)
13544 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13545 DefaultCon,
13546 /* ConstRHS */ false,
13547 /* Diagnose */ false);
13548
13549 // We don't need to use SpecialMemberIsTrivial here; triviality for default
13550 // constructors is easy to compute.
13551 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13552
13553 // Note that we have declared this constructor.
13554 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13555
13556 Scope *S = getScopeForContext(ClassDecl);
13557 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13558
13559 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13560 SetDeclDeleted(DefaultCon, ClassLoc);
13561
13562 if (S)
13563 PushOnScopeChains(DefaultCon, S, false);
13564 ClassDecl->addDecl(DefaultCon);
13565
13566 return DefaultCon;
13567}
13568
13569void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13570 CXXConstructorDecl *Constructor) {
13571 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&(static_cast <bool> ((Constructor->isDefaulted() &&
Constructor->isDefaultConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? void (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13574, __extension__ __PRETTY_FUNCTION__
))
13572 !Constructor->doesThisDeclarationHaveABody() &&(static_cast <bool> ((Constructor->isDefaulted() &&
Constructor->isDefaultConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? void (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13574, __extension__ __PRETTY_FUNCTION__
))
13573 !Constructor->isDeleted()) &&(static_cast <bool> ((Constructor->isDefaulted() &&
Constructor->isDefaultConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? void (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13574, __extension__ __PRETTY_FUNCTION__
))
13574 "DefineImplicitDefaultConstructor - call it for implicit default ctor")(static_cast <bool> ((Constructor->isDefaulted() &&
Constructor->isDefaultConstructor() && !Constructor
->doesThisDeclarationHaveABody() && !Constructor->
isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor"
) ? void (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13574, __extension__ __PRETTY_FUNCTION__
))
;
13575 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13576 return;
13577
13578 CXXRecordDecl *ClassDecl = Constructor->getParent();
13579 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor")(static_cast <bool> (ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"
) ? void (0) : __assert_fail ("ClassDecl && \"DefineImplicitDefaultConstructor - invalid constructor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13579, __extension__ __PRETTY_FUNCTION__
))
;
13580
13581 SynthesizedFunctionScope Scope(*this, Constructor);
13582
13583 // The exception specification is needed because we are defining the
13584 // function.
13585 ResolveExceptionSpec(CurrentLocation,
13586 Constructor->getType()->castAs<FunctionProtoType>());
13587 MarkVTableUsed(CurrentLocation, ClassDecl);
13588
13589 // Add a context note for diagnostics produced after this point.
13590 Scope.addContextNote(CurrentLocation);
13591
13592 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13593 Constructor->setInvalidDecl();
13594 return;
13595 }
13596
13597 SourceLocation Loc = Constructor->getEndLoc().isValid()
13598 ? Constructor->getEndLoc()
13599 : Constructor->getLocation();
13600 Constructor->setBody(new (Context) CompoundStmt(Loc));
13601 Constructor->markUsed(Context);
13602
13603 if (ASTMutationListener *L = getASTMutationListener()) {
13604 L->CompletedImplicitDefinition(Constructor);
13605 }
13606
13607 DiagnoseUninitializedFields(*this, Constructor);
13608}
13609
13610void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13611 // Perform any delayed checks on exception specifications.
13612 CheckDelayedMemberExceptionSpecs();
13613}
13614
13615/// Find or create the fake constructor we synthesize to model constructing an
13616/// object of a derived class via a constructor of a base class.
13617CXXConstructorDecl *
13618Sema::findInheritingConstructor(SourceLocation Loc,
13619 CXXConstructorDecl *BaseCtor,
13620 ConstructorUsingShadowDecl *Shadow) {
13621 CXXRecordDecl *Derived = Shadow->getParent();
13622 SourceLocation UsingLoc = Shadow->getLocation();
13623
13624 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13625 // For now we use the name of the base class constructor as a member of the
13626 // derived class to indicate a (fake) inherited constructor name.
13627 DeclarationName Name = BaseCtor->getDeclName();
13628
13629 // Check to see if we already have a fake constructor for this inherited
13630 // constructor call.
13631 for (NamedDecl *Ctor : Derived->lookup(Name))
13632 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13633 ->getInheritedConstructor()
13634 .getConstructor(),
13635 BaseCtor))
13636 return cast<CXXConstructorDecl>(Ctor);
13637
13638 DeclarationNameInfo NameInfo(Name, UsingLoc);
13639 TypeSourceInfo *TInfo =
13640 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13641 FunctionProtoTypeLoc ProtoLoc =
13642 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13643
13644 // Check the inherited constructor is valid and find the list of base classes
13645 // from which it was inherited.
13646 InheritedConstructorInfo ICI(*this, Loc, Shadow);
13647
13648 bool Constexpr =
13649 BaseCtor->isConstexpr() &&
13650 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13651 false, BaseCtor, &ICI);
13652
13653 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13654 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13655 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13656 /*isInline=*/true,
13657 /*isImplicitlyDeclared=*/true,
13658 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13659 InheritedConstructor(Shadow, BaseCtor),
13660 BaseCtor->getTrailingRequiresClause());
13661 if (Shadow->isInvalidDecl())
13662 DerivedCtor->setInvalidDecl();
13663
13664 // Build an unevaluated exception specification for this fake constructor.
13665 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13666 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13667 EPI.ExceptionSpec.Type = EST_Unevaluated;
13668 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13669 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13670 FPT->getParamTypes(), EPI));
13671
13672 // Build the parameter declarations.
13673 SmallVector<ParmVarDecl *, 16> ParamDecls;
13674 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13675 TypeSourceInfo *TInfo =
13676 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13677 ParmVarDecl *PD = ParmVarDecl::Create(
13678 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13679 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13680 PD->setScopeInfo(0, I);
13681 PD->setImplicit();
13682 // Ensure attributes are propagated onto parameters (this matters for
13683 // format, pass_object_size, ...).
13684 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13685 ParamDecls.push_back(PD);
13686 ProtoLoc.setParam(I, PD);
13687 }
13688
13689 // Set up the new constructor.
13690 assert(!BaseCtor->isDeleted() && "should not use deleted constructor")(static_cast <bool> (!BaseCtor->isDeleted() &&
"should not use deleted constructor") ? void (0) : __assert_fail
("!BaseCtor->isDeleted() && \"should not use deleted constructor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13690, __extension__ __PRETTY_FUNCTION__
))
;
13691 DerivedCtor->setAccess(BaseCtor->getAccess());
13692 DerivedCtor->setParams(ParamDecls);
13693 Derived->addDecl(DerivedCtor);
13694
13695 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13696 SetDeclDeleted(DerivedCtor, UsingLoc);
13697
13698 return DerivedCtor;
13699}
13700
13701void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13702 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13703 Ctor->getInheritedConstructor().getShadowDecl());
13704 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13705 /*Diagnose*/true);
13706}
13707
13708void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13709 CXXConstructorDecl *Constructor) {
13710 CXXRecordDecl *ClassDecl = Constructor->getParent();
13711 assert(Constructor->getInheritedConstructor() &&(static_cast <bool> (Constructor->getInheritedConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) ? void (0) : __assert_fail
("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 13713, __extension__ __PRETTY_FUNCTION__
))
13712 !Constructor->doesThisDeclarationHaveABody() &&(static_cast <bool> (Constructor->getInheritedConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) ? void (0) : __assert_fail
("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 13713, __extension__ __PRETTY_FUNCTION__
))
13713 !Constructor->isDeleted())(static_cast <bool> (Constructor->getInheritedConstructor
() && !Constructor->doesThisDeclarationHaveABody()
&& !Constructor->isDeleted()) ? void (0) : __assert_fail
("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 13713, __extension__ __PRETTY_FUNCTION__
))
;
13714 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13715 return;
13716
13717 // Initializations are performed "as if by a defaulted default constructor",
13718 // so enter the appropriate scope.
13719 SynthesizedFunctionScope Scope(*this, Constructor);
13720
13721 // The exception specification is needed because we are defining the
13722 // function.
13723 ResolveExceptionSpec(CurrentLocation,
13724 Constructor->getType()->castAs<FunctionProtoType>());
13725 MarkVTableUsed(CurrentLocation, ClassDecl);
13726
13727 // Add a context note for diagnostics produced after this point.
13728 Scope.addContextNote(CurrentLocation);
13729
13730 ConstructorUsingShadowDecl *Shadow =
13731 Constructor->getInheritedConstructor().getShadowDecl();
13732 CXXConstructorDecl *InheritedCtor =
13733 Constructor->getInheritedConstructor().getConstructor();
13734
13735 // [class.inhctor.init]p1:
13736 // initialization proceeds as if a defaulted default constructor is used to
13737 // initialize the D object and each base class subobject from which the
13738 // constructor was inherited
13739
13740 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13741 CXXRecordDecl *RD = Shadow->getParent();
13742 SourceLocation InitLoc = Shadow->getLocation();
13743
13744 // Build explicit initializers for all base classes from which the
13745 // constructor was inherited.
13746 SmallVector<CXXCtorInitializer*, 8> Inits;
13747 for (bool VBase : {false, true}) {
13748 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13749 if (B.isVirtual() != VBase)
13750 continue;
13751
13752 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13753 if (!BaseRD)
13754 continue;
13755
13756 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13757 if (!BaseCtor.first)
13758 continue;
13759
13760 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13761 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13762 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13763
13764 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13765 Inits.push_back(new (Context) CXXCtorInitializer(
13766 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13767 SourceLocation()));
13768 }
13769 }
13770
13771 // We now proceed as if for a defaulted default constructor, with the relevant
13772 // initializers replaced.
13773
13774 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13775 Constructor->setInvalidDecl();
13776 return;
13777 }
13778
13779 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13780 Constructor->markUsed(Context);
13781
13782 if (ASTMutationListener *L = getASTMutationListener()) {
13783 L->CompletedImplicitDefinition(Constructor);
13784 }
13785
13786 DiagnoseUninitializedFields(*this, Constructor);
13787}
13788
13789CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13790 // C++ [class.dtor]p2:
13791 // If a class has no user-declared destructor, a destructor is
13792 // declared implicitly. An implicitly-declared destructor is an
13793 // inline public member of its class.
13794 assert(ClassDecl->needsImplicitDestructor())(static_cast <bool> (ClassDecl->needsImplicitDestructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitDestructor()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 13794, __extension__ __PRETTY_FUNCTION__
))
;
13795
13796 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13797 if (DSM.isAlreadyBeingDeclared())
13798 return nullptr;
13799
13800 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13801 CXXDestructor,
13802 false);
13803
13804 // Create the actual destructor declaration.
13805 CanQualType ClassType
13806 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13807 SourceLocation ClassLoc = ClassDecl->getLocation();
13808 DeclarationName Name
13809 = Context.DeclarationNames.getCXXDestructorName(ClassType);
13810 DeclarationNameInfo NameInfo(Name, ClassLoc);
13811 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
13812 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
13813 getCurFPFeatures().isFPConstrained(),
13814 /*isInline=*/true,
13815 /*isImplicitlyDeclared=*/true,
13816 Constexpr ? ConstexprSpecKind::Constexpr
13817 : ConstexprSpecKind::Unspecified);
13818 Destructor->setAccess(AS_public);
13819 Destructor->setDefaulted();
13820
13821 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt);
13822
13823 if (getLangOpts().CUDA)
13824 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13825 Destructor,
13826 /* ConstRHS */ false,
13827 /* Diagnose */ false);
13828
13829 // We don't need to use SpecialMemberIsTrivial here; triviality for
13830 // destructors is easy to compute.
13831 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13832 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13833 ClassDecl->hasTrivialDestructorForCall());
13834
13835 // Note that we have declared this destructor.
13836 ++getASTContext().NumImplicitDestructorsDeclared;
13837
13838 Scope *S = getScopeForContext(ClassDecl);
13839 CheckImplicitSpecialMemberDeclaration(S, Destructor);
13840
13841 // We can't check whether an implicit destructor is deleted before we complete
13842 // the definition of the class, because its validity depends on the alignment
13843 // of the class. We'll check this from ActOnFields once the class is complete.
13844 if (ClassDecl->isCompleteDefinition() &&
13845 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13846 SetDeclDeleted(Destructor, ClassLoc);
13847
13848 // Introduce this destructor into its scope.
13849 if (S)
13850 PushOnScopeChains(Destructor, S, false);
13851 ClassDecl->addDecl(Destructor);
13852
13853 return Destructor;
13854}
13855
13856void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13857 CXXDestructorDecl *Destructor) {
13858 assert((Destructor->isDefaulted() &&(static_cast <bool> ((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() && !Destructor
->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? void (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13861, __extension__ __PRETTY_FUNCTION__
))
13859 !Destructor->doesThisDeclarationHaveABody() &&(static_cast <bool> ((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() && !Destructor
->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? void (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13861, __extension__ __PRETTY_FUNCTION__
))
13860 !Destructor->isDeleted()) &&(static_cast <bool> ((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() && !Destructor
->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? void (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13861, __extension__ __PRETTY_FUNCTION__
))
13861 "DefineImplicitDestructor - call it for implicit default dtor")(static_cast <bool> ((Destructor->isDefaulted() &&
!Destructor->doesThisDeclarationHaveABody() && !Destructor
->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor"
) ? void (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13861, __extension__ __PRETTY_FUNCTION__
))
;
13862 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13863 return;
13864
13865 CXXRecordDecl *ClassDecl = Destructor->getParent();
13866 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor")(static_cast <bool> (ClassDecl && "DefineImplicitDestructor - invalid destructor"
) ? void (0) : __assert_fail ("ClassDecl && \"DefineImplicitDestructor - invalid destructor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13866, __extension__ __PRETTY_FUNCTION__
))
;
13867
13868 SynthesizedFunctionScope Scope(*this, Destructor);
13869
13870 // The exception specification is needed because we are defining the
13871 // function.
13872 ResolveExceptionSpec(CurrentLocation,
13873 Destructor->getType()->castAs<FunctionProtoType>());
13874 MarkVTableUsed(CurrentLocation, ClassDecl);
13875
13876 // Add a context note for diagnostics produced after this point.
13877 Scope.addContextNote(CurrentLocation);
13878
13879 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13880 Destructor->getParent());
13881
13882 if (CheckDestructor(Destructor)) {
13883 Destructor->setInvalidDecl();
13884 return;
13885 }
13886
13887 SourceLocation Loc = Destructor->getEndLoc().isValid()
13888 ? Destructor->getEndLoc()
13889 : Destructor->getLocation();
13890 Destructor->setBody(new (Context) CompoundStmt(Loc));
13891 Destructor->markUsed(Context);
13892
13893 if (ASTMutationListener *L = getASTMutationListener()) {
13894 L->CompletedImplicitDefinition(Destructor);
13895 }
13896}
13897
13898void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13899 CXXDestructorDecl *Destructor) {
13900 if (Destructor->isInvalidDecl())
13901 return;
13902
13903 CXXRecordDecl *ClassDecl = Destructor->getParent();
13904 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&(static_cast <bool> (Context.getTargetInfo().getCXXABI(
).isMicrosoft() && "implicit complete dtors unneeded outside MS ABI"
) ? void (0) : __assert_fail ("Context.getTargetInfo().getCXXABI().isMicrosoft() && \"implicit complete dtors unneeded outside MS ABI\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13905, __extension__ __PRETTY_FUNCTION__
))
13905 "implicit complete dtors unneeded outside MS ABI")(static_cast <bool> (Context.getTargetInfo().getCXXABI(
).isMicrosoft() && "implicit complete dtors unneeded outside MS ABI"
) ? void (0) : __assert_fail ("Context.getTargetInfo().getCXXABI().isMicrosoft() && \"implicit complete dtors unneeded outside MS ABI\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13905, __extension__ __PRETTY_FUNCTION__
))
;
13906 assert(ClassDecl->getNumVBases() > 0 &&(static_cast <bool> (ClassDecl->getNumVBases() > 0
&& "complete dtor only exists for classes with vbases"
) ? void (0) : __assert_fail ("ClassDecl->getNumVBases() > 0 && \"complete dtor only exists for classes with vbases\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13907, __extension__ __PRETTY_FUNCTION__
))
13907 "complete dtor only exists for classes with vbases")(static_cast <bool> (ClassDecl->getNumVBases() > 0
&& "complete dtor only exists for classes with vbases"
) ? void (0) : __assert_fail ("ClassDecl->getNumVBases() > 0 && \"complete dtor only exists for classes with vbases\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13907, __extension__ __PRETTY_FUNCTION__
))
;
13908
13909 SynthesizedFunctionScope Scope(*this, Destructor);
13910
13911 // Add a context note for diagnostics produced after this point.
13912 Scope.addContextNote(CurrentLocation);
13913
13914 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13915}
13916
13917/// Perform any semantic analysis which needs to be delayed until all
13918/// pending class member declarations have been parsed.
13919void Sema::ActOnFinishCXXMemberDecls() {
13920 // If the context is an invalid C++ class, just suppress these checks.
13921 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13922 if (Record->isInvalidDecl()) {
13923 DelayedOverridingExceptionSpecChecks.clear();
13924 DelayedEquivalentExceptionSpecChecks.clear();
13925 return;
13926 }
13927 checkForMultipleExportedDefaultConstructors(*this, Record);
13928 }
13929}
13930
13931void Sema::ActOnFinishCXXNonNestedClass() {
13932 referenceDLLExportedClassMethods();
13933
13934 if (!DelayedDllExportMemberFunctions.empty()) {
13935 SmallVector<CXXMethodDecl*, 4> WorkList;
13936 std::swap(DelayedDllExportMemberFunctions, WorkList);
13937 for (CXXMethodDecl *M : WorkList) {
13938 DefineDefaultedFunction(*this, M, M->getLocation());
13939
13940 // Pass the method to the consumer to get emitted. This is not necessary
13941 // for explicit instantiation definitions, as they will get emitted
13942 // anyway.
13943 if (M->getParent()->getTemplateSpecializationKind() !=
13944 TSK_ExplicitInstantiationDefinition)
13945 ActOnFinishInlineFunctionDef(M);
13946 }
13947 }
13948}
13949
13950void Sema::referenceDLLExportedClassMethods() {
13951 if (!DelayedDllExportClasses.empty()) {
13952 // Calling ReferenceDllExportedMembers might cause the current function to
13953 // be called again, so use a local copy of DelayedDllExportClasses.
13954 SmallVector<CXXRecordDecl *, 4> WorkList;
13955 std::swap(DelayedDllExportClasses, WorkList);
13956 for (CXXRecordDecl *Class : WorkList)
13957 ReferenceDllExportedMembers(*this, Class);
13958 }
13959}
13960
13961void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13962 assert(getLangOpts().CPlusPlus11 &&(static_cast <bool> (getLangOpts().CPlusPlus11 &&
"adjusting dtor exception specs was introduced in c++11") ? void
(0) : __assert_fail ("getLangOpts().CPlusPlus11 && \"adjusting dtor exception specs was introduced in c++11\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13963, __extension__ __PRETTY_FUNCTION__
))
13963 "adjusting dtor exception specs was introduced in c++11")(static_cast <bool> (getLangOpts().CPlusPlus11 &&
"adjusting dtor exception specs was introduced in c++11") ? void
(0) : __assert_fail ("getLangOpts().CPlusPlus11 && \"adjusting dtor exception specs was introduced in c++11\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 13963, __extension__ __PRETTY_FUNCTION__
))
;
13964
13965 if (Destructor->isDependentContext())
13966 return;
13967
13968 // C++11 [class.dtor]p3:
13969 // A declaration of a destructor that does not have an exception-
13970 // specification is implicitly considered to have the same exception-
13971 // specification as an implicit declaration.
13972 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13973 if (DtorType->hasExceptionSpec())
13974 return;
13975
13976 // Replace the destructor's type, building off the existing one. Fortunately,
13977 // the only thing of interest in the destructor type is its extended info.
13978 // The return and arguments are fixed.
13979 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13980 EPI.ExceptionSpec.Type = EST_Unevaluated;
13981 EPI.ExceptionSpec.SourceDecl = Destructor;
13982 Destructor->setType(
13983 Context.getFunctionType(Context.VoidTy, std::nullopt, EPI));
13984
13985 // FIXME: If the destructor has a body that could throw, and the newly created
13986 // spec doesn't allow exceptions, we should emit a warning, because this
13987 // change in behavior can break conforming C++03 programs at runtime.
13988 // However, we don't have a body or an exception specification yet, so it
13989 // needs to be done somewhere else.
13990}
13991
13992namespace {
13993/// An abstract base class for all helper classes used in building the
13994// copy/move operators. These classes serve as factory functions and help us
13995// avoid using the same Expr* in the AST twice.
13996class ExprBuilder {
13997 ExprBuilder(const ExprBuilder&) = delete;
13998 ExprBuilder &operator=(const ExprBuilder&) = delete;
13999
14000protected:
14001 static Expr *assertNotNull(Expr *E) {
14002 assert(E && "Expression construction must not fail.")(static_cast <bool> (E && "Expression construction must not fail."
) ? void (0) : __assert_fail ("E && \"Expression construction must not fail.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14002, __extension__ __PRETTY_FUNCTION__
))
;
14003 return E;
14004 }
14005
14006public:
14007 ExprBuilder() {}
14008 virtual ~ExprBuilder() {}
14009
14010 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14011};
14012
14013class RefBuilder: public ExprBuilder {
14014 VarDecl *Var;
14015 QualType VarType;
14016
14017public:
14018 Expr *build(Sema &S, SourceLocation Loc) const override {
14019 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
14020 }
14021
14022 RefBuilder(VarDecl *Var, QualType VarType)
14023 : Var(Var), VarType(VarType) {}
14024};
14025
14026class ThisBuilder: public ExprBuilder {
14027public:
14028 Expr *build(Sema &S, SourceLocation Loc) const override {
14029 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
14030 }
14031};
14032
14033class CastBuilder: public ExprBuilder {
14034 const ExprBuilder &Builder;
14035 QualType Type;
14036 ExprValueKind Kind;
14037 const CXXCastPath &Path;
14038
14039public:
14040 Expr *build(Sema &S, SourceLocation Loc) const override {
14041 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
14042 CK_UncheckedDerivedToBase, Kind,
14043 &Path).get());
14044 }
14045
14046 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14047 const CXXCastPath &Path)
14048 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14049};
14050
14051class DerefBuilder: public ExprBuilder {
14052 const ExprBuilder &Builder;
14053
14054public:
14055 Expr *build(Sema &S, SourceLocation Loc) const override {
14056 return assertNotNull(
14057 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
14058 }
14059
14060 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14061};
14062
14063class MemberBuilder: public ExprBuilder {
14064 const ExprBuilder &Builder;
14065 QualType Type;
14066 CXXScopeSpec SS;
14067 bool IsArrow;
14068 LookupResult &MemberLookup;
14069
14070public:
14071 Expr *build(Sema &S, SourceLocation Loc) const override {
14072 return assertNotNull(S.BuildMemberReferenceExpr(
14073 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14074 nullptr, MemberLookup, nullptr, nullptr).get());
14075 }
14076
14077 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14078 LookupResult &MemberLookup)
14079 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14080 MemberLookup(MemberLookup) {}
14081};
14082
14083class MoveCastBuilder: public ExprBuilder {
14084 const ExprBuilder &Builder;
14085
14086public:
14087 Expr *build(Sema &S, SourceLocation Loc) const override {
14088 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14089 }
14090
14091 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14092};
14093
14094class LvalueConvBuilder: public ExprBuilder {
14095 const ExprBuilder &Builder;
14096
14097public:
14098 Expr *build(Sema &S, SourceLocation Loc) const override {
14099 return assertNotNull(
14100 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14101 }
14102
14103 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14104};
14105
14106class SubscriptBuilder: public ExprBuilder {
14107 const ExprBuilder &Base;
14108 const ExprBuilder &Index;
14109
14110public:
14111 Expr *build(Sema &S, SourceLocation Loc) const override {
14112 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14113 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14114 }
14115
14116 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14117 : Base(Base), Index(Index) {}
14118};
14119
14120} // end anonymous namespace
14121
14122/// When generating a defaulted copy or move assignment operator, if a field
14123/// should be copied with __builtin_memcpy rather than via explicit assignments,
14124/// do so. This optimization only applies for arrays of scalars, and for arrays
14125/// of class type where the selected copy/move-assignment operator is trivial.
14126static StmtResult
14127buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14128 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14129 // Compute the size of the memory buffer to be copied.
14130 QualType SizeType = S.Context.getSizeType();
14131 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14132 S.Context.getTypeSizeInChars(T).getQuantity());
14133
14134 // Take the address of the field references for "from" and "to". We
14135 // directly construct UnaryOperators here because semantic analysis
14136 // does not permit us to take the address of an xvalue.
14137 Expr *From = FromB.build(S, Loc);
14138 From = UnaryOperator::Create(
14139 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14140 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14141 Expr *To = ToB.build(S, Loc);
14142 To = UnaryOperator::Create(
14143 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14144 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14145
14146 const Type *E = T->getBaseElementTypeUnsafe();
14147 bool NeedsCollectableMemCpy =
14148 E->isRecordType() &&
14149 E->castAs<RecordType>()->getDecl()->hasObjectMember();
14150
14151 // Create a reference to the __builtin_objc_memmove_collectable function
14152 StringRef MemCpyName = NeedsCollectableMemCpy ?
14153 "__builtin_objc_memmove_collectable" :
14154 "__builtin_memcpy";
14155 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14156 Sema::LookupOrdinaryName);
14157 S.LookupName(R, S.TUScope, true);
14158
14159 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14160 if (!MemCpy)
14161 // Something went horribly wrong earlier, and we will have complained
14162 // about it.
14163 return StmtError();
14164
14165 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14166 VK_PRValue, Loc, nullptr);
14167 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail")(static_cast <bool> (MemCpyRef.isUsable() && "Builtin reference cannot fail"
) ? void (0) : __assert_fail ("MemCpyRef.isUsable() && \"Builtin reference cannot fail\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14167, __extension__ __PRETTY_FUNCTION__
))
;
14168
14169 Expr *CallArgs[] = {
14170 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14171 };
14172 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14173 Loc, CallArgs, Loc);
14174
14175 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!")(static_cast <bool> (!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"
) ? void (0) : __assert_fail ("!Call.isInvalid() && \"Call to __builtin_memcpy cannot fail!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14175, __extension__ __PRETTY_FUNCTION__
))
;
14176 return Call.getAs<Stmt>();
14177}
14178
14179/// Builds a statement that copies/moves the given entity from \p From to
14180/// \c To.
14181///
14182/// This routine is used to copy/move the members of a class with an
14183/// implicitly-declared copy/move assignment operator. When the entities being
14184/// copied are arrays, this routine builds for loops to copy them.
14185///
14186/// \param S The Sema object used for type-checking.
14187///
14188/// \param Loc The location where the implicit copy/move is being generated.
14189///
14190/// \param T The type of the expressions being copied/moved. Both expressions
14191/// must have this type.
14192///
14193/// \param To The expression we are copying/moving to.
14194///
14195/// \param From The expression we are copying/moving from.
14196///
14197/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14198/// Otherwise, it's a non-static member subobject.
14199///
14200/// \param Copying Whether we're copying or moving.
14201///
14202/// \param Depth Internal parameter recording the depth of the recursion.
14203///
14204/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14205/// if a memcpy should be used instead.
14206static StmtResult
14207buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14208 const ExprBuilder &To, const ExprBuilder &From,
14209 bool CopyingBaseSubobject, bool Copying,
14210 unsigned Depth = 0) {
14211 // C++11 [class.copy]p28:
14212 // Each subobject is assigned in the manner appropriate to its type:
14213 //
14214 // - if the subobject is of class type, as if by a call to operator= with
14215 // the subobject as the object expression and the corresponding
14216 // subobject of x as a single function argument (as if by explicit
14217 // qualification; that is, ignoring any possible virtual overriding
14218 // functions in more derived classes);
14219 //
14220 // C++03 [class.copy]p13:
14221 // - if the subobject is of class type, the copy assignment operator for
14222 // the class is used (as if by explicit qualification; that is,
14223 // ignoring any possible virtual overriding functions in more derived
14224 // classes);
14225 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14226 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14227
14228 // Look for operator=.
14229 DeclarationName Name
14230 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14231 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14232 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14233
14234 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14235 // operator.
14236 if (!S.getLangOpts().CPlusPlus11) {
14237 LookupResult::Filter F = OpLookup.makeFilter();
14238 while (F.hasNext()) {
14239 NamedDecl *D = F.next();
14240 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14241 if (Method->isCopyAssignmentOperator() ||
14242 (!Copying && Method->isMoveAssignmentOperator()))
14243 continue;
14244
14245 F.erase();
14246 }
14247 F.done();
14248 }
14249
14250 // Suppress the protected check (C++ [class.protected]) for each of the
14251 // assignment operators we found. This strange dance is required when
14252 // we're assigning via a base classes's copy-assignment operator. To
14253 // ensure that we're getting the right base class subobject (without
14254 // ambiguities), we need to cast "this" to that subobject type; to
14255 // ensure that we don't go through the virtual call mechanism, we need
14256 // to qualify the operator= name with the base class (see below). However,
14257 // this means that if the base class has a protected copy assignment
14258 // operator, the protected member access check will fail. So, we
14259 // rewrite "protected" access to "public" access in this case, since we
14260 // know by construction that we're calling from a derived class.
14261 if (CopyingBaseSubobject) {
14262 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14263 L != LEnd; ++L) {
14264 if (L.getAccess() == AS_protected)
14265 L.setAccess(AS_public);
14266 }
14267 }
14268
14269 // Create the nested-name-specifier that will be used to qualify the
14270 // reference to operator=; this is required to suppress the virtual
14271 // call mechanism.
14272 CXXScopeSpec SS;
14273 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14274 SS.MakeTrivial(S.Context,
14275 NestedNameSpecifier::Create(S.Context, nullptr, false,
14276 CanonicalT),
14277 Loc);
14278
14279 // Create the reference to operator=.
14280 ExprResult OpEqualRef
14281 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14282 SS, /*TemplateKWLoc=*/SourceLocation(),
14283 /*FirstQualifierInScope=*/nullptr,
14284 OpLookup,
14285 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14286 /*SuppressQualifierCheck=*/true);
14287 if (OpEqualRef.isInvalid())
14288 return StmtError();
14289
14290 // Build the call to the assignment operator.
14291
14292 Expr *FromInst = From.build(S, Loc);
14293 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14294 OpEqualRef.getAs<Expr>(),
14295 Loc, FromInst, Loc);
14296 if (Call.isInvalid())
14297 return StmtError();
14298
14299 // If we built a call to a trivial 'operator=' while copying an array,
14300 // bail out. We'll replace the whole shebang with a memcpy.
14301 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14302 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14303 return StmtResult((Stmt*)nullptr);
14304
14305 // Convert to an expression-statement, and clean up any produced
14306 // temporaries.
14307 return S.ActOnExprStmt(Call);
14308 }
14309
14310 // - if the subobject is of scalar type, the built-in assignment
14311 // operator is used.
14312 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14313 if (!ArrayTy) {
14314 ExprResult Assignment = S.CreateBuiltinBinOp(
14315 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14316 if (Assignment.isInvalid())
14317 return StmtError();
14318 return S.ActOnExprStmt(Assignment);
14319 }
14320
14321 // - if the subobject is an array, each element is assigned, in the
14322 // manner appropriate to the element type;
14323
14324 // Construct a loop over the array bounds, e.g.,
14325 //
14326 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14327 //
14328 // that will copy each of the array elements.
14329 QualType SizeType = S.Context.getSizeType();
14330
14331 // Create the iteration variable.
14332 IdentifierInfo *IterationVarName = nullptr;
14333 {
14334 SmallString<8> Str;
14335 llvm::raw_svector_ostream OS(Str);
14336 OS << "__i" << Depth;
14337 IterationVarName = &S.Context.Idents.get(OS.str());
14338 }
14339 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14340 IterationVarName, SizeType,
14341 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14342 SC_None);
14343
14344 // Initialize the iteration variable to zero.
14345 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14346 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14347
14348 // Creates a reference to the iteration variable.
14349 RefBuilder IterationVarRef(IterationVar, SizeType);
14350 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14351
14352 // Create the DeclStmt that holds the iteration variable.
14353 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14354
14355 // Subscript the "from" and "to" expressions with the iteration variable.
14356 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14357 MoveCastBuilder FromIndexMove(FromIndexCopy);
14358 const ExprBuilder *FromIndex;
14359 if (Copying)
14360 FromIndex = &FromIndexCopy;
14361 else
14362 FromIndex = &FromIndexMove;
14363
14364 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14365
14366 // Build the copy/move for an individual element of the array.
14367 StmtResult Copy =
14368 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14369 ToIndex, *FromIndex, CopyingBaseSubobject,
14370 Copying, Depth + 1);
14371 // Bail out if copying fails or if we determined that we should use memcpy.
14372 if (Copy.isInvalid() || !Copy.get())
14373 return Copy;
14374
14375 // Create the comparison against the array bound.
14376 llvm::APInt Upper
14377 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14378 Expr *Comparison = BinaryOperator::Create(
14379 S.Context, IterationVarRefRVal.build(S, Loc),
14380 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14381 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14382 S.CurFPFeatureOverrides());
14383
14384 // Create the pre-increment of the iteration variable. We can determine
14385 // whether the increment will overflow based on the value of the array
14386 // bound.
14387 Expr *Increment = UnaryOperator::Create(
14388 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14389 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14390
14391 // Construct the loop that copies all elements of this array.
14392 return S.ActOnForStmt(
14393 Loc, Loc, InitStmt,
14394 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14395 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14396}
14397
14398static StmtResult
14399buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14400 const ExprBuilder &To, const ExprBuilder &From,
14401 bool CopyingBaseSubobject, bool Copying) {
14402 // Maybe we should use a memcpy?
14403 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14404 T.isTriviallyCopyableType(S.Context))
14405 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14406
14407 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14408 CopyingBaseSubobject,
14409 Copying, 0));
14410
14411 // If we ended up picking a trivial assignment operator for an array of a
14412 // non-trivially-copyable class type, just emit a memcpy.
14413 if (!Result.isInvalid() && !Result.get())
14414 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14415
14416 return Result;
14417}
14418
14419CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14420 // Note: The following rules are largely analoguous to the copy
14421 // constructor rules. Note that virtual bases are not taken into account
14422 // for determining the argument type of the operator. Note also that
14423 // operators taking an object instead of a reference are allowed.
14424 assert(ClassDecl->needsImplicitCopyAssignment())(static_cast <bool> (ClassDecl->needsImplicitCopyAssignment
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitCopyAssignment()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 14424, __extension__ __PRETTY_FUNCTION__
))
;
14425
14426 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14427 if (DSM.isAlreadyBeingDeclared())
14428 return nullptr;
14429
14430 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14431 LangAS AS = getDefaultCXXMethodAddrSpace();
14432 if (AS != LangAS::Default)
14433 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14434 QualType RetType = Context.getLValueReferenceType(ArgType);
14435 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14436 if (Const)
14437 ArgType = ArgType.withConst();
14438
14439 ArgType = Context.getLValueReferenceType(ArgType);
14440
14441 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14442 CXXCopyAssignment,
14443 Const);
14444
14445 // An implicitly-declared copy assignment operator is an inline public
14446 // member of its class.
14447 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14448 SourceLocation ClassLoc = ClassDecl->getLocation();
14449 DeclarationNameInfo NameInfo(Name, ClassLoc);
14450 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14451 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14452 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14453 getCurFPFeatures().isFPConstrained(),
14454 /*isInline=*/true,
14455 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14456 SourceLocation());
14457 CopyAssignment->setAccess(AS_public);
14458 CopyAssignment->setDefaulted();
14459 CopyAssignment->setImplicit();
14460
14461 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14462
14463 if (getLangOpts().CUDA)
14464 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14465 CopyAssignment,
14466 /* ConstRHS */ Const,
14467 /* Diagnose */ false);
14468
14469 // Add the parameter to the operator.
14470 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14471 ClassLoc, ClassLoc,
14472 /*Id=*/nullptr, ArgType,
14473 /*TInfo=*/nullptr, SC_None,
14474 nullptr);
14475 CopyAssignment->setParams(FromParam);
14476
14477 CopyAssignment->setTrivial(
14478 ClassDecl->needsOverloadResolutionForCopyAssignment()
14479 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14480 : ClassDecl->hasTrivialCopyAssignment());
14481
14482 // Note that we have added this copy-assignment operator.
14483 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14484
14485 Scope *S = getScopeForContext(ClassDecl);
14486 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14487
14488 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14489 ClassDecl->setImplicitCopyAssignmentIsDeleted();
14490 SetDeclDeleted(CopyAssignment, ClassLoc);
14491 }
14492
14493 if (S)
14494 PushOnScopeChains(CopyAssignment, S, false);
14495 ClassDecl->addDecl(CopyAssignment);
14496
14497 return CopyAssignment;
14498}
14499
14500/// Diagnose an implicit copy operation for a class which is odr-used, but
14501/// which is deprecated because the class has a user-declared copy constructor,
14502/// copy assignment operator, or destructor.
14503static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14504 assert(CopyOp->isImplicit())(static_cast <bool> (CopyOp->isImplicit()) ? void (0
) : __assert_fail ("CopyOp->isImplicit()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 14504, __extension__ __PRETTY_FUNCTION__))
;
14505
14506 CXXRecordDecl *RD = CopyOp->getParent();
14507 CXXMethodDecl *UserDeclaredOperation = nullptr;
14508
14509 if (RD->hasUserDeclaredDestructor()) {
14510 UserDeclaredOperation = RD->getDestructor();
14511 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14512 RD->hasUserDeclaredCopyConstructor()) {
14513 // Find any user-declared copy constructor.
14514 for (auto *I : RD->ctors()) {
14515 if (I->isCopyConstructor()) {
14516 UserDeclaredOperation = I;
14517 break;
14518 }
14519 }
14520 assert(UserDeclaredOperation)(static_cast <bool> (UserDeclaredOperation) ? void (0) :
__assert_fail ("UserDeclaredOperation", "clang/lib/Sema/SemaDeclCXX.cpp"
, 14520, __extension__ __PRETTY_FUNCTION__))
;
14521 } else if (isa<CXXConstructorDecl>(CopyOp) &&
14522 RD->hasUserDeclaredCopyAssignment()) {
14523 // Find any user-declared move assignment operator.
14524 for (auto *I : RD->methods()) {
14525 if (I->isCopyAssignmentOperator()) {
14526 UserDeclaredOperation = I;
14527 break;
14528 }
14529 }
14530 assert(UserDeclaredOperation)(static_cast <bool> (UserDeclaredOperation) ? void (0) :
__assert_fail ("UserDeclaredOperation", "clang/lib/Sema/SemaDeclCXX.cpp"
, 14530, __extension__ __PRETTY_FUNCTION__))
;
14531 }
14532
14533 if (UserDeclaredOperation) {
14534 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14535 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14536 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14537 unsigned DiagID =
14538 (UDOIsUserProvided && UDOIsDestructor)
14539 ? diag::warn_deprecated_copy_with_user_provided_dtor
14540 : (UDOIsUserProvided && !UDOIsDestructor)
14541 ? diag::warn_deprecated_copy_with_user_provided_copy
14542 : (!UDOIsUserProvided && UDOIsDestructor)
14543 ? diag::warn_deprecated_copy_with_dtor
14544 : diag::warn_deprecated_copy;
14545 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14546 << RD << IsCopyAssignment;
14547 }
14548}
14549
14550void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14551 CXXMethodDecl *CopyAssignOperator) {
14552 assert((CopyAssignOperator->isDefaulted() &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14557, __extension__ __PRETTY_FUNCTION__
))
14553 CopyAssignOperator->isOverloadedOperator() &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14557, __extension__ __PRETTY_FUNCTION__
))
14554 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14557, __extension__ __PRETTY_FUNCTION__
))
14555 !CopyAssignOperator->doesThisDeclarationHaveABody() &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14557, __extension__ __PRETTY_FUNCTION__
))
14556 !CopyAssignOperator->isDeleted()) &&(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14557, __extension__ __PRETTY_FUNCTION__
))
14557 "DefineImplicitCopyAssignment called for wrong function")(static_cast <bool> ((CopyAssignOperator->isDefaulted
() && CopyAssignOperator->isOverloadedOperator() &&
CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
!CopyAssignOperator->doesThisDeclarationHaveABody() &&
!CopyAssignOperator->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function"
) ? void (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14557, __extension__ __PRETTY_FUNCTION__
))
;
14558 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14559 return;
14560
14561 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14562 if (ClassDecl->isInvalidDecl()) {
14563 CopyAssignOperator->setInvalidDecl();
14564 return;
14565 }
14566
14567 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14568
14569 // The exception specification is needed because we are defining the
14570 // function.
14571 ResolveExceptionSpec(CurrentLocation,
14572 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14573
14574 // Add a context note for diagnostics produced after this point.
14575 Scope.addContextNote(CurrentLocation);
14576
14577 // C++11 [class.copy]p18:
14578 // The [definition of an implicitly declared copy assignment operator] is
14579 // deprecated if the class has a user-declared copy constructor or a
14580 // user-declared destructor.
14581 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14582 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14583
14584 // C++0x [class.copy]p30:
14585 // The implicitly-defined or explicitly-defaulted copy assignment operator
14586 // for a non-union class X performs memberwise copy assignment of its
14587 // subobjects. The direct base classes of X are assigned first, in the
14588 // order of their declaration in the base-specifier-list, and then the
14589 // immediate non-static data members of X are assigned, in the order in
14590 // which they were declared in the class definition.
14591
14592 // The statements that form the synthesized function body.
14593 SmallVector<Stmt*, 8> Statements;
14594
14595 // The parameter for the "other" object, which we are copying from.
14596 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14597 Qualifiers OtherQuals = Other->getType().getQualifiers();
14598 QualType OtherRefType = Other->getType();
14599 if (const LValueReferenceType *OtherRef
14600 = OtherRefType->getAs<LValueReferenceType>()) {
14601 OtherRefType = OtherRef->getPointeeType();
14602 OtherQuals = OtherRefType.getQualifiers();
14603 }
14604
14605 // Our location for everything implicitly-generated.
14606 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14607 ? CopyAssignOperator->getEndLoc()
14608 : CopyAssignOperator->getLocation();
14609
14610 // Builds a DeclRefExpr for the "other" object.
14611 RefBuilder OtherRef(Other, OtherRefType);
14612
14613 // Builds the "this" pointer.
14614 ThisBuilder This;
14615
14616 // Assign base classes.
14617 bool Invalid = false;
14618 for (auto &Base : ClassDecl->bases()) {
14619 // Form the assignment:
14620 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14621 QualType BaseType = Base.getType().getUnqualifiedType();
14622 if (!BaseType->isRecordType()) {
14623 Invalid = true;
14624 continue;
14625 }
14626
14627 CXXCastPath BasePath;
14628 BasePath.push_back(&Base);
14629
14630 // Construct the "from" expression, which is an implicit cast to the
14631 // appropriately-qualified base type.
14632 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14633 VK_LValue, BasePath);
14634
14635 // Dereference "this".
14636 DerefBuilder DerefThis(This);
14637 CastBuilder To(DerefThis,
14638 Context.getQualifiedType(
14639 BaseType, CopyAssignOperator->getMethodQualifiers()),
14640 VK_LValue, BasePath);
14641
14642 // Build the copy.
14643 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14644 To, From,
14645 /*CopyingBaseSubobject=*/true,
14646 /*Copying=*/true);
14647 if (Copy.isInvalid()) {
14648 CopyAssignOperator->setInvalidDecl();
14649 return;
14650 }
14651
14652 // Success! Record the copy.
14653 Statements.push_back(Copy.getAs<Expr>());
14654 }
14655
14656 // Assign non-static members.
14657 for (auto *Field : ClassDecl->fields()) {
14658 // FIXME: We should form some kind of AST representation for the implied
14659 // memcpy in a union copy operation.
14660 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14661 continue;
14662
14663 if (Field->isInvalidDecl()) {
14664 Invalid = true;
14665 continue;
14666 }
14667
14668 // Check for members of reference type; we can't copy those.
14669 if (Field->getType()->isReferenceType()) {
14670 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14671 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14672 Diag(Field->getLocation(), diag::note_declared_at);
14673 Invalid = true;
14674 continue;
14675 }
14676
14677 // Check for members of const-qualified, non-class type.
14678 QualType BaseType = Context.getBaseElementType(Field->getType());
14679 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14680 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14681 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14682 Diag(Field->getLocation(), diag::note_declared_at);
14683 Invalid = true;
14684 continue;
14685 }
14686
14687 // Suppress assigning zero-width bitfields.
14688 if (Field->isZeroLengthBitField(Context))
14689 continue;
14690
14691 QualType FieldType = Field->getType().getNonReferenceType();
14692 if (FieldType->isIncompleteArrayType()) {
14693 assert(ClassDecl->hasFlexibleArrayMember() &&(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14694, __extension__ __PRETTY_FUNCTION__
))
14694 "Incomplete array type is not valid")(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14694, __extension__ __PRETTY_FUNCTION__
))
;
14695 continue;
14696 }
14697
14698 // Build references to the field in the object we're copying from and to.
14699 CXXScopeSpec SS; // Intentionally empty
14700 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14701 LookupMemberName);
14702 MemberLookup.addDecl(Field);
14703 MemberLookup.resolveKind();
14704
14705 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14706
14707 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/!LangOpts.HLSL,
14708 MemberLookup);
14709
14710 // Build the copy of this field.
14711 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14712 To, From,
14713 /*CopyingBaseSubobject=*/false,
14714 /*Copying=*/true);
14715 if (Copy.isInvalid()) {
14716 CopyAssignOperator->setInvalidDecl();
14717 return;
14718 }
14719
14720 // Success! Record the copy.
14721 Statements.push_back(Copy.getAs<Stmt>());
14722 }
14723
14724 if (!Invalid) {
14725 // Add a "return *this;"
14726 Expr *ThisExpr = nullptr;
14727 if (!LangOpts.HLSL) {
14728 ExprResult ThisObj =
14729 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14730 ThisExpr = ThisObj.get();
14731 } else {
14732 ThisExpr = This.build(*this, Loc);
14733 }
14734
14735 StmtResult Return = BuildReturnStmt(Loc, ThisExpr);
14736 if (Return.isInvalid())
14737 Invalid = true;
14738 else
14739 Statements.push_back(Return.getAs<Stmt>());
14740 }
14741
14742 if (Invalid) {
14743 CopyAssignOperator->setInvalidDecl();
14744 return;
14745 }
14746
14747 StmtResult Body;
14748 {
14749 CompoundScopeRAII CompoundScope(*this);
14750 Body = ActOnCompoundStmt(Loc, Loc, Statements,
14751 /*isStmtExpr=*/false);
14752 assert(!Body.isInvalid() && "Compound statement creation cannot fail")(static_cast <bool> (!Body.isInvalid() && "Compound statement creation cannot fail"
) ? void (0) : __assert_fail ("!Body.isInvalid() && \"Compound statement creation cannot fail\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14752, __extension__ __PRETTY_FUNCTION__
))
;
14753 }
14754 CopyAssignOperator->setBody(Body.getAs<Stmt>());
14755 CopyAssignOperator->markUsed(Context);
14756
14757 if (ASTMutationListener *L = getASTMutationListener()) {
14758 L->CompletedImplicitDefinition(CopyAssignOperator);
14759 }
14760}
14761
14762CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14763 assert(ClassDecl->needsImplicitMoveAssignment())(static_cast <bool> (ClassDecl->needsImplicitMoveAssignment
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitMoveAssignment()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 14763, __extension__ __PRETTY_FUNCTION__
))
;
14764
14765 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14766 if (DSM.isAlreadyBeingDeclared())
14767 return nullptr;
14768
14769 // Note: The following rules are largely analoguous to the move
14770 // constructor rules.
14771
14772 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14773 LangAS AS = getDefaultCXXMethodAddrSpace();
14774 if (AS != LangAS::Default)
14775 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14776 QualType RetType = Context.getLValueReferenceType(ArgType);
14777 ArgType = Context.getRValueReferenceType(ArgType);
14778
14779 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14780 CXXMoveAssignment,
14781 false);
14782
14783 // An implicitly-declared move assignment operator is an inline public
14784 // member of its class.
14785 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14786 SourceLocation ClassLoc = ClassDecl->getLocation();
14787 DeclarationNameInfo NameInfo(Name, ClassLoc);
14788 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14789 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14790 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14791 getCurFPFeatures().isFPConstrained(),
14792 /*isInline=*/true,
14793 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14794 SourceLocation());
14795 MoveAssignment->setAccess(AS_public);
14796 MoveAssignment->setDefaulted();
14797 MoveAssignment->setImplicit();
14798
14799 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14800
14801 if (getLangOpts().CUDA)
14802 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14803 MoveAssignment,
14804 /* ConstRHS */ false,
14805 /* Diagnose */ false);
14806
14807 // Add the parameter to the operator.
14808 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14809 ClassLoc, ClassLoc,
14810 /*Id=*/nullptr, ArgType,
14811 /*TInfo=*/nullptr, SC_None,
14812 nullptr);
14813 MoveAssignment->setParams(FromParam);
14814
14815 MoveAssignment->setTrivial(
14816 ClassDecl->needsOverloadResolutionForMoveAssignment()
14817 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14818 : ClassDecl->hasTrivialMoveAssignment());
14819
14820 // Note that we have added this copy-assignment operator.
14821 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14822
14823 Scope *S = getScopeForContext(ClassDecl);
14824 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14825
14826 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14827 ClassDecl->setImplicitMoveAssignmentIsDeleted();
14828 SetDeclDeleted(MoveAssignment, ClassLoc);
14829 }
14830
14831 if (S)
14832 PushOnScopeChains(MoveAssignment, S, false);
14833 ClassDecl->addDecl(MoveAssignment);
14834
14835 return MoveAssignment;
14836}
14837
14838/// Check if we're implicitly defining a move assignment operator for a class
14839/// with virtual bases. Such a move assignment might move-assign the virtual
14840/// base multiple times.
14841static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14842 SourceLocation CurrentLocation) {
14843 assert(!Class->isDependentContext() && "should not define dependent move")(static_cast <bool> (!Class->isDependentContext() &&
"should not define dependent move") ? void (0) : __assert_fail
("!Class->isDependentContext() && \"should not define dependent move\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14843, __extension__ __PRETTY_FUNCTION__
))
;
14844
14845 // Only a virtual base could get implicitly move-assigned multiple times.
14846 // Only a non-trivial move assignment can observe this. We only want to
14847 // diagnose if we implicitly define an assignment operator that assigns
14848 // two base classes, both of which move-assign the same virtual base.
14849 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14850 Class->getNumBases() < 2)
14851 return;
14852
14853 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14854 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14855 VBaseMap VBases;
14856
14857 for (auto &BI : Class->bases()) {
14858 Worklist.push_back(&BI);
14859 while (!Worklist.empty()) {
14860 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14861 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14862
14863 // If the base has no non-trivial move assignment operators,
14864 // we don't care about moves from it.
14865 if (!Base->hasNonTrivialMoveAssignment())
14866 continue;
14867
14868 // If there's nothing virtual here, skip it.
14869 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14870 continue;
14871
14872 // If we're not actually going to call a move assignment for this base,
14873 // or the selected move assignment is trivial, skip it.
14874 Sema::SpecialMemberOverloadResult SMOR =
14875 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14876 /*ConstArg*/false, /*VolatileArg*/false,
14877 /*RValueThis*/true, /*ConstThis*/false,
14878 /*VolatileThis*/false);
14879 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14880 !SMOR.getMethod()->isMoveAssignmentOperator())
14881 continue;
14882
14883 if (BaseSpec->isVirtual()) {
14884 // We're going to move-assign this virtual base, and its move
14885 // assignment operator is not trivial. If this can happen for
14886 // multiple distinct direct bases of Class, diagnose it. (If it
14887 // only happens in one base, we'll diagnose it when synthesizing
14888 // that base class's move assignment operator.)
14889 CXXBaseSpecifier *&Existing =
14890 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14891 .first->second;
14892 if (Existing && Existing != &BI) {
14893 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14894 << Class << Base;
14895 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14896 << (Base->getCanonicalDecl() ==
14897 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14898 << Base << Existing->getType() << Existing->getSourceRange();
14899 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14900 << (Base->getCanonicalDecl() ==
14901 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14902 << Base << BI.getType() << BaseSpec->getSourceRange();
14903
14904 // Only diagnose each vbase once.
14905 Existing = nullptr;
14906 }
14907 } else {
14908 // Only walk over bases that have defaulted move assignment operators.
14909 // We assume that any user-provided move assignment operator handles
14910 // the multiple-moves-of-vbase case itself somehow.
14911 if (!SMOR.getMethod()->isDefaulted())
14912 continue;
14913
14914 // We're going to move the base classes of Base. Add them to the list.
14915 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
14916 }
14917 }
14918 }
14919}
14920
14921void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14922 CXXMethodDecl *MoveAssignOperator) {
14923 assert((MoveAssignOperator->isDefaulted() &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14928, __extension__ __PRETTY_FUNCTION__
))
14924 MoveAssignOperator->isOverloadedOperator() &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14928, __extension__ __PRETTY_FUNCTION__
))
14925 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14928, __extension__ __PRETTY_FUNCTION__
))
14926 !MoveAssignOperator->doesThisDeclarationHaveABody() &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14928, __extension__ __PRETTY_FUNCTION__
))
14927 !MoveAssignOperator->isDeleted()) &&(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14928, __extension__ __PRETTY_FUNCTION__
))
14928 "DefineImplicitMoveAssignment called for wrong function")(static_cast <bool> ((MoveAssignOperator->isDefaulted
() && MoveAssignOperator->isOverloadedOperator() &&
MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
!MoveAssignOperator->doesThisDeclarationHaveABody() &&
!MoveAssignOperator->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function"
) ? void (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 14928, __extension__ __PRETTY_FUNCTION__
))
;
14929 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14930 return;
14931
14932 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14933 if (ClassDecl->isInvalidDecl()) {
14934 MoveAssignOperator->setInvalidDecl();
14935 return;
14936 }
14937
14938 // C++0x [class.copy]p28:
14939 // The implicitly-defined or move assignment operator for a non-union class
14940 // X performs memberwise move assignment of its subobjects. The direct base
14941 // classes of X are assigned first, in the order of their declaration in the
14942 // base-specifier-list, and then the immediate non-static data members of X
14943 // are assigned, in the order in which they were declared in the class
14944 // definition.
14945
14946 // Issue a warning if our implicit move assignment operator will move
14947 // from a virtual base more than once.
14948 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14949
14950 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14951
14952 // The exception specification is needed because we are defining the
14953 // function.
14954 ResolveExceptionSpec(CurrentLocation,
14955 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14956
14957 // Add a context note for diagnostics produced after this point.
14958 Scope.addContextNote(CurrentLocation);
14959
14960 // The statements that form the synthesized function body.
14961 SmallVector<Stmt*, 8> Statements;
14962
14963 // The parameter for the "other" object, which we are move from.
14964 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14965 QualType OtherRefType =
14966 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14967
14968 // Our location for everything implicitly-generated.
14969 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14970 ? MoveAssignOperator->getEndLoc()
14971 : MoveAssignOperator->getLocation();
14972
14973 // Builds a reference to the "other" object.
14974 RefBuilder OtherRef(Other, OtherRefType);
14975 // Cast to rvalue.
14976 MoveCastBuilder MoveOther(OtherRef);
14977
14978 // Builds the "this" pointer.
14979 ThisBuilder This;
14980
14981 // Assign base classes.
14982 bool Invalid = false;
14983 for (auto &Base : ClassDecl->bases()) {
14984 // C++11 [class.copy]p28:
14985 // It is unspecified whether subobjects representing virtual base classes
14986 // are assigned more than once by the implicitly-defined copy assignment
14987 // operator.
14988 // FIXME: Do not assign to a vbase that will be assigned by some other base
14989 // class. For a move-assignment, this can result in the vbase being moved
14990 // multiple times.
14991
14992 // Form the assignment:
14993 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14994 QualType BaseType = Base.getType().getUnqualifiedType();
14995 if (!BaseType->isRecordType()) {
14996 Invalid = true;
14997 continue;
14998 }
14999
15000 CXXCastPath BasePath;
15001 BasePath.push_back(&Base);
15002
15003 // Construct the "from" expression, which is an implicit cast to the
15004 // appropriately-qualified base type.
15005 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15006
15007 // Dereference "this".
15008 DerefBuilder DerefThis(This);
15009
15010 // Implicitly cast "this" to the appropriately-qualified base type.
15011 CastBuilder To(DerefThis,
15012 Context.getQualifiedType(
15013 BaseType, MoveAssignOperator->getMethodQualifiers()),
15014 VK_LValue, BasePath);
15015
15016 // Build the move.
15017 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
15018 To, From,
15019 /*CopyingBaseSubobject=*/true,
15020 /*Copying=*/false);
15021 if (Move.isInvalid()) {
15022 MoveAssignOperator->setInvalidDecl();
15023 return;
15024 }
15025
15026 // Success! Record the move.
15027 Statements.push_back(Move.getAs<Expr>());
15028 }
15029
15030 // Assign non-static members.
15031 for (auto *Field : ClassDecl->fields()) {
15032 // FIXME: We should form some kind of AST representation for the implied
15033 // memcpy in a union copy operation.
15034 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
15035 continue;
15036
15037 if (Field->isInvalidDecl()) {
15038 Invalid = true;
15039 continue;
15040 }
15041
15042 // Check for members of reference type; we can't move those.
15043 if (Field->getType()->isReferenceType()) {
15044 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15045 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
15046 Diag(Field->getLocation(), diag::note_declared_at);
15047 Invalid = true;
15048 continue;
15049 }
15050
15051 // Check for members of const-qualified, non-class type.
15052 QualType BaseType = Context.getBaseElementType(Field->getType());
15053 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
15054 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
15055 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
15056 Diag(Field->getLocation(), diag::note_declared_at);
15057 Invalid = true;
15058 continue;
15059 }
15060
15061 // Suppress assigning zero-width bitfields.
15062 if (Field->isZeroLengthBitField(Context))
15063 continue;
15064
15065 QualType FieldType = Field->getType().getNonReferenceType();
15066 if (FieldType->isIncompleteArrayType()) {
15067 assert(ClassDecl->hasFlexibleArrayMember() &&(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15068, __extension__ __PRETTY_FUNCTION__
))
15068 "Incomplete array type is not valid")(static_cast <bool> (ClassDecl->hasFlexibleArrayMember
() && "Incomplete array type is not valid") ? void (0
) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15068, __extension__ __PRETTY_FUNCTION__
))
;
15069 continue;
15070 }
15071
15072 // Build references to the field in the object we're copying from and to.
15073 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15074 LookupMemberName);
15075 MemberLookup.addDecl(Field);
15076 MemberLookup.resolveKind();
15077 MemberBuilder From(MoveOther, OtherRefType,
15078 /*IsArrow=*/false, MemberLookup);
15079 MemberBuilder To(This, getCurrentThisType(),
15080 /*IsArrow=*/true, MemberLookup);
15081
15082 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue(static_cast <bool> (!From.build(*this, Loc)->isLValue
() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? void
(0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15084, __extension__ __PRETTY_FUNCTION__
))
15083 "Member reference with rvalue base must be rvalue except for reference "(static_cast <bool> (!From.build(*this, Loc)->isLValue
() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? void
(0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15084, __extension__ __PRETTY_FUNCTION__
))
15084 "members, which aren't allowed for move assignment.")(static_cast <bool> (!From.build(*this, Loc)->isLValue
() && "Member reference with rvalue base must be rvalue except for reference "
"members, which aren't allowed for move assignment.") ? void
(0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15084, __extension__ __PRETTY_FUNCTION__
))
;
15085
15086 // Build the move of this field.
15087 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15088 To, From,
15089 /*CopyingBaseSubobject=*/false,
15090 /*Copying=*/false);
15091 if (Move.isInvalid()) {
15092 MoveAssignOperator->setInvalidDecl();
15093 return;
15094 }
15095
15096 // Success! Record the copy.
15097 Statements.push_back(Move.getAs<Stmt>());
15098 }
15099
15100 if (!Invalid) {
15101 // Add a "return *this;"
15102 ExprResult ThisObj =
15103 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
15104
15105 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
15106 if (Return.isInvalid())
15107 Invalid = true;
15108 else
15109 Statements.push_back(Return.getAs<Stmt>());
15110 }
15111
15112 if (Invalid) {
15113 MoveAssignOperator->setInvalidDecl();
15114 return;
15115 }
15116
15117 StmtResult Body;
15118 {
15119 CompoundScopeRAII CompoundScope(*this);
15120 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15121 /*isStmtExpr=*/false);
15122 assert(!Body.isInvalid() && "Compound statement creation cannot fail")(static_cast <bool> (!Body.isInvalid() && "Compound statement creation cannot fail"
) ? void (0) : __assert_fail ("!Body.isInvalid() && \"Compound statement creation cannot fail\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15122, __extension__ __PRETTY_FUNCTION__
))
;
15123 }
15124 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15125 MoveAssignOperator->markUsed(Context);
15126
15127 if (ASTMutationListener *L = getASTMutationListener()) {
15128 L->CompletedImplicitDefinition(MoveAssignOperator);
15129 }
15130}
15131
15132CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15133 CXXRecordDecl *ClassDecl) {
15134 // C++ [class.copy]p4:
15135 // If the class definition does not explicitly declare a copy
15136 // constructor, one is declared implicitly.
15137 assert(ClassDecl->needsImplicitCopyConstructor())(static_cast <bool> (ClassDecl->needsImplicitCopyConstructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitCopyConstructor()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15137, __extension__ __PRETTY_FUNCTION__
))
;
15138
15139 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15140 if (DSM.isAlreadyBeingDeclared())
15141 return nullptr;
15142
15143 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15144 QualType ArgType = ClassType;
15145 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15146 if (Const)
15147 ArgType = ArgType.withConst();
15148
15149 LangAS AS = getDefaultCXXMethodAddrSpace();
15150 if (AS != LangAS::Default)
15151 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15152
15153 ArgType = Context.getLValueReferenceType(ArgType);
15154
15155 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15156 CXXCopyConstructor,
15157 Const);
15158
15159 DeclarationName Name
15160 = Context.DeclarationNames.getCXXConstructorName(
15161 Context.getCanonicalType(ClassType));
15162 SourceLocation ClassLoc = ClassDecl->getLocation();
15163 DeclarationNameInfo NameInfo(Name, ClassLoc);
15164
15165 // An implicitly-declared copy constructor is an inline public
15166 // member of its class.
15167 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15168 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15169 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15170 /*isInline=*/true,
15171 /*isImplicitlyDeclared=*/true,
15172 Constexpr ? ConstexprSpecKind::Constexpr
15173 : ConstexprSpecKind::Unspecified);
15174 CopyConstructor->setAccess(AS_public);
15175 CopyConstructor->setDefaulted();
15176
15177 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15178
15179 if (getLangOpts().CUDA)
15180 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15181 CopyConstructor,
15182 /* ConstRHS */ Const,
15183 /* Diagnose */ false);
15184
15185 // During template instantiation of special member functions we need a
15186 // reliable TypeSourceInfo for the parameter types in order to allow functions
15187 // to be substituted.
15188 TypeSourceInfo *TSI = nullptr;
15189 if (inTemplateInstantiation() && ClassDecl->isLambda())
15190 TSI = Context.getTrivialTypeSourceInfo(ArgType);
15191
15192 // Add the parameter to the constructor.
15193 ParmVarDecl *FromParam =
15194 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15195 /*IdentifierInfo=*/nullptr, ArgType,
15196 /*TInfo=*/TSI, SC_None, nullptr);
15197 CopyConstructor->setParams(FromParam);
15198
15199 CopyConstructor->setTrivial(
15200 ClassDecl->needsOverloadResolutionForCopyConstructor()
15201 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15202 : ClassDecl->hasTrivialCopyConstructor());
15203
15204 CopyConstructor->setTrivialForCall(
15205 ClassDecl->hasAttr<TrivialABIAttr>() ||
15206 (ClassDecl->needsOverloadResolutionForCopyConstructor()
15207 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15208 TAH_ConsiderTrivialABI)
15209 : ClassDecl->hasTrivialCopyConstructorForCall()));
15210
15211 // Note that we have declared this constructor.
15212 ++getASTContext().NumImplicitCopyConstructorsDeclared;
15213
15214 Scope *S = getScopeForContext(ClassDecl);
15215 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15216
15217 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15218 ClassDecl->setImplicitCopyConstructorIsDeleted();
15219 SetDeclDeleted(CopyConstructor, ClassLoc);
15220 }
15221
15222 if (S)
15223 PushOnScopeChains(CopyConstructor, S, false);
15224 ClassDecl->addDecl(CopyConstructor);
15225
15226 return CopyConstructor;
15227}
15228
15229void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15230 CXXConstructorDecl *CopyConstructor) {
15231 assert((CopyConstructor->isDefaulted() &&(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15235, __extension__ __PRETTY_FUNCTION__
))
15232 CopyConstructor->isCopyConstructor() &&(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15235, __extension__ __PRETTY_FUNCTION__
))
15233 !CopyConstructor->doesThisDeclarationHaveABody() &&(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15235, __extension__ __PRETTY_FUNCTION__
))
15234 !CopyConstructor->isDeleted()) &&(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15235, __extension__ __PRETTY_FUNCTION__
))
15235 "DefineImplicitCopyConstructor - call it for implicit copy ctor")(static_cast <bool> ((CopyConstructor->isDefaulted()
&& CopyConstructor->isCopyConstructor() &&
!CopyConstructor->doesThisDeclarationHaveABody() &&
!CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor"
) ? void (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15235, __extension__ __PRETTY_FUNCTION__
))
;
15236 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15237 return;
15238
15239 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15240 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor")(static_cast <bool> (ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"
) ? void (0) : __assert_fail ("ClassDecl && \"DefineImplicitCopyConstructor - invalid constructor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15240, __extension__ __PRETTY_FUNCTION__
))
;
15241
15242 SynthesizedFunctionScope Scope(*this, CopyConstructor);
15243
15244 // The exception specification is needed because we are defining the
15245 // function.
15246 ResolveExceptionSpec(CurrentLocation,
15247 CopyConstructor->getType()->castAs<FunctionProtoType>());
15248 MarkVTableUsed(CurrentLocation, ClassDecl);
15249
15250 // Add a context note for diagnostics produced after this point.
15251 Scope.addContextNote(CurrentLocation);
15252
15253 // C++11 [class.copy]p7:
15254 // The [definition of an implicitly declared copy constructor] is
15255 // deprecated if the class has a user-declared copy assignment operator
15256 // or a user-declared destructor.
15257 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15258 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15259
15260 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15261 CopyConstructor->setInvalidDecl();
15262 } else {
15263 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15264 ? CopyConstructor->getEndLoc()
15265 : CopyConstructor->getLocation();
15266 Sema::CompoundScopeRAII CompoundScope(*this);
15267 CopyConstructor->setBody(
15268 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15269 .getAs<Stmt>());
15270 CopyConstructor->markUsed(Context);
15271 }
15272
15273 if (ASTMutationListener *L = getASTMutationListener()) {
15274 L->CompletedImplicitDefinition(CopyConstructor);
15275 }
15276}
15277
15278CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15279 CXXRecordDecl *ClassDecl) {
15280 assert(ClassDecl->needsImplicitMoveConstructor())(static_cast <bool> (ClassDecl->needsImplicitMoveConstructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitMoveConstructor()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15280, __extension__ __PRETTY_FUNCTION__
))
;
15281
15282 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15283 if (DSM.isAlreadyBeingDeclared())
15284 return nullptr;
15285
15286 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15287
15288 QualType ArgType = ClassType;
15289 LangAS AS = getDefaultCXXMethodAddrSpace();
15290 if (AS != LangAS::Default)
15291 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15292 ArgType = Context.getRValueReferenceType(ArgType);
15293
15294 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15295 CXXMoveConstructor,
15296 false);
15297
15298 DeclarationName Name
15299 = Context.DeclarationNames.getCXXConstructorName(
15300 Context.getCanonicalType(ClassType));
15301 SourceLocation ClassLoc = ClassDecl->getLocation();
15302 DeclarationNameInfo NameInfo(Name, ClassLoc);
15303
15304 // C++11 [class.copy]p11:
15305 // An implicitly-declared copy/move constructor is an inline public
15306 // member of its class.
15307 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15308 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15309 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15310 /*isInline=*/true,
15311 /*isImplicitlyDeclared=*/true,
15312 Constexpr ? ConstexprSpecKind::Constexpr
15313 : ConstexprSpecKind::Unspecified);
15314 MoveConstructor->setAccess(AS_public);
15315 MoveConstructor->setDefaulted();
15316
15317 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15318
15319 if (getLangOpts().CUDA)
15320 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15321 MoveConstructor,
15322 /* ConstRHS */ false,
15323 /* Diagnose */ false);
15324
15325 // Add the parameter to the constructor.
15326 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15327 ClassLoc, ClassLoc,
15328 /*IdentifierInfo=*/nullptr,
15329 ArgType, /*TInfo=*/nullptr,
15330 SC_None, nullptr);
15331 MoveConstructor->setParams(FromParam);
15332
15333 MoveConstructor->setTrivial(
15334 ClassDecl->needsOverloadResolutionForMoveConstructor()
15335 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15336 : ClassDecl->hasTrivialMoveConstructor());
15337
15338 MoveConstructor->setTrivialForCall(
15339 ClassDecl->hasAttr<TrivialABIAttr>() ||
15340 (ClassDecl->needsOverloadResolutionForMoveConstructor()
15341 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15342 TAH_ConsiderTrivialABI)
15343 : ClassDecl->hasTrivialMoveConstructorForCall()));
15344
15345 // Note that we have declared this constructor.
15346 ++getASTContext().NumImplicitMoveConstructorsDeclared;
15347
15348 Scope *S = getScopeForContext(ClassDecl);
15349 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15350
15351 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15352 ClassDecl->setImplicitMoveConstructorIsDeleted();
15353 SetDeclDeleted(MoveConstructor, ClassLoc);
15354 }
15355
15356 if (S)
15357 PushOnScopeChains(MoveConstructor, S, false);
15358 ClassDecl->addDecl(MoveConstructor);
15359
15360 return MoveConstructor;
15361}
15362
15363void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15364 CXXConstructorDecl *MoveConstructor) {
15365 assert((MoveConstructor->isDefaulted() &&(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15369, __extension__ __PRETTY_FUNCTION__
))
15366 MoveConstructor->isMoveConstructor() &&(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15369, __extension__ __PRETTY_FUNCTION__
))
15367 !MoveConstructor->doesThisDeclarationHaveABody() &&(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15369, __extension__ __PRETTY_FUNCTION__
))
15368 !MoveConstructor->isDeleted()) &&(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15369, __extension__ __PRETTY_FUNCTION__
))
15369 "DefineImplicitMoveConstructor - call it for implicit move ctor")(static_cast <bool> ((MoveConstructor->isDefaulted()
&& MoveConstructor->isMoveConstructor() &&
!MoveConstructor->doesThisDeclarationHaveABody() &&
!MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor"
) ? void (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15369, __extension__ __PRETTY_FUNCTION__
))
;
15370 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15371 return;
15372
15373 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15374 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor")(static_cast <bool> (ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"
) ? void (0) : __assert_fail ("ClassDecl && \"DefineImplicitMoveConstructor - invalid constructor\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15374, __extension__ __PRETTY_FUNCTION__
))
;
15375
15376 SynthesizedFunctionScope Scope(*this, MoveConstructor);
15377
15378 // The exception specification is needed because we are defining the
15379 // function.
15380 ResolveExceptionSpec(CurrentLocation,
15381 MoveConstructor->getType()->castAs<FunctionProtoType>());
15382 MarkVTableUsed(CurrentLocation, ClassDecl);
15383
15384 // Add a context note for diagnostics produced after this point.
15385 Scope.addContextNote(CurrentLocation);
15386
15387 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15388 MoveConstructor->setInvalidDecl();
15389 } else {
15390 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15391 ? MoveConstructor->getEndLoc()
15392 : MoveConstructor->getLocation();
15393 Sema::CompoundScopeRAII CompoundScope(*this);
15394 MoveConstructor->setBody(
15395 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false)
15396 .getAs<Stmt>());
15397 MoveConstructor->markUsed(Context);
15398 }
15399
15400 if (ASTMutationListener *L = getASTMutationListener()) {
15401 L->CompletedImplicitDefinition(MoveConstructor);
15402 }
15403}
15404
15405bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15406 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15407}
15408
15409void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15410 SourceLocation CurrentLocation,
15411 CXXConversionDecl *Conv) {
15412 SynthesizedFunctionScope Scope(*this, Conv);
15413 assert(!Conv->getReturnType()->isUndeducedType())(static_cast <bool> (!Conv->getReturnType()->isUndeducedType
()) ? void (0) : __assert_fail ("!Conv->getReturnType()->isUndeducedType()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15413, __extension__ __PRETTY_FUNCTION__
))
;
15414
15415 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15416 CallingConv CC =
15417 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15418
15419 CXXRecordDecl *Lambda = Conv->getParent();
15420 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15421 FunctionDecl *Invoker =
15422 CallOp->isStatic() ? CallOp : Lambda->getLambdaStaticInvoker(CC);
15423
15424 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15425 CallOp = InstantiateFunctionDeclaration(
15426 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15427 if (!CallOp)
15428 return;
15429
15430 if (CallOp != Invoker) {
15431 Invoker = InstantiateFunctionDeclaration(
15432 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
15433 CurrentLocation);
15434 if (!Invoker)
15435 return;
15436 }
15437 }
15438
15439 if (CallOp->isInvalidDecl())
15440 return;
15441
15442 // Mark the call operator referenced (and add to pending instantiations
15443 // if necessary).
15444 // For both the conversion and static-invoker template specializations
15445 // we construct their body's in this function, so no need to add them
15446 // to the PendingInstantiations.
15447 MarkFunctionReferenced(CurrentLocation, CallOp);
15448
15449 if (Invoker != CallOp) {
15450 // Fill in the __invoke function with a dummy implementation. IR generation
15451 // will fill in the actual details. Update its type in case it contained
15452 // an 'auto'.
15453 Invoker->markUsed(Context);
15454 Invoker->setReferenced();
15455 Invoker->setType(Conv->getReturnType()->getPointeeType());
15456 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15457 }
15458
15459 // Construct the body of the conversion function { return __invoke; }.
15460 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
15461 Conv->getLocation());
15462 assert(FunctionRef && "Can't refer to __invoke function?")(static_cast <bool> (FunctionRef && "Can't refer to __invoke function?"
) ? void (0) : __assert_fail ("FunctionRef && \"Can't refer to __invoke function?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15462, __extension__ __PRETTY_FUNCTION__
))
;
15463 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15464 Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(),
15465 Conv->getLocation(), Conv->getLocation()));
15466 Conv->markUsed(Context);
15467 Conv->setReferenced();
15468
15469 if (ASTMutationListener *L = getASTMutationListener()) {
15470 L->CompletedImplicitDefinition(Conv);
15471 if (Invoker != CallOp)
15472 L->CompletedImplicitDefinition(Invoker);
15473 }
15474}
15475
15476void Sema::DefineImplicitLambdaToBlockPointerConversion(
15477 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
15478 assert(!Conv->getParent()->isGenericLambda())(static_cast <bool> (!Conv->getParent()->isGenericLambda
()) ? void (0) : __assert_fail ("!Conv->getParent()->isGenericLambda()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15478, __extension__ __PRETTY_FUNCTION__
))
;
15479
15480 SynthesizedFunctionScope Scope(*this, Conv);
15481
15482 // Copy-initialize the lambda object as needed to capture it.
15483 Expr *This = ActOnCXXThis(CurrentLocation).get();
15484 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15485
15486 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15487 Conv->getLocation(),
15488 Conv, DerefThis);
15489
15490 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15491 // behavior. Note that only the general conversion function does this
15492 // (since it's unusable otherwise); in the case where we inline the
15493 // block literal, it has block literal lifetime semantics.
15494 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15495 BuildBlock = ImplicitCastExpr::Create(
15496 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15497 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15498
15499 if (BuildBlock.isInvalid()) {
15500 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15501 Conv->setInvalidDecl();
15502 return;
15503 }
15504
15505 // Create the return statement that returns the block from the conversion
15506 // function.
15507 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15508 if (Return.isInvalid()) {
15509 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15510 Conv->setInvalidDecl();
15511 return;
15512 }
15513
15514 // Set the body of the conversion function.
15515 Stmt *ReturnS = Return.get();
15516 Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(),
15517 Conv->getLocation(), Conv->getLocation()));
15518 Conv->markUsed(Context);
15519
15520 // We're done; notify the mutation listener, if any.
15521 if (ASTMutationListener *L = getASTMutationListener()) {
15522 L->CompletedImplicitDefinition(Conv);
15523 }
15524}
15525
15526/// Determine whether the given list arguments contains exactly one
15527/// "real" (non-default) argument.
15528static bool hasOneRealArgument(MultiExprArg Args) {
15529 switch (Args.size()) {
15530 case 0:
15531 return false;
15532
15533 default:
15534 if (!Args[1]->isDefaultArgument())
15535 return false;
15536
15537 [[fallthrough]];
15538 case 1:
15539 return !Args[0]->isDefaultArgument();
15540 }
15541
15542 return false;
15543}
15544
15545ExprResult
15546Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15547 NamedDecl *FoundDecl,
15548 CXXConstructorDecl *Constructor,
15549 MultiExprArg ExprArgs,
15550 bool HadMultipleCandidates,
15551 bool IsListInitialization,
15552 bool IsStdInitListInitialization,
15553 bool RequiresZeroInit,
15554 unsigned ConstructKind,
15555 SourceRange ParenRange) {
15556 bool Elidable = false;
15557
15558 // C++0x [class.copy]p34:
15559 // When certain criteria are met, an implementation is allowed to
15560 // omit the copy/move construction of a class object, even if the
15561 // copy/move constructor and/or destructor for the object have
15562 // side effects. [...]
15563 // - when a temporary class object that has not been bound to a
15564 // reference (12.2) would be copied/moved to a class object
15565 // with the same cv-unqualified type, the copy/move operation
15566 // can be omitted by constructing the temporary object
15567 // directly into the target of the omitted copy/move
15568 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15569 // FIXME: Converting constructors should also be accepted.
15570 // But to fix this, the logic that digs down into a CXXConstructExpr
15571 // to find the source object needs to handle it.
15572 // Right now it assumes the source object is passed directly as the
15573 // first argument.
15574 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15575 Expr *SubExpr = ExprArgs[0];
15576 // FIXME: Per above, this is also incorrect if we want to accept
15577 // converting constructors, as isTemporaryObject will
15578 // reject temporaries with different type from the
15579 // CXXRecord itself.
15580 Elidable = SubExpr->isTemporaryObject(
15581 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15582 }
15583
15584 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15585 FoundDecl, Constructor,
15586 Elidable, ExprArgs, HadMultipleCandidates,
15587 IsListInitialization,
15588 IsStdInitListInitialization, RequiresZeroInit,
15589 ConstructKind, ParenRange);
15590}
15591
15592ExprResult
15593Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15594 NamedDecl *FoundDecl,
15595 CXXConstructorDecl *Constructor,
15596 bool Elidable,
15597 MultiExprArg ExprArgs,
15598 bool HadMultipleCandidates,
15599 bool IsListInitialization,
15600 bool IsStdInitListInitialization,
15601 bool RequiresZeroInit,
15602 unsigned ConstructKind,
15603 SourceRange ParenRange) {
15604 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15605 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15606 // The only way to get here is if we did overlaod resolution to find the
15607 // shadow decl, so we don't need to worry about re-checking the trailing
15608 // requires clause.
15609 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc))
15610 return ExprError();
15611 }
15612
15613 return BuildCXXConstructExpr(
15614 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15615 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15616 RequiresZeroInit, ConstructKind, ParenRange);
15617}
15618
15619/// BuildCXXConstructExpr - Creates a complete call to a constructor,
15620/// including handling of its default argument expressions.
15621ExprResult
15622Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15623 CXXConstructorDecl *Constructor,
15624 bool Elidable,
15625 MultiExprArg ExprArgs,
15626 bool HadMultipleCandidates,
15627 bool IsListInitialization,
15628 bool IsStdInitListInitialization,
15629 bool RequiresZeroInit,
15630 unsigned ConstructKind,
15631 SourceRange ParenRange) {
15632 assert(declaresSameEntity((static_cast <bool> (declaresSameEntity( Constructor->
getParent(), DeclInitType->getBaseElementTypeUnsafe()->
getAsCXXRecordDecl()) && "given constructor for wrong type"
) ? void (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15635, __extension__ __PRETTY_FUNCTION__
))
15633 Constructor->getParent(),(static_cast <bool> (declaresSameEntity( Constructor->
getParent(), DeclInitType->getBaseElementTypeUnsafe()->
getAsCXXRecordDecl()) && "given constructor for wrong type"
) ? void (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15635, __extension__ __PRETTY_FUNCTION__
))
15634 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&(static_cast <bool> (declaresSameEntity( Constructor->
getParent(), DeclInitType->getBaseElementTypeUnsafe()->
getAsCXXRecordDecl()) && "given constructor for wrong type"
) ? void (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15635, __extension__ __PRETTY_FUNCTION__
))
15635 "given constructor for wrong type")(static_cast <bool> (declaresSameEntity( Constructor->
getParent(), DeclInitType->getBaseElementTypeUnsafe()->
getAsCXXRecordDecl()) && "given constructor for wrong type"
) ? void (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15635, __extension__ __PRETTY_FUNCTION__
))
;
15636 MarkFunctionReferenced(ConstructLoc, Constructor);
15637 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15638 return ExprError();
15639 if (getLangOpts().SYCLIsDevice &&
15640 !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15641 return ExprError();
15642
15643 return CheckForImmediateInvocation(
15644 CXXConstructExpr::Create(
15645 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15646 HadMultipleCandidates, IsListInitialization,
15647 IsStdInitListInitialization, RequiresZeroInit,
15648 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15649 ParenRange),
15650 Constructor);
15651}
15652
15653void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15654 if (VD->isInvalidDecl()) return;
15655 // If initializing the variable failed, don't also diagnose problems with
15656 // the destructor, they're likely related.
15657 if (VD->getInit() && VD->getInit()->containsErrors())
15658 return;
15659
15660 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15661 if (ClassDecl->isInvalidDecl()) return;
15662 if (ClassDecl->hasIrrelevantDestructor()) return;
15663 if (ClassDecl->isDependentContext()) return;
15664
15665 if (VD->isNoDestroy(getASTContext()))
15666 return;
15667
15668 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15669
15670 // If this is an array, we'll require the destructor during initialization, so
15671 // we can skip over this. We still want to emit exit-time destructor warnings
15672 // though.
15673 if (!VD->getType()->isArrayType()) {
15674 MarkFunctionReferenced(VD->getLocation(), Destructor);
15675 CheckDestructorAccess(VD->getLocation(), Destructor,
15676 PDiag(diag::err_access_dtor_var)
15677 << VD->getDeclName() << VD->getType());
15678 DiagnoseUseOfDecl(Destructor, VD->getLocation());
15679 }
15680
15681 if (Destructor->isTrivial()) return;
15682
15683 // If the destructor is constexpr, check whether the variable has constant
15684 // destruction now.
15685 if (Destructor->isConstexpr()) {
15686 bool HasConstantInit = false;
15687 if (VD->getInit() && !VD->getInit()->isValueDependent())
15688 HasConstantInit = VD->evaluateValue();
15689 SmallVector<PartialDiagnosticAt, 8> Notes;
15690 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15691 HasConstantInit) {
15692 Diag(VD->getLocation(),
15693 diag::err_constexpr_var_requires_const_destruction) << VD;
15694 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15695 Diag(Notes[I].first, Notes[I].second);
15696 }
15697 }
15698
15699 if (!VD->hasGlobalStorage()) return;
15700
15701 // Emit warning for non-trivial dtor in global scope (a real global,
15702 // class-static, function-static).
15703 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15704
15705 // TODO: this should be re-enabled for static locals by !CXAAtExit
15706 if (!VD->isStaticLocal())
15707 Diag(VD->getLocation(), diag::warn_global_destructor);
15708}
15709
15710/// Given a constructor and the set of arguments provided for the
15711/// constructor, convert the arguments and add any required default arguments
15712/// to form a proper call to this constructor.
15713///
15714/// \returns true if an error occurred, false otherwise.
15715bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15716 QualType DeclInitType, MultiExprArg ArgsPtr,
15717 SourceLocation Loc,
15718 SmallVectorImpl<Expr *> &ConvertedArgs,
15719 bool AllowExplicit,
15720 bool IsListInitialization) {
15721 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15722 unsigned NumArgs = ArgsPtr.size();
15723 Expr **Args = ArgsPtr.data();
15724
15725 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15726 unsigned NumParams = Proto->getNumParams();
15727
15728 // If too few arguments are available, we'll fill in the rest with defaults.
15729 if (NumArgs < NumParams)
15730 ConvertedArgs.reserve(NumParams);
15731 else
15732 ConvertedArgs.reserve(NumArgs);
15733
15734 VariadicCallType CallType =
15735 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15736 SmallVector<Expr *, 8> AllArgs;
15737 bool Invalid = GatherArgumentsForCall(
15738 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs,
15739 CallType, AllowExplicit, IsListInitialization);
15740 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15741
15742 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15743
15744 CheckConstructorCall(Constructor, DeclInitType,
15745 llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto,
15746 Loc);
15747
15748 return Invalid;
15749}
15750
15751static inline bool
15752CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15753 const FunctionDecl *FnDecl) {
15754 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15755 if (isa<NamespaceDecl>(DC)) {
15756 return SemaRef.Diag(FnDecl->getLocation(),
15757 diag::err_operator_new_delete_declared_in_namespace)
15758 << FnDecl->getDeclName();
15759 }
15760
15761 if (isa<TranslationUnitDecl>(DC) &&
15762 FnDecl->getStorageClass() == SC_Static) {
15763 return SemaRef.Diag(FnDecl->getLocation(),
15764 diag::err_operator_new_delete_declared_static)
15765 << FnDecl->getDeclName();
15766 }
15767
15768 return false;
15769}
15770
15771static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15772 const PointerType *PtrTy) {
15773 auto &Ctx = SemaRef.Context;
15774 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15775 PtrQuals.removeAddressSpace();
15776 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15777 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15778}
15779
15780static inline bool
15781CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15782 CanQualType ExpectedResultType,
15783 CanQualType ExpectedFirstParamType,
15784 unsigned DependentParamTypeDiag,
15785 unsigned InvalidParamTypeDiag) {
15786 QualType ResultType =
15787 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15788
15789 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15790 // The operator is valid on any address space for OpenCL.
15791 // Drop address space from actual and expected result types.
15792 if (const auto *PtrTy = ResultType->getAs<PointerType>())
15793 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15794
15795 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15796 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15797 }
15798
15799 // Check that the result type is what we expect.
15800 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15801 // Reject even if the type is dependent; an operator delete function is
15802 // required to have a non-dependent result type.
15803 return SemaRef.Diag(
15804 FnDecl->getLocation(),
15805 ResultType->isDependentType()
15806 ? diag::err_operator_new_delete_dependent_result_type
15807 : diag::err_operator_new_delete_invalid_result_type)
15808 << FnDecl->getDeclName() << ExpectedResultType;
15809 }
15810
15811 // A function template must have at least 2 parameters.
15812 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15813 return SemaRef.Diag(FnDecl->getLocation(),
15814 diag::err_operator_new_delete_template_too_few_parameters)
15815 << FnDecl->getDeclName();
15816
15817 // The function decl must have at least 1 parameter.
15818 if (FnDecl->getNumParams() == 0)
15819 return SemaRef.Diag(FnDecl->getLocation(),
15820 diag::err_operator_new_delete_too_few_parameters)
15821 << FnDecl->getDeclName();
15822
15823 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15824 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15825 // The operator is valid on any address space for OpenCL.
15826 // Drop address space from actual and expected first parameter types.
15827 if (const auto *PtrTy =
15828 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15829 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15830
15831 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15832 ExpectedFirstParamType =
15833 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15834 }
15835
15836 // Check that the first parameter type is what we expect.
15837 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15838 ExpectedFirstParamType) {
15839 // The first parameter type is not allowed to be dependent. As a tentative
15840 // DR resolution, we allow a dependent parameter type if it is the right
15841 // type anyway, to allow destroying operator delete in class templates.
15842 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15843 ? DependentParamTypeDiag
15844 : InvalidParamTypeDiag)
15845 << FnDecl->getDeclName() << ExpectedFirstParamType;
15846 }
15847
15848 return false;
15849}
15850
15851static bool
15852CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15853 // C++ [basic.stc.dynamic.allocation]p1:
15854 // A program is ill-formed if an allocation function is declared in a
15855 // namespace scope other than global scope or declared static in global
15856 // scope.
15857 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15858 return true;
15859
15860 CanQualType SizeTy =
15861 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15862
15863 // C++ [basic.stc.dynamic.allocation]p1:
15864 // The return type shall be void*. The first parameter shall have type
15865 // std::size_t.
15866 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15867 SizeTy,
15868 diag::err_operator_new_dependent_param_type,
15869 diag::err_operator_new_param_type))
15870 return true;
15871
15872 // C++ [basic.stc.dynamic.allocation]p1:
15873 // The first parameter shall not have an associated default argument.
15874 if (FnDecl->getParamDecl(0)->hasDefaultArg())
15875 return SemaRef.Diag(FnDecl->getLocation(),
15876 diag::err_operator_new_default_arg)
15877 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15878
15879 return false;
15880}
15881
15882static bool
15883CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15884 // C++ [basic.stc.dynamic.deallocation]p1:
15885 // A program is ill-formed if deallocation functions are declared in a
15886 // namespace scope other than global scope or declared static in global
15887 // scope.
15888 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15889 return true;
15890
15891 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15892
15893 // C++ P0722:
15894 // Within a class C, the first parameter of a destroying operator delete
15895 // shall be of type C *. The first parameter of any other deallocation
15896 // function shall be of type void *.
15897 CanQualType ExpectedFirstParamType =
15898 MD && MD->isDestroyingOperatorDelete()
15899 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15900 SemaRef.Context.getRecordType(MD->getParent())))
15901 : SemaRef.Context.VoidPtrTy;
15902
15903 // C++ [basic.stc.dynamic.deallocation]p2:
15904 // Each deallocation function shall return void
15905 if (CheckOperatorNewDeleteTypes(
15906 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15907 diag::err_operator_delete_dependent_param_type,
15908 diag::err_operator_delete_param_type))
15909 return true;
15910
15911 // C++ P0722:
15912 // A destroying operator delete shall be a usual deallocation function.
15913 if (MD && !MD->getParent()->isDependentContext() &&
15914 MD->isDestroyingOperatorDelete() &&
15915 !SemaRef.isUsualDeallocationFunction(MD)) {
15916 SemaRef.Diag(MD->getLocation(),
15917 diag::err_destroying_operator_delete_not_usual);
15918 return true;
15919 }
15920
15921 return false;
15922}
15923
15924/// CheckOverloadedOperatorDeclaration - Check whether the declaration
15925/// of this overloaded operator is well-formed. If so, returns false;
15926/// otherwise, emits appropriate diagnostics and returns true.
15927bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15928 assert(FnDecl && FnDecl->isOverloadedOperator() &&(static_cast <bool> (FnDecl && FnDecl->isOverloadedOperator
() && "Expected an overloaded operator declaration") ?
void (0) : __assert_fail ("FnDecl && FnDecl->isOverloadedOperator() && \"Expected an overloaded operator declaration\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15929, __extension__ __PRETTY_FUNCTION__
))
15929 "Expected an overloaded operator declaration")(static_cast <bool> (FnDecl && FnDecl->isOverloadedOperator
() && "Expected an overloaded operator declaration") ?
void (0) : __assert_fail ("FnDecl && FnDecl->isOverloadedOperator() && \"Expected an overloaded operator declaration\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15929, __extension__ __PRETTY_FUNCTION__
))
;
15930
15931 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15932
15933 // C++ [over.oper]p5:
15934 // The allocation and deallocation functions, operator new,
15935 // operator new[], operator delete and operator delete[], are
15936 // described completely in 3.7.3. The attributes and restrictions
15937 // found in the rest of this subclause do not apply to them unless
15938 // explicitly stated in 3.7.3.
15939 if (Op == OO_Delete || Op == OO_Array_Delete)
15940 return CheckOperatorDeleteDeclaration(*this, FnDecl);
15941
15942 if (Op == OO_New || Op == OO_Array_New)
15943 return CheckOperatorNewDeclaration(*this, FnDecl);
15944
15945 // C++ [over.oper]p7:
15946 // An operator function shall either be a member function or
15947 // be a non-member function and have at least one parameter
15948 // whose type is a class, a reference to a class, an enumeration,
15949 // or a reference to an enumeration.
15950 // Note: Before C++23, a member function could not be static. The only member
15951 // function allowed to be static is the call operator function.
15952 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15953 if (MethodDecl->isStatic()) {
15954 if (Op == OO_Call || Op == OO_Subscript)
15955 Diag(FnDecl->getLocation(),
15956 (LangOpts.CPlusPlus2b
15957 ? diag::warn_cxx20_compat_operator_overload_static
15958 : diag::ext_operator_overload_static))
15959 << FnDecl;
15960 else
15961 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
15962 << FnDecl;
15963 }
15964 } else {
15965 bool ClassOrEnumParam = false;
15966 for (auto *Param : FnDecl->parameters()) {
15967 QualType ParamType = Param->getType().getNonReferenceType();
15968 if (ParamType->isDependentType() || ParamType->isRecordType() ||
15969 ParamType->isEnumeralType()) {
15970 ClassOrEnumParam = true;
15971 break;
15972 }
15973 }
15974
15975 if (!ClassOrEnumParam)
15976 return Diag(FnDecl->getLocation(),
15977 diag::err_operator_overload_needs_class_or_enum)
15978 << FnDecl->getDeclName();
15979 }
15980
15981 // C++ [over.oper]p8:
15982 // An operator function cannot have default arguments (8.3.6),
15983 // except where explicitly stated below.
15984 //
15985 // Only the function-call operator (C++ [over.call]p1) and the subscript
15986 // operator (CWG2507) allow default arguments.
15987 if (Op != OO_Call) {
15988 ParmVarDecl *FirstDefaultedParam = nullptr;
15989 for (auto *Param : FnDecl->parameters()) {
15990 if (Param->hasDefaultArg()) {
15991 FirstDefaultedParam = Param;
15992 break;
15993 }
15994 }
15995 if (FirstDefaultedParam) {
15996 if (Op == OO_Subscript) {
15997 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15998 ? diag::ext_subscript_overload
15999 : diag::error_subscript_overload)
16000 << FnDecl->getDeclName() << 1
16001 << FirstDefaultedParam->getDefaultArgRange();
16002 } else {
16003 return Diag(FirstDefaultedParam->getLocation(),
16004 diag::err_operator_overload_default_arg)
16005 << FnDecl->getDeclName()
16006 << FirstDefaultedParam->getDefaultArgRange();
16007 }
16008 }
16009 }
16010
16011 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16012 { false, false, false }
16013#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16014 , { Unary, Binary, MemberOnly }
16015#include "clang/Basic/OperatorKinds.def"
16016 };
16017
16018 bool CanBeUnaryOperator = OperatorUses[Op][0];
16019 bool CanBeBinaryOperator = OperatorUses[Op][1];
16020 bool MustBeMemberOperator = OperatorUses[Op][2];
16021
16022 // C++ [over.oper]p8:
16023 // [...] Operator functions cannot have more or fewer parameters
16024 // than the number required for the corresponding operator, as
16025 // described in the rest of this subclause.
16026 unsigned NumParams = FnDecl->getNumParams()
16027 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
16028 if (Op != OO_Call && Op != OO_Subscript &&
16029 ((NumParams == 1 && !CanBeUnaryOperator) ||
16030 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16031 (NumParams > 2))) {
16032 // We have the wrong number of parameters.
16033 unsigned ErrorKind;
16034 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16035 ErrorKind = 2; // 2 -> unary or binary.
16036 } else if (CanBeUnaryOperator) {
16037 ErrorKind = 0; // 0 -> unary
16038 } else {
16039 assert(CanBeBinaryOperator &&(static_cast <bool> (CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!"
) ? void (0) : __assert_fail ("CanBeBinaryOperator && \"All non-call overloaded operators are unary or binary!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 16040, __extension__ __PRETTY_FUNCTION__
))
16040 "All non-call overloaded operators are unary or binary!")(static_cast <bool> (CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!"
) ? void (0) : __assert_fail ("CanBeBinaryOperator && \"All non-call overloaded operators are unary or binary!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 16040, __extension__ __PRETTY_FUNCTION__
))
;
16041 ErrorKind = 1; // 1 -> binary
16042 }
16043 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16044 << FnDecl->getDeclName() << NumParams << ErrorKind;
16045 }
16046
16047 if (Op == OO_Subscript && NumParams != 2) {
16048 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
16049 ? diag::ext_subscript_overload
16050 : diag::error_subscript_overload)
16051 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16052 }
16053
16054 // Overloaded operators other than operator() and operator[] cannot be
16055 // variadic.
16056 if (Op != OO_Call &&
16057 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16058 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16059 << FnDecl->getDeclName();
16060 }
16061
16062 // Some operators must be member functions.
16063 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16064 return Diag(FnDecl->getLocation(),
16065 diag::err_operator_overload_must_be_member)
16066 << FnDecl->getDeclName();
16067 }
16068
16069 // C++ [over.inc]p1:
16070 // The user-defined function called operator++ implements the
16071 // prefix and postfix ++ operator. If this function is a member
16072 // function with no parameters, or a non-member function with one
16073 // parameter of class or enumeration type, it defines the prefix
16074 // increment operator ++ for objects of that type. If the function
16075 // is a member function with one parameter (which shall be of type
16076 // int) or a non-member function with two parameters (the second
16077 // of which shall be of type int), it defines the postfix
16078 // increment operator ++ for objects of that type.
16079 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16080 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16081 QualType ParamType = LastParam->getType();
16082
16083 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16084 !ParamType->isDependentType())
16085 return Diag(LastParam->getLocation(),
16086 diag::err_operator_overload_post_incdec_must_be_int)
16087 << LastParam->getType() << (Op == OO_MinusMinus);
16088 }
16089
16090 return false;
16091}
16092
16093static bool
16094checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16095 FunctionTemplateDecl *TpDecl) {
16096 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16097
16098 // Must have one or two template parameters.
16099 if (TemplateParams->size() == 1) {
16100 NonTypeTemplateParmDecl *PmDecl =
16101 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16102
16103 // The template parameter must be a char parameter pack.
16104 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16105 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16106 return false;
16107
16108 // C++20 [over.literal]p5:
16109 // A string literal operator template is a literal operator template
16110 // whose template-parameter-list comprises a single non-type
16111 // template-parameter of class type.
16112 //
16113 // As a DR resolution, we also allow placeholders for deduced class
16114 // template specializations.
16115 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16116 !PmDecl->isTemplateParameterPack() &&
16117 (PmDecl->getType()->isRecordType() ||
16118 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16119 return false;
16120 } else if (TemplateParams->size() == 2) {
16121 TemplateTypeParmDecl *PmType =
16122 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16123 NonTypeTemplateParmDecl *PmArgs =
16124 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16125
16126 // The second template parameter must be a parameter pack with the
16127 // first template parameter as its type.
16128 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16129 PmArgs->isTemplateParameterPack()) {
16130 const TemplateTypeParmType *TArgs =
16131 PmArgs->getType()->getAs<TemplateTypeParmType>();
16132 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16133 TArgs->getIndex() == PmType->getIndex()) {
16134 if (!SemaRef.inTemplateInstantiation())
16135 SemaRef.Diag(TpDecl->getLocation(),
16136 diag::ext_string_literal_operator_template);
16137 return false;
16138 }
16139 }
16140 }
16141
16142 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16143 diag::err_literal_operator_template)
16144 << TpDecl->getTemplateParameters()->getSourceRange();
16145 return true;
16146}
16147
16148/// CheckLiteralOperatorDeclaration - Check whether the declaration
16149/// of this literal operator function is well-formed. If so, returns
16150/// false; otherwise, emits appropriate diagnostics and returns true.
16151bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16152 if (isa<CXXMethodDecl>(FnDecl)) {
16153 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16154 << FnDecl->getDeclName();
16155 return true;
16156 }
16157
16158 if (FnDecl->isExternC()) {
16159 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16160 if (const LinkageSpecDecl *LSD =
16161 FnDecl->getDeclContext()->getExternCContext())
16162 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16163 return true;
16164 }
16165
16166 // This might be the definition of a literal operator template.
16167 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16168
16169 // This might be a specialization of a literal operator template.
16170 if (!TpDecl)
16171 TpDecl = FnDecl->getPrimaryTemplate();
16172
16173 // template <char...> type operator "" name() and
16174 // template <class T, T...> type operator "" name() are the only valid
16175 // template signatures, and the only valid signatures with no parameters.
16176 //
16177 // C++20 also allows template <SomeClass T> type operator "" name().
16178 if (TpDecl) {
16179 if (FnDecl->param_size() != 0) {
16180 Diag(FnDecl->getLocation(),
16181 diag::err_literal_operator_template_with_params);
16182 return true;
16183 }
16184
16185 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16186 return true;
16187
16188 } else if (FnDecl->param_size() == 1) {
16189 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16190
16191 QualType ParamType = Param->getType().getUnqualifiedType();
16192
16193 // Only unsigned long long int, long double, any character type, and const
16194 // char * are allowed as the only parameters.
16195 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16196 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16197 Context.hasSameType(ParamType, Context.CharTy) ||
16198 Context.hasSameType(ParamType, Context.WideCharTy) ||
16199 Context.hasSameType(ParamType, Context.Char8Ty) ||
16200 Context.hasSameType(ParamType, Context.Char16Ty) ||
16201 Context.hasSameType(ParamType, Context.Char32Ty)) {
16202 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16203 QualType InnerType = Ptr->getPointeeType();
16204
16205 // Pointer parameter must be a const char *.
16206 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16207 Context.CharTy) &&
16208 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16209 Diag(Param->getSourceRange().getBegin(),
16210 diag::err_literal_operator_param)
16211 << ParamType << "'const char *'" << Param->getSourceRange();
16212 return true;
16213 }
16214
16215 } else if (ParamType->isRealFloatingType()) {
16216 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16217 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16218 return true;
16219
16220 } else if (ParamType->isIntegerType()) {
16221 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16222 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16223 return true;
16224
16225 } else {
16226 Diag(Param->getSourceRange().getBegin(),
16227 diag::err_literal_operator_invalid_param)
16228 << ParamType << Param->getSourceRange();
16229 return true;
16230 }
16231
16232 } else if (FnDecl->param_size() == 2) {
16233 FunctionDecl::param_iterator Param = FnDecl->param_begin();
16234
16235 // First, verify that the first parameter is correct.
16236
16237 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16238
16239 // Two parameter function must have a pointer to const as a
16240 // first parameter; let's strip those qualifiers.
16241 const PointerType *PT = FirstParamType->getAs<PointerType>();
16242
16243 if (!PT) {
16244 Diag((*Param)->getSourceRange().getBegin(),
16245 diag::err_literal_operator_param)
16246 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16247 return true;
16248 }
16249
16250 QualType PointeeType = PT->getPointeeType();
16251 // First parameter must be const
16252 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16253 Diag((*Param)->getSourceRange().getBegin(),
16254 diag::err_literal_operator_param)
16255 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16256 return true;
16257 }
16258
16259 QualType InnerType = PointeeType.getUnqualifiedType();
16260 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16261 // const char32_t* are allowed as the first parameter to a two-parameter
16262 // function
16263 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16264 Context.hasSameType(InnerType, Context.WideCharTy) ||
16265 Context.hasSameType(InnerType, Context.Char8Ty) ||
16266 Context.hasSameType(InnerType, Context.Char16Ty) ||
16267 Context.hasSameType(InnerType, Context.Char32Ty))) {
16268 Diag((*Param)->getSourceRange().getBegin(),
16269 diag::err_literal_operator_param)
16270 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16271 return true;
16272 }
16273
16274 // Move on to the second and final parameter.
16275 ++Param;
16276
16277 // The second parameter must be a std::size_t.
16278 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16279 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16280 Diag((*Param)->getSourceRange().getBegin(),
16281 diag::err_literal_operator_param)
16282 << SecondParamType << Context.getSizeType()
16283 << (*Param)->getSourceRange();
16284 return true;
16285 }
16286 } else {
16287 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16288 return true;
16289 }
16290
16291 // Parameters are good.
16292
16293 // A parameter-declaration-clause containing a default argument is not
16294 // equivalent to any of the permitted forms.
16295 for (auto *Param : FnDecl->parameters()) {
16296 if (Param->hasDefaultArg()) {
16297 Diag(Param->getDefaultArgRange().getBegin(),
16298 diag::err_literal_operator_default_argument)
16299 << Param->getDefaultArgRange();
16300 break;
16301 }
16302 }
16303
16304 StringRef LiteralName
16305 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
16306 if (LiteralName[0] != '_' &&
16307 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16308 // C++11 [usrlit.suffix]p1:
16309 // Literal suffix identifiers that do not start with an underscore
16310 // are reserved for future standardization.
16311 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16312 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
16313 }
16314
16315 return false;
16316}
16317
16318/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16319/// linkage specification, including the language and (if present)
16320/// the '{'. ExternLoc is the location of the 'extern', Lang is the
16321/// language string literal. LBraceLoc, if valid, provides the location of
16322/// the '{' brace. Otherwise, this linkage specification does not
16323/// have any braces.
16324Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16325 Expr *LangStr,
16326 SourceLocation LBraceLoc) {
16327 StringLiteral *Lit = cast<StringLiteral>(LangStr);
16328 if (!Lit->isOrdinary()) {
16329 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16330 << LangStr->getSourceRange();
16331 return nullptr;
16332 }
16333
16334 StringRef Lang = Lit->getString();
16335 LinkageSpecDecl::LanguageIDs Language;
16336 if (Lang == "C")
16337 Language = LinkageSpecDecl::lang_c;
16338 else if (Lang == "C++")
16339 Language = LinkageSpecDecl::lang_cxx;
16340 else {
16341 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16342 << LangStr->getSourceRange();
16343 return nullptr;
16344 }
16345
16346 // FIXME: Add all the various semantics of linkage specifications
16347
16348 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16349 LangStr->getExprLoc(), Language,
16350 LBraceLoc.isValid());
16351
16352 /// C++ [module.unit]p7.2.3
16353 /// - Otherwise, if the declaration
16354 /// - ...
16355 /// - ...
16356 /// - appears within a linkage-specification,
16357 /// it is attached to the global module.
16358 ///
16359 /// If the declaration is already in global module fragment, we don't
16360 /// need to attach it again.
16361 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16362 Module *GlobalModule =
16363 PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true);
16364 /// According to [module.reach]p3.2,
16365 /// The declaration in global module fragment is reachable if it is not
16366 /// discarded. And the discarded declaration should be deleted. So it
16367 /// doesn't matter mark the declaration in global module fragment as
16368 /// reachable here.
16369 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
16370 D->setLocalOwningModule(GlobalModule);
16371 }
16372
16373 CurContext->addDecl(D);
16374 PushDeclContext(S, D);
16375 return D;
16376}
16377
16378/// ActOnFinishLinkageSpecification - Complete the definition of
16379/// the C++ linkage specification LinkageSpec. If RBraceLoc is
16380/// valid, it's the position of the closing '}' brace in a linkage
16381/// specification that uses braces.
16382Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16383 Decl *LinkageSpec,
16384 SourceLocation RBraceLoc) {
16385 if (RBraceLoc.isValid()) {
16386 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16387 LSDecl->setRBraceLoc(RBraceLoc);
16388 }
16389
16390 // If the current module doesn't has Parent, it implies that the
16391 // LinkageSpec isn't in the module created by itself. So we don't
16392 // need to pop it.
16393 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16394 getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent)
16395 PopGlobalModuleFragment();
16396
16397 PopDeclContext();
16398 return LinkageSpec;
16399}
16400
16401Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16402 const ParsedAttributesView &AttrList,
16403 SourceLocation SemiLoc) {
16404 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16405 // Attribute declarations appertain to empty declaration so we handle
16406 // them here.
16407 ProcessDeclAttributeList(S, ED, AttrList);
16408
16409 CurContext->addDecl(ED);
16410 return ED;
16411}
16412
16413/// Perform semantic analysis for the variable declaration that
16414/// occurs within a C++ catch clause, returning the newly-created
16415/// variable.
16416VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16417 TypeSourceInfo *TInfo,
16418 SourceLocation StartLoc,
16419 SourceLocation Loc,
16420 IdentifierInfo *Name) {
16421 bool Invalid = false;
16422 QualType ExDeclType = TInfo->getType();
16423
16424 // Arrays and functions decay.
16425 if (ExDeclType->isArrayType())
16426 ExDeclType = Context.getArrayDecayedType(ExDeclType);
16427 else if (ExDeclType->isFunctionType())
16428 ExDeclType = Context.getPointerType(ExDeclType);
16429
16430 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16431 // The exception-declaration shall not denote a pointer or reference to an
16432 // incomplete type, other than [cv] void*.
16433 // N2844 forbids rvalue references.
16434 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16435 Diag(Loc, diag::err_catch_rvalue_ref);
16436 Invalid = true;
16437 }
16438
16439 if (ExDeclType->isVariablyModifiedType()) {
16440 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16441 Invalid = true;
16442 }
16443
16444 QualType BaseType = ExDeclType;
16445 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16446 unsigned DK = diag::err_catch_incomplete;
16447 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16448 BaseType = Ptr->getPointeeType();
16449 Mode = 1;
16450 DK = diag::err_catch_incomplete_ptr;
16451 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16452 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16453 BaseType = Ref->getPointeeType();
16454 Mode = 2;
16455 DK = diag::err_catch_incomplete_ref;
16456 }
16457 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16458 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16459 Invalid = true;
16460
16461 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16462 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16463 Invalid = true;
16464 }
16465
16466 if (!Invalid && !ExDeclType->isDependentType() &&
16467 RequireNonAbstractType(Loc, ExDeclType,
16468 diag::err_abstract_type_in_decl,
16469 AbstractVariableType))
16470 Invalid = true;
16471
16472 // Only the non-fragile NeXT runtime currently supports C++ catches
16473 // of ObjC types, and no runtime supports catching ObjC types by value.
16474 if (!Invalid && getLangOpts().ObjC) {
16475 QualType T = ExDeclType;
16476 if (const ReferenceType *RT = T->getAs<ReferenceType>())
16477 T = RT->getPointeeType();
16478
16479 if (T->isObjCObjectType()) {
16480 Diag(Loc, diag::err_objc_object_catch);
16481 Invalid = true;
16482 } else if (T->isObjCObjectPointerType()) {
16483 // FIXME: should this be a test for macosx-fragile specifically?
16484 if (getLangOpts().ObjCRuntime.isFragile())
16485 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16486 }
16487 }
16488
16489 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16490 ExDeclType, TInfo, SC_None);
16491 ExDecl->setExceptionVariable(true);
16492
16493 // In ARC, infer 'retaining' for variables of retainable type.
16494 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16495 Invalid = true;
16496
16497 if (!Invalid && !ExDeclType->isDependentType()) {
16498 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16499 // Insulate this from anything else we might currently be parsing.
16500 EnterExpressionEvaluationContext scope(
16501 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16502
16503 // C++ [except.handle]p16:
16504 // The object declared in an exception-declaration or, if the
16505 // exception-declaration does not specify a name, a temporary (12.2) is
16506 // copy-initialized (8.5) from the exception object. [...]
16507 // The object is destroyed when the handler exits, after the destruction
16508 // of any automatic objects initialized within the handler.
16509 //
16510 // We just pretend to initialize the object with itself, then make sure
16511 // it can be destroyed later.
16512 QualType initType = Context.getExceptionObjectType(ExDeclType);
16513
16514 InitializedEntity entity =
16515 InitializedEntity::InitializeVariable(ExDecl);
16516 InitializationKind initKind =
16517 InitializationKind::CreateCopy(Loc, SourceLocation());
16518
16519 Expr *opaqueValue =
16520 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16521 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16522 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16523 if (result.isInvalid())
16524 Invalid = true;
16525 else {
16526 // If the constructor used was non-trivial, set this as the
16527 // "initializer".
16528 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16529 if (!construct->getConstructor()->isTrivial()) {
16530 Expr *init = MaybeCreateExprWithCleanups(construct);
16531 ExDecl->setInit(init);
16532 }
16533
16534 // And make sure it's destructable.
16535 FinalizeVarWithDestructor(ExDecl, recordType);
16536 }
16537 }
16538 }
16539
16540 if (Invalid)
16541 ExDecl->setInvalidDecl();
16542
16543 return ExDecl;
16544}
16545
16546/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16547/// handler.
16548Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16549 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16550 bool Invalid = D.isInvalidType();
16551
16552 // Check for unexpanded parameter packs.
16553 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16554 UPPC_ExceptionType)) {
16555 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16556 D.getIdentifierLoc());
16557 Invalid = true;
16558 }
16559
16560 IdentifierInfo *II = D.getIdentifier();
16561 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16562 LookupOrdinaryName,
16563 ForVisibleRedeclaration)) {
16564 // The scope should be freshly made just for us. There is just no way
16565 // it contains any previous declaration, except for function parameters in
16566 // a function-try-block's catch statement.
16567 assert(!S->isDeclScope(PrevDecl))(static_cast <bool> (!S->isDeclScope(PrevDecl)) ? void
(0) : __assert_fail ("!S->isDeclScope(PrevDecl)", "clang/lib/Sema/SemaDeclCXX.cpp"
, 16567, __extension__ __PRETTY_FUNCTION__))
;
16568 if (isDeclInScope(PrevDecl, CurContext, S)) {
16569 Diag(D.getIdentifierLoc(), diag::err_redefinition)
16570 << D.getIdentifier();
16571 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16572 Invalid = true;
16573 } else if (PrevDecl->isTemplateParameter())
16574 // Maybe we will complain about the shadowed template parameter.
16575 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16576 }
16577
16578 if (D.getCXXScopeSpec().isSet() && !Invalid) {
16579 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16580 << D.getCXXScopeSpec().getRange();
16581 Invalid = true;
16582 }
16583
16584 VarDecl *ExDecl = BuildExceptionDeclaration(
16585 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16586 if (Invalid)
16587 ExDecl->setInvalidDecl();
16588
16589 // Add the exception declaration into this scope.
16590 if (II)
16591 PushOnScopeChains(ExDecl, S);
16592 else
16593 CurContext->addDecl(ExDecl);
16594
16595 ProcessDeclAttributes(S, ExDecl, D);
16596 return ExDecl;
16597}
16598
16599Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16600 Expr *AssertExpr,
16601 Expr *AssertMessageExpr,
16602 SourceLocation RParenLoc) {
16603 StringLiteral *AssertMessage =
16604 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16605
16606 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16607 return nullptr;
16608
16609 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16610 AssertMessage, RParenLoc, false);
16611}
16612
16613/// Convert \V to a string we can present to the user in a diagnostic
16614/// \T is the type of the expression that has been evaluated into \V
16615static bool ConvertAPValueToString(const APValue &V, QualType T,
16616 SmallVectorImpl<char> &Str) {
16617 if (!V.hasValue())
16618 return false;
16619
16620 switch (V.getKind()) {
16621 case APValue::ValueKind::Int:
16622 if (T->isBooleanType()) {
16623 // Bools are reduced to ints during evaluation, but for
16624 // diagnostic purposes we want to print them as
16625 // true or false.
16626 int64_t BoolValue = V.getInt().getExtValue();
16627 assert((BoolValue == 0 || BoolValue == 1) &&(static_cast <bool> ((BoolValue == 0 || BoolValue == 1)
&& "Bool type, but value is not 0 or 1") ? void (0) :
__assert_fail ("(BoolValue == 0 || BoolValue == 1) && \"Bool type, but value is not 0 or 1\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 16628, __extension__ __PRETTY_FUNCTION__
))
16628 "Bool type, but value is not 0 or 1")(static_cast <bool> ((BoolValue == 0 || BoolValue == 1)
&& "Bool type, but value is not 0 or 1") ? void (0) :
__assert_fail ("(BoolValue == 0 || BoolValue == 1) && \"Bool type, but value is not 0 or 1\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 16628, __extension__ __PRETTY_FUNCTION__
))
;
16629 llvm::raw_svector_ostream OS(Str);
16630 OS << (BoolValue ? "true" : "false");
16631 } else if (T->isCharType()) {
16632 // Same is true for chars.
16633 Str.push_back('\'');
16634 Str.push_back(V.getInt().getExtValue());
16635 Str.push_back('\'');
16636 } else
16637 V.getInt().toString(Str);
16638
16639 break;
16640
16641 case APValue::ValueKind::Float:
16642 V.getFloat().toString(Str);
16643 break;
16644
16645 case APValue::ValueKind::LValue:
16646 if (V.isNullPointer()) {
16647 llvm::raw_svector_ostream OS(Str);
16648 OS << "nullptr";
16649 } else
16650 return false;
16651 break;
16652
16653 case APValue::ValueKind::ComplexFloat: {
16654 llvm::raw_svector_ostream OS(Str);
16655 OS << '(';
16656 V.getComplexFloatReal().toString(Str);
16657 OS << " + ";
16658 V.getComplexFloatImag().toString(Str);
16659 OS << "i)";
16660 } break;
16661
16662 case APValue::ValueKind::ComplexInt: {
16663 llvm::raw_svector_ostream OS(Str);
16664 OS << '(';
16665 V.getComplexIntReal().toString(Str);
16666 OS << " + ";
16667 V.getComplexIntImag().toString(Str);
16668 OS << "i)";
16669 } break;
16670
16671 default:
16672 return false;
16673 }
16674
16675 return true;
16676}
16677
16678/// Some Expression types are not useful to print notes about,
16679/// e.g. literals and values that have already been expanded
16680/// before such as int-valued template parameters.
16681static bool UsefulToPrintExpr(const Expr *E) {
16682 E = E->IgnoreParenImpCasts();
16683 // Literals are pretty easy for humans to understand.
16684 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
16685 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(E))
16686 return false;
16687
16688 // These have been substituted from template parameters
16689 // and appear as literals in the static assert error.
16690 if (isa<SubstNonTypeTemplateParmExpr>(E))
16691 return false;
16692
16693 // -5 is also simple to understand.
16694 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E))
16695 return UsefulToPrintExpr(UnaryOp->getSubExpr());
16696
16697 // Ignore nested binary operators. This could be a FIXME for improvements
16698 // to the diagnostics in the future.
16699 if (isa<BinaryOperator>(E))
16700 return false;
16701
16702 return true;
16703}
16704
16705/// Try to print more useful information about a failed static_assert
16706/// with expression \E
16707void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
16708 if (const auto *Op = dyn_cast<BinaryOperator>(E)) {
16709 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
16710 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
16711
16712 // Ignore comparisons of boolean expressions with a boolean literal.
16713 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
16714 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
16715 return;
16716
16717 // Don't print obvious expressions.
16718 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
16719 return;
16720
16721 struct {
16722 const clang::Expr *Cond;
16723 Expr::EvalResult Result;
16724 SmallString<12> ValueString;
16725 bool Print;
16726 } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
16727 {RHS, Expr::EvalResult(), {}, false}};
16728 for (unsigned I = 0; I < 2; I++) {
16729 const Expr *Side = DiagSide[I].Cond;
16730
16731 Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
16732
16733 DiagSide[I].Print = ConvertAPValueToString(
16734 DiagSide[I].Result.Val, Side->getType(), DiagSide[I].ValueString);
16735 }
16736 if (DiagSide[0].Print && DiagSide[1].Print) {
16737 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
16738 << DiagSide[0].ValueString << Op->getOpcodeStr()
16739 << DiagSide[1].ValueString << Op->getSourceRange();
16740 }
16741 }
16742}
16743
16744Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16745 Expr *AssertExpr,
16746 StringLiteral *AssertMessage,
16747 SourceLocation RParenLoc,
16748 bool Failed) {
16749 assert(AssertExpr != nullptr && "Expected non-null condition")(static_cast <bool> (AssertExpr != nullptr && "Expected non-null condition"
) ? void (0) : __assert_fail ("AssertExpr != nullptr && \"Expected non-null condition\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 16749, __extension__ __PRETTY_FUNCTION__
))
;
16750 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16751 !Failed) {
16752 // In a static_assert-declaration, the constant-expression shall be a
16753 // constant expression that can be contextually converted to bool.
16754 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16755 if (Converted.isInvalid())
16756 Failed = true;
16757
16758 ExprResult FullAssertExpr =
16759 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16760 /*DiscardedValue*/ false,
16761 /*IsConstexpr*/ true);
16762 if (FullAssertExpr.isInvalid())
16763 Failed = true;
16764 else
16765 AssertExpr = FullAssertExpr.get();
16766
16767 llvm::APSInt Cond;
16768 Expr *BaseExpr = AssertExpr;
16769 AllowFoldKind FoldKind = NoFold;
16770
16771 if (!getLangOpts().CPlusPlus) {
16772 // In C mode, allow folding as an extension for better compatibility with
16773 // C++ in terms of expressions like static_assert("test") or
16774 // static_assert(nullptr).
16775 FoldKind = AllowFold;
16776 }
16777
16778 if (!Failed && VerifyIntegerConstantExpression(
16779 BaseExpr, &Cond,
16780 diag::err_static_assert_expression_is_not_constant,
16781 FoldKind).isInvalid())
16782 Failed = true;
16783
16784 if (!Failed && !Cond) {
16785 SmallString<256> MsgBuffer;
16786 llvm::raw_svector_ostream Msg(MsgBuffer);
16787 if (AssertMessage) {
16788 const auto *MsgStr = cast<StringLiteral>(AssertMessage);
16789 if (MsgStr->isOrdinary())
16790 Msg << MsgStr->getString();
16791 else
16792 MsgStr->printPretty(Msg, nullptr, getPrintingPolicy());
16793 }
16794
16795 Expr *InnerCond = nullptr;
16796 std::string InnerCondDescription;
16797 std::tie(InnerCond, InnerCondDescription) =
16798 findFailedBooleanCondition(Converted.get());
16799 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16800 // Drill down into concept specialization expressions to see why they
16801 // weren't satisfied.
16802 Diag(StaticAssertLoc, diag::err_static_assert_failed)
16803 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16804 ConstraintSatisfaction Satisfaction;
16805 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16806 DiagnoseUnsatisfiedConstraint(Satisfaction);
16807 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16808 && !isa<IntegerLiteral>(InnerCond)) {
16809 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16810 << InnerCondDescription << !AssertMessage
16811 << Msg.str() << InnerCond->getSourceRange();
16812 DiagnoseStaticAssertDetails(InnerCond);
16813 } else {
16814 Diag(StaticAssertLoc, diag::err_static_assert_failed)
16815 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16816 }
16817 Failed = true;
16818 }
16819 } else {
16820 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16821 /*DiscardedValue*/false,
16822 /*IsConstexpr*/true);
16823 if (FullAssertExpr.isInvalid())
16824 Failed = true;
16825 else
16826 AssertExpr = FullAssertExpr.get();
16827 }
16828
16829 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16830 AssertExpr, AssertMessage, RParenLoc,
16831 Failed);
16832
16833 CurContext->addDecl(Decl);
16834 return Decl;
16835}
16836
16837/// Perform semantic analysis of the given friend type declaration.
16838///
16839/// \returns A friend declaration that.
16840FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16841 SourceLocation FriendLoc,
16842 TypeSourceInfo *TSInfo) {
16843 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration")(static_cast <bool> (TSInfo && "NULL TypeSourceInfo for friend type declaration"
) ? void (0) : __assert_fail ("TSInfo && \"NULL TypeSourceInfo for friend type declaration\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 16843, __extension__ __PRETTY_FUNCTION__
))
;
16844
16845 QualType T = TSInfo->getType();
16846 SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
16847
16848 // C++03 [class.friend]p2:
16849 // An elaborated-type-specifier shall be used in a friend declaration
16850 // for a class.*
16851 //
16852 // * The class-key of the elaborated-type-specifier is required.
16853 if (!CodeSynthesisContexts.empty()) {
16854 // Do not complain about the form of friend template types during any kind
16855 // of code synthesis. For template instantiation, we will have complained
16856 // when the template was defined.
16857 } else {
16858 if (!T->isElaboratedTypeSpecifier()) {
16859 // If we evaluated the type to a record type, suggest putting
16860 // a tag in front.
16861 if (const RecordType *RT = T->getAs<RecordType>()) {
16862 RecordDecl *RD = RT->getDecl();
16863
16864 SmallString<16> InsertionText(" ");
16865 InsertionText += RD->getKindName();
16866
16867 Diag(TypeRange.getBegin(),
16868 getLangOpts().CPlusPlus11 ?
16869 diag::warn_cxx98_compat_unelaborated_friend_type :
16870 diag::ext_unelaborated_friend_type)
16871 << (unsigned) RD->getTagKind()
16872 << T
16873 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16874 InsertionText);
16875 } else {
16876 Diag(FriendLoc,
16877 getLangOpts().CPlusPlus11 ?
16878 diag::warn_cxx98_compat_nonclass_type_friend :
16879 diag::ext_nonclass_type_friend)
16880 << T
16881 << TypeRange;
16882 }
16883 } else if (T->getAs<EnumType>()) {
16884 Diag(FriendLoc,
16885 getLangOpts().CPlusPlus11 ?
16886 diag::warn_cxx98_compat_enum_friend :
16887 diag::ext_enum_friend)
16888 << T
16889 << TypeRange;
16890 }
16891
16892 // C++11 [class.friend]p3:
16893 // A friend declaration that does not declare a function shall have one
16894 // of the following forms:
16895 // friend elaborated-type-specifier ;
16896 // friend simple-type-specifier ;
16897 // friend typename-specifier ;
16898 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16899 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16900 }
16901
16902 // If the type specifier in a friend declaration designates a (possibly
16903 // cv-qualified) class type, that class is declared as a friend; otherwise,
16904 // the friend declaration is ignored.
16905 return FriendDecl::Create(Context, CurContext,
16906 TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16907 FriendLoc);
16908}
16909
16910/// Handle a friend tag declaration where the scope specifier was
16911/// templated.
16912Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16913 unsigned TagSpec, SourceLocation TagLoc,
16914 CXXScopeSpec &SS, IdentifierInfo *Name,
16915 SourceLocation NameLoc,
16916 const ParsedAttributesView &Attr,
16917 MultiTemplateParamsArg TempParamLists) {
16918 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16919
16920 bool IsMemberSpecialization = false;
16921 bool Invalid = false;
16922
16923 if (TemplateParameterList *TemplateParams =
16924 MatchTemplateParametersToScopeSpecifier(
16925 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16926 IsMemberSpecialization, Invalid)) {
16927 if (TemplateParams->size() > 0) {
16928 // This is a declaration of a class template.
16929 if (Invalid)
16930 return nullptr;
16931
16932 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16933 NameLoc, Attr, TemplateParams, AS_public,
16934 /*ModulePrivateLoc=*/SourceLocation(),
16935 FriendLoc, TempParamLists.size() - 1,
16936 TempParamLists.data()).get();
16937 } else {
16938 // The "template<>" header is extraneous.
16939 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16940 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16941 IsMemberSpecialization = true;
16942 }
16943 }
16944
16945 if (Invalid) return nullptr;
16946
16947 bool isAllExplicitSpecializations = true;
16948 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16949 if (TempParamLists[I]->size()) {
16950 isAllExplicitSpecializations = false;
16951 break;
16952 }
16953 }
16954
16955 // FIXME: don't ignore attributes.
16956
16957 // If it's explicit specializations all the way down, just forget
16958 // about the template header and build an appropriate non-templated
16959 // friend. TODO: for source fidelity, remember the headers.
16960 if (isAllExplicitSpecializations) {
16961 if (SS.isEmpty()) {
16962 bool Owned = false;
16963 bool IsDependent = false;
16964 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16965 Attr, AS_public,
16966 /*ModulePrivateLoc=*/SourceLocation(),
16967 MultiTemplateParamsArg(), Owned, IsDependent,
16968 /*ScopedEnumKWLoc=*/SourceLocation(),
16969 /*ScopedEnumUsesClassTag=*/false,
16970 /*UnderlyingType=*/TypeResult(),
16971 /*IsTypeSpecifier=*/false,
16972 /*IsTemplateParamOrArg=*/false);
16973 }
16974
16975 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16976 ElaboratedTypeKeyword Keyword
16977 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16978 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16979 *Name, NameLoc);
16980 if (T.isNull())
16981 return nullptr;
16982
16983 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16984 if (isa<DependentNameType>(T)) {
16985 DependentNameTypeLoc TL =
16986 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16987 TL.setElaboratedKeywordLoc(TagLoc);
16988 TL.setQualifierLoc(QualifierLoc);
16989 TL.setNameLoc(NameLoc);
16990 } else {
16991 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16992 TL.setElaboratedKeywordLoc(TagLoc);
16993 TL.setQualifierLoc(QualifierLoc);
16994 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16995 }
16996
16997 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16998 TSI, FriendLoc, TempParamLists);
16999 Friend->setAccess(AS_public);
17000 CurContext->addDecl(Friend);
17001 return Friend;
17002 }
17003
17004 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?")(static_cast <bool> (SS.isNotEmpty() && "valid templated tag with no SS and no direct?"
) ? void (0) : __assert_fail ("SS.isNotEmpty() && \"valid templated tag with no SS and no direct?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 17004, __extension__ __PRETTY_FUNCTION__
))
;
17005
17006
17007
17008 // Handle the case of a templated-scope friend class. e.g.
17009 // template <class T> class A<T>::B;
17010 // FIXME: we don't support these right now.
17011 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
17012 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
17013 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
17014 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
17015 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17016 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17017 TL.setElaboratedKeywordLoc(TagLoc);
17018 TL.setQualifierLoc(SS.getWithLocInContext(Context));
17019 TL.setNameLoc(NameLoc);
17020
17021 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17022 TSI, FriendLoc, TempParamLists);
17023 Friend->setAccess(AS_public);
17024 Friend->setUnsupportedFriend(true);
17025 CurContext->addDecl(Friend);
17026 return Friend;
17027}
17028
17029/// Handle a friend type declaration. This works in tandem with
17030/// ActOnTag.
17031///
17032/// Notes on friend class templates:
17033///
17034/// We generally treat friend class declarations as if they were
17035/// declaring a class. So, for example, the elaborated type specifier
17036/// in a friend declaration is required to obey the restrictions of a
17037/// class-head (i.e. no typedefs in the scope chain), template
17038/// parameters are required to match up with simple template-ids, &c.
17039/// However, unlike when declaring a template specialization, it's
17040/// okay to refer to a template specialization without an empty
17041/// template parameter declaration, e.g.
17042/// friend class A<T>::B<unsigned>;
17043/// We permit this as a special case; if there are any template
17044/// parameters present at all, require proper matching, i.e.
17045/// template <> template \<class T> friend class A<int>::B;
17046Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
17047 MultiTemplateParamsArg TempParams) {
17048 SourceLocation Loc = DS.getBeginLoc();
17049
17050 assert(DS.isFriendSpecified())(static_cast <bool> (DS.isFriendSpecified()) ? void (0)
: __assert_fail ("DS.isFriendSpecified()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 17050, __extension__ __PRETTY_FUNCTION__))
;
17051 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)(static_cast <bool> (DS.getStorageClassSpec() == DeclSpec
::SCS_unspecified) ? void (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_unspecified"
, "clang/lib/Sema/SemaDeclCXX.cpp", 17051, __extension__ __PRETTY_FUNCTION__
))
;
17052
17053 // C++ [class.friend]p3:
17054 // A friend declaration that does not declare a function shall have one of
17055 // the following forms:
17056 // friend elaborated-type-specifier ;
17057 // friend simple-type-specifier ;
17058 // friend typename-specifier ;
17059 //
17060 // Any declaration with a type qualifier does not have that form. (It's
17061 // legal to specify a qualified type as a friend, you just can't write the
17062 // keywords.)
17063 if (DS.getTypeQualifiers()) {
17064 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
17065 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17066 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
17067 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17068 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
17069 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17070 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
17071 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17072 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
17073 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17074 }
17075
17076 // Try to convert the decl specifier to a type. This works for
17077 // friend templates because ActOnTag never produces a ClassTemplateDecl
17078 // for a TUK_Friend.
17079 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17080 DeclaratorContext::Member);
17081 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
17082 QualType T = TSI->getType();
17083 if (TheDeclarator.isInvalidType())
17084 return nullptr;
17085
17086 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
17087 return nullptr;
17088
17089 // This is definitely an error in C++98. It's probably meant to
17090 // be forbidden in C++0x, too, but the specification is just
17091 // poorly written.
17092 //
17093 // The problem is with declarations like the following:
17094 // template <T> friend A<T>::foo;
17095 // where deciding whether a class C is a friend or not now hinges
17096 // on whether there exists an instantiation of A that causes
17097 // 'foo' to equal C. There are restrictions on class-heads
17098 // (which we declare (by fiat) elaborated friend declarations to
17099 // be) that makes this tractable.
17100 //
17101 // FIXME: handle "template <> friend class A<T>;", which
17102 // is possibly well-formed? Who even knows?
17103 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
17104 Diag(Loc, diag::err_tagless_friend_type_template)
17105 << DS.getSourceRange();
17106 return nullptr;
17107 }
17108
17109 // C++98 [class.friend]p1: A friend of a class is a function
17110 // or class that is not a member of the class . . .
17111 // This is fixed in DR77, which just barely didn't make the C++03
17112 // deadline. It's also a very silly restriction that seriously
17113 // affects inner classes and which nobody else seems to implement;
17114 // thus we never diagnose it, not even in -pedantic.
17115 //
17116 // But note that we could warn about it: it's always useless to
17117 // friend one of your own members (it's not, however, worthless to
17118 // friend a member of an arbitrary specialization of your template).
17119
17120 Decl *D;
17121 if (!TempParams.empty())
17122 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
17123 TempParams,
17124 TSI,
17125 DS.getFriendSpecLoc());
17126 else
17127 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
17128
17129 if (!D)
17130 return nullptr;
17131
17132 D->setAccess(AS_public);
17133 CurContext->addDecl(D);
17134
17135 return D;
17136}
17137
17138NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
17139 MultiTemplateParamsArg TemplateParams) {
17140 const DeclSpec &DS = D.getDeclSpec();
17141
17142 assert(DS.isFriendSpecified())(static_cast <bool> (DS.isFriendSpecified()) ? void (0)
: __assert_fail ("DS.isFriendSpecified()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 17142, __extension__ __PRETTY_FUNCTION__))
;
17143 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)(static_cast <bool> (DS.getStorageClassSpec() == DeclSpec
::SCS_unspecified) ? void (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_unspecified"
, "clang/lib/Sema/SemaDeclCXX.cpp", 17143, __extension__ __PRETTY_FUNCTION__
))
;
17144
17145 SourceLocation Loc = D.getIdentifierLoc();
17146 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17147
17148 // C++ [class.friend]p1
17149 // A friend of a class is a function or class....
17150 // Note that this sees through typedefs, which is intended.
17151 // It *doesn't* see through dependent types, which is correct
17152 // according to [temp.arg.type]p3:
17153 // If a declaration acquires a function type through a
17154 // type dependent on a template-parameter and this causes
17155 // a declaration that does not use the syntactic form of a
17156 // function declarator to have a function type, the program
17157 // is ill-formed.
17158 if (!TInfo->getType()->isFunctionType()) {
17159 Diag(Loc, diag::err_unexpected_friend);
17160
17161 // It might be worthwhile to try to recover by creating an
17162 // appropriate declaration.
17163 return nullptr;
17164 }
17165
17166 // C++ [namespace.memdef]p3
17167 // - If a friend declaration in a non-local class first declares a
17168 // class or function, the friend class or function is a member
17169 // of the innermost enclosing namespace.
17170 // - The name of the friend is not found by simple name lookup
17171 // until a matching declaration is provided in that namespace
17172 // scope (either before or after the class declaration granting
17173 // friendship).
17174 // - If a friend function is called, its name may be found by the
17175 // name lookup that considers functions from namespaces and
17176 // classes associated with the types of the function arguments.
17177 // - When looking for a prior declaration of a class or a function
17178 // declared as a friend, scopes outside the innermost enclosing
17179 // namespace scope are not considered.
17180
17181 CXXScopeSpec &SS = D.getCXXScopeSpec();
17182 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
17183 assert(NameInfo.getName())(static_cast <bool> (NameInfo.getName()) ? void (0) : __assert_fail
("NameInfo.getName()", "clang/lib/Sema/SemaDeclCXX.cpp", 17183
, __extension__ __PRETTY_FUNCTION__))
;
17184
17185 // Check for unexpanded parameter packs.
17186 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
17187 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
17188 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
17189 return nullptr;
17190
17191 // The context we found the declaration in, or in which we should
17192 // create the declaration.
17193 DeclContext *DC;
17194 Scope *DCScope = S;
17195 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17196 ForExternalRedeclaration);
17197
17198 // There are five cases here.
17199 // - There's no scope specifier and we're in a local class. Only look
17200 // for functions declared in the immediately-enclosing block scope.
17201 // We recover from invalid scope qualifiers as if they just weren't there.
17202 FunctionDecl *FunctionContainingLocalClass = nullptr;
17203 if ((SS.isInvalid() || !SS.isSet()) &&
17204 (FunctionContainingLocalClass =
17205 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17206 // C++11 [class.friend]p11:
17207 // If a friend declaration appears in a local class and the name
17208 // specified is an unqualified name, a prior declaration is
17209 // looked up without considering scopes that are outside the
17210 // innermost enclosing non-class scope. For a friend function
17211 // declaration, if there is no prior declaration, the program is
17212 // ill-formed.
17213
17214 // Find the innermost enclosing non-class scope. This is the block
17215 // scope containing the local class definition (or for a nested class,
17216 // the outer local class).
17217 DCScope = S->getFnParent();
17218
17219 // Look up the function name in the scope.
17220 Previous.clear(LookupLocalFriendName);
17221 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17222
17223 if (!Previous.empty()) {
17224 // All possible previous declarations must have the same context:
17225 // either they were declared at block scope or they are members of
17226 // one of the enclosing local classes.
17227 DC = Previous.getRepresentativeDecl()->getDeclContext();
17228 } else {
17229 // This is ill-formed, but provide the context that we would have
17230 // declared the function in, if we were permitted to, for error recovery.
17231 DC = FunctionContainingLocalClass;
17232 }
17233 adjustContextForLocalExternDecl(DC);
17234
17235 // C++ [class.friend]p6:
17236 // A function can be defined in a friend declaration of a class if and
17237 // only if the class is a non-local class (9.8), the function name is
17238 // unqualified, and the function has namespace scope.
17239 if (D.isFunctionDefinition()) {
17240 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17241 }
17242
17243 // - There's no scope specifier, in which case we just go to the
17244 // appropriate scope and look for a function or function template
17245 // there as appropriate.
17246 } else if (SS.isInvalid() || !SS.isSet()) {
17247 // C++11 [namespace.memdef]p3:
17248 // If the name in a friend declaration is neither qualified nor
17249 // a template-id and the declaration is a function or an
17250 // elaborated-type-specifier, the lookup to determine whether
17251 // the entity has been previously declared shall not consider
17252 // any scopes outside the innermost enclosing namespace.
17253 bool isTemplateId =
17254 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17255
17256 // Find the appropriate context according to the above.
17257 DC = CurContext;
17258
17259 // Skip class contexts. If someone can cite chapter and verse
17260 // for this behavior, that would be nice --- it's what GCC and
17261 // EDG do, and it seems like a reasonable intent, but the spec
17262 // really only says that checks for unqualified existing
17263 // declarations should stop at the nearest enclosing namespace,
17264 // not that they should only consider the nearest enclosing
17265 // namespace.
17266 while (DC->isRecord())
17267 DC = DC->getParent();
17268
17269 DeclContext *LookupDC = DC->getNonTransparentContext();
17270 while (true) {
17271 LookupQualifiedName(Previous, LookupDC);
17272
17273 if (!Previous.empty()) {
17274 DC = LookupDC;
17275 break;
17276 }
17277
17278 if (isTemplateId) {
17279 if (isa<TranslationUnitDecl>(LookupDC)) break;
17280 } else {
17281 if (LookupDC->isFileContext()) break;
17282 }
17283 LookupDC = LookupDC->getParent();
17284 }
17285
17286 DCScope = getScopeForDeclContext(S, DC);
17287
17288 // - There's a non-dependent scope specifier, in which case we
17289 // compute it and do a previous lookup there for a function
17290 // or function template.
17291 } else if (!SS.getScopeRep()->isDependent()) {
17292 DC = computeDeclContext(SS);
17293 if (!DC) return nullptr;
17294
17295 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17296
17297 LookupQualifiedName(Previous, DC);
17298
17299 // C++ [class.friend]p1: A friend of a class is a function or
17300 // class that is not a member of the class . . .
17301 if (DC->Equals(CurContext))
17302 Diag(DS.getFriendSpecLoc(),
17303 getLangOpts().CPlusPlus11 ?
17304 diag::warn_cxx98_compat_friend_is_member :
17305 diag::err_friend_is_member);
17306
17307 if (D.isFunctionDefinition()) {
17308 // C++ [class.friend]p6:
17309 // A function can be defined in a friend declaration of a class if and
17310 // only if the class is a non-local class (9.8), the function name is
17311 // unqualified, and the function has namespace scope.
17312 //
17313 // FIXME: We should only do this if the scope specifier names the
17314 // innermost enclosing namespace; otherwise the fixit changes the
17315 // meaning of the code.
17316 SemaDiagnosticBuilder DB
17317 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17318
17319 DB << SS.getScopeRep();
17320 if (DC->isFileContext())
17321 DB << FixItHint::CreateRemoval(SS.getRange());
17322 SS.clear();
17323 }
17324
17325 // - There's a scope specifier that does not match any template
17326 // parameter lists, in which case we use some arbitrary context,
17327 // create a method or method template, and wait for instantiation.
17328 // - There's a scope specifier that does match some template
17329 // parameter lists, which we don't handle right now.
17330 } else {
17331 if (D.isFunctionDefinition()) {
17332 // C++ [class.friend]p6:
17333 // A function can be defined in a friend declaration of a class if and
17334 // only if the class is a non-local class (9.8), the function name is
17335 // unqualified, and the function has namespace scope.
17336 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
17337 << SS.getScopeRep();
17338 }
17339
17340 DC = CurContext;
17341 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?")(static_cast <bool> (isa<CXXRecordDecl>(DC) &&
"friend declaration not in class?") ? void (0) : __assert_fail
("isa<CXXRecordDecl>(DC) && \"friend declaration not in class?\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 17341, __extension__ __PRETTY_FUNCTION__
))
;
17342 }
17343
17344 if (!DC->isRecord()) {
17345 int DiagArg = -1;
17346 switch (D.getName().getKind()) {
17347 case UnqualifiedIdKind::IK_ConstructorTemplateId:
17348 case UnqualifiedIdKind::IK_ConstructorName:
17349 DiagArg = 0;
17350 break;
17351 case UnqualifiedIdKind::IK_DestructorName:
17352 DiagArg = 1;
17353 break;
17354 case UnqualifiedIdKind::IK_ConversionFunctionId:
17355 DiagArg = 2;
17356 break;
17357 case UnqualifiedIdKind::IK_DeductionGuideName:
17358 DiagArg = 3;
17359 break;
17360 case UnqualifiedIdKind::IK_Identifier:
17361 case UnqualifiedIdKind::IK_ImplicitSelfParam:
17362 case UnqualifiedIdKind::IK_LiteralOperatorId:
17363 case UnqualifiedIdKind::IK_OperatorFunctionId:
17364 case UnqualifiedIdKind::IK_TemplateId:
17365 break;
17366 }
17367 // This implies that it has to be an operator or function.
17368 if (DiagArg >= 0) {
17369 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17370 return nullptr;
17371 }
17372 }
17373
17374 // FIXME: This is an egregious hack to cope with cases where the scope stack
17375 // does not contain the declaration context, i.e., in an out-of-line
17376 // definition of a class.
17377 Scope FakeDCScope(S, Scope::DeclScope, Diags);
17378 if (!DCScope) {
17379 FakeDCScope.setEntity(DC);
17380 DCScope = &FakeDCScope;
17381 }
17382
17383 bool AddToScope = true;
17384 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17385 TemplateParams, AddToScope);
17386 if (!ND) return nullptr;
17387
17388 assert(ND->getLexicalDeclContext() == CurContext)(static_cast <bool> (ND->getLexicalDeclContext() == CurContext
) ? void (0) : __assert_fail ("ND->getLexicalDeclContext() == CurContext"
, "clang/lib/Sema/SemaDeclCXX.cpp", 17388, __extension__ __PRETTY_FUNCTION__
))
;
17389
17390 // If we performed typo correction, we might have added a scope specifier
17391 // and changed the decl context.
17392 DC = ND->getDeclContext();
17393
17394 // Add the function declaration to the appropriate lookup tables,
17395 // adjusting the redeclarations list as necessary. We don't
17396 // want to do this yet if the friending class is dependent.
17397 //
17398 // Also update the scope-based lookup if the target context's
17399 // lookup context is in lexical scope.
17400 if (!CurContext->isDependentContext()) {
17401 DC = DC->getRedeclContext();
17402 DC->makeDeclVisibleInContext(ND);
17403 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17404 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17405 }
17406
17407 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
17408 D.getIdentifierLoc(), ND,
17409 DS.getFriendSpecLoc());
17410 FrD->setAccess(AS_public);
17411 CurContext->addDecl(FrD);
17412
17413 if (ND->isInvalidDecl()) {
17414 FrD->setInvalidDecl();
17415 } else {
17416 if (DC->isRecord()) CheckFriendAccess(ND);
17417
17418 FunctionDecl *FD;
17419 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17420 FD = FTD->getTemplatedDecl();
17421 else
17422 FD = cast<FunctionDecl>(ND);
17423
17424 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17425 // default argument expression, that declaration shall be a definition
17426 // and shall be the only declaration of the function or function
17427 // template in the translation unit.
17428 if (functionDeclHasDefaultArgument(FD)) {
17429 // We can't look at FD->getPreviousDecl() because it may not have been set
17430 // if we're in a dependent context. If the function is known to be a
17431 // redeclaration, we will have narrowed Previous down to the right decl.
17432 if (D.isRedeclaration()) {
17433 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17434 Diag(Previous.getRepresentativeDecl()->getLocation(),
17435 diag::note_previous_declaration);
17436 } else if (!D.isFunctionDefinition())
17437 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17438 }
17439
17440 // Mark templated-scope function declarations as unsupported.
17441 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17442 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17443 << SS.getScopeRep() << SS.getRange()
17444 << cast<CXXRecordDecl>(CurContext);
17445 FrD->setUnsupportedFriend(true);
17446 }
17447 }
17448
17449 warnOnReservedIdentifier(ND);
17450
17451 return ND;
17452}
17453
17454void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
17455 AdjustDeclIfTemplate(Dcl);
17456
17457 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17458 if (!Fn) {
17459 Diag(DelLoc, diag::err_deleted_non_function);
17460 return;
17461 }
17462
17463 // Deleted function does not have a body.
17464 Fn->setWillHaveBody(false);
17465
17466 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17467 // Don't consider the implicit declaration we generate for explicit
17468 // specializations. FIXME: Do not generate these implicit declarations.
17469 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17470 Prev->getPreviousDecl()) &&
17471 !Prev->isDefined()) {
17472 Diag(DelLoc, diag::err_deleted_decl_not_first);
17473 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17474 Prev->isImplicit() ? diag::note_previous_implicit_declaration
17475 : diag::note_previous_declaration);
17476 // We can't recover from this; the declaration might have already
17477 // been used.
17478 Fn->setInvalidDecl();
17479 return;
17480 }
17481
17482 // To maintain the invariant that functions are only deleted on their first
17483 // declaration, mark the implicitly-instantiated declaration of the
17484 // explicitly-specialized function as deleted instead of marking the
17485 // instantiated redeclaration.
17486 Fn = Fn->getCanonicalDecl();
17487 }
17488
17489 // dllimport/dllexport cannot be deleted.
17490 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17491 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17492 Fn->setInvalidDecl();
17493 }
17494
17495 // C++11 [basic.start.main]p3:
17496 // A program that defines main as deleted [...] is ill-formed.
17497 if (Fn->isMain())
17498 Diag(DelLoc, diag::err_deleted_main);
17499
17500 // C++11 [dcl.fct.def.delete]p4:
17501 // A deleted function is implicitly inline.
17502 Fn->setImplicitlyInline();
17503 Fn->setDeletedAsWritten();
17504}
17505
17506void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17507 if (!Dcl || Dcl->isInvalidDecl())
17508 return;
17509
17510 auto *FD = dyn_cast<FunctionDecl>(Dcl);
17511 if (!FD) {
17512 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17513 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17514 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17515 return;
17516 }
17517 }
17518
17519 Diag(DefaultLoc, diag::err_default_special_members)
17520 << getLangOpts().CPlusPlus20;
17521 return;
17522 }
17523
17524 // Reject if this can't possibly be a defaultable function.
17525 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17526 if (!DefKind &&
17527 // A dependent function that doesn't locally look defaultable can
17528 // still instantiate to a defaultable function if it's a constructor
17529 // or assignment operator.
17530 (!FD->isDependentContext() ||
17531 (!isa<CXXConstructorDecl>(FD) &&
17532 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17533 Diag(DefaultLoc, diag::err_default_special_members)
17534 << getLangOpts().CPlusPlus20;
17535 return;
17536 }
17537
17538 // Issue compatibility warning. We already warned if the operator is
17539 // 'operator<=>' when parsing the '<=>' token.
17540 if (DefKind.isComparison() &&
17541 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17542 Diag(DefaultLoc, getLangOpts().CPlusPlus20
17543 ? diag::warn_cxx17_compat_defaulted_comparison
17544 : diag::ext_defaulted_comparison);
17545 }
17546
17547 FD->setDefaulted();
17548 FD->setExplicitlyDefaulted();
17549 FD->setDefaultLoc(DefaultLoc);
17550
17551 // Defer checking functions that are defaulted in a dependent context.
17552 if (FD->isDependentContext())
17553 return;
17554
17555 // Unset that we will have a body for this function. We might not,
17556 // if it turns out to be trivial, and we don't need this marking now
17557 // that we've marked it as defaulted.
17558 FD->setWillHaveBody(false);
17559
17560 if (DefKind.isComparison()) {
17561 // If this comparison's defaulting occurs within the definition of its
17562 // lexical class context, we have to do the checking when complete.
17563 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
17564 if (!RD->isCompleteDefinition())
17565 return;
17566 }
17567
17568 // If this member fn was defaulted on its first declaration, we will have
17569 // already performed the checking in CheckCompletedCXXClass. Such a
17570 // declaration doesn't trigger an implicit definition.
17571 if (isa<CXXMethodDecl>(FD)) {
17572 const FunctionDecl *Primary = FD;
17573 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17574 // Ask the template instantiation pattern that actually had the
17575 // '= default' on it.
17576 Primary = Pattern;
17577 if (Primary->getCanonicalDecl()->isDefaulted())
17578 return;
17579 }
17580
17581 if (DefKind.isComparison()) {
17582 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
17583 FD->setInvalidDecl();
17584 else
17585 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
17586 } else {
17587 auto *MD = cast<CXXMethodDecl>(FD);
17588
17589 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember(),
17590 DefaultLoc))
17591 MD->setInvalidDecl();
17592 else
17593 DefineDefaultedFunction(*this, MD, DefaultLoc);
17594 }
17595}
17596
17597static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17598 for (Stmt *SubStmt : S->children()) {
17599 if (!SubStmt)
17600 continue;
17601 if (isa<ReturnStmt>(SubStmt))
17602 Self.Diag(SubStmt->getBeginLoc(),
17603 diag::err_return_in_constructor_handler);
17604 if (!isa<Expr>(SubStmt))
17605 SearchForReturnInStmt(Self, SubStmt);
17606 }
17607}
17608
17609void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
17610 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17611 CXXCatchStmt *Handler = TryBlock->getHandler(I);
17612 SearchForReturnInStmt(*this, Handler);
17613 }
17614}
17615
17616void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
17617 FnBodyKind BodyKind) {
17618 switch (BodyKind) {
17619 case FnBodyKind::Delete:
17620 SetDeclDeleted(D, Loc);
17621 break;
17622 case FnBodyKind::Default:
17623 SetDeclDefaulted(D, Loc);
17624 break;
17625 case FnBodyKind::Other:
17626 llvm_unreachable(::llvm::llvm_unreachable_internal("Parsed function body should be '= delete;' or '= default;'"
, "clang/lib/Sema/SemaDeclCXX.cpp", 17627)
17627 "Parsed function body should be '= delete;' or '= default;'")::llvm::llvm_unreachable_internal("Parsed function body should be '= delete;' or '= default;'"
, "clang/lib/Sema/SemaDeclCXX.cpp", 17627)
;
17628 }
17629}
17630
17631bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
17632 const CXXMethodDecl *Old) {
17633 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17634 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17635
17636 if (OldFT->hasExtParameterInfos()) {
17637 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17638 // A parameter of the overriding method should be annotated with noescape
17639 // if the corresponding parameter of the overridden method is annotated.
17640 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17641 !NewFT->getExtParameterInfo(I).isNoEscape()) {
17642 Diag(New->getParamDecl(I)->getLocation(),
17643 diag::warn_overriding_method_missing_noescape);
17644 Diag(Old->getParamDecl(I)->getLocation(),
17645 diag::note_overridden_marked_noescape);
17646 }
17647 }
17648
17649 // Virtual overrides must have the same code_seg.
17650 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17651 const auto *NewCSA = New->getAttr<CodeSegAttr>();
17652 if ((NewCSA || OldCSA) &&
17653 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17654 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17655 Diag(Old->getLocation(), diag::note_previous_declaration);
17656 return true;
17657 }
17658
17659 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17660
17661 // If the calling conventions match, everything is fine
17662 if (NewCC == OldCC)
17663 return false;
17664
17665 // If the calling conventions mismatch because the new function is static,
17666 // suppress the calling convention mismatch error; the error about static
17667 // function override (err_static_overrides_virtual from
17668 // Sema::CheckFunctionDeclaration) is more clear.
17669 if (New->getStorageClass() == SC_Static)
17670 return false;
17671
17672 Diag(New->getLocation(),
17673 diag::err_conflicting_overriding_cc_attributes)
17674 << New->getDeclName() << New->getType() << Old->getType();
17675 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
17676 return true;
17677}
17678
17679bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
17680 const CXXMethodDecl *Old) {
17681 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17682 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17683
17684 if (Context.hasSameType(NewTy, OldTy) ||
17685 NewTy->isDependentType() || OldTy->isDependentType())
17686 return false;
17687
17688 // Check if the return types are covariant
17689 QualType NewClassTy, OldClassTy;
17690
17691 /// Both types must be pointers or references to classes.
17692 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17693 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17694 NewClassTy = NewPT->getPointeeType();
17695 OldClassTy = OldPT->getPointeeType();
17696 }
17697 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17698 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17699 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17700 NewClassTy = NewRT->getPointeeType();
17701 OldClassTy = OldRT->getPointeeType();
17702 }
17703 }
17704 }
17705
17706 // The return types aren't either both pointers or references to a class type.
17707 if (NewClassTy.isNull()) {
17708 Diag(New->getLocation(),
17709 diag::err_different_return_type_for_overriding_virtual_function)
17710 << New->getDeclName() << NewTy << OldTy
17711 << New->getReturnTypeSourceRange();
17712 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17713 << Old->getReturnTypeSourceRange();
17714
17715 return true;
17716 }
17717
17718 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17719 // C++14 [class.virtual]p8:
17720 // If the class type in the covariant return type of D::f differs from
17721 // that of B::f, the class type in the return type of D::f shall be
17722 // complete at the point of declaration of D::f or shall be the class
17723 // type D.
17724 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17725 if (!RT->isBeingDefined() &&
17726 RequireCompleteType(New->getLocation(), NewClassTy,
17727 diag::err_covariant_return_incomplete,
17728 New->getDeclName()))
17729 return true;
17730 }
17731
17732 // Check if the new class derives from the old class.
17733 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17734 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17735 << New->getDeclName() << NewTy << OldTy
17736 << New->getReturnTypeSourceRange();
17737 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17738 << Old->getReturnTypeSourceRange();
17739 return true;
17740 }
17741
17742 // Check if we the conversion from derived to base is valid.
17743 if (CheckDerivedToBaseConversion(
17744 NewClassTy, OldClassTy,
17745 diag::err_covariant_return_inaccessible_base,
17746 diag::err_covariant_return_ambiguous_derived_to_base_conv,
17747 New->getLocation(), New->getReturnTypeSourceRange(),
17748 New->getDeclName(), nullptr)) {
17749 // FIXME: this note won't trigger for delayed access control
17750 // diagnostics, and it's impossible to get an undelayed error
17751 // here from access control during the original parse because
17752 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17753 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17754 << Old->getReturnTypeSourceRange();
17755 return true;
17756 }
17757 }
17758
17759 // The qualifiers of the return types must be the same.
17760 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17761 Diag(New->getLocation(),
17762 diag::err_covariant_return_type_different_qualifications)
17763 << New->getDeclName() << NewTy << OldTy
17764 << New->getReturnTypeSourceRange();
17765 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17766 << Old->getReturnTypeSourceRange();
17767 return true;
17768 }
17769
17770
17771 // The new class type must have the same or less qualifiers as the old type.
17772 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17773 Diag(New->getLocation(),
17774 diag::err_covariant_return_type_class_type_more_qualified)
17775 << New->getDeclName() << NewTy << OldTy
17776 << New->getReturnTypeSourceRange();
17777 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17778 << Old->getReturnTypeSourceRange();
17779 return true;
17780 }
17781
17782 return false;
17783}
17784
17785/// Mark the given method pure.
17786///
17787/// \param Method the method to be marked pure.
17788///
17789/// \param InitRange the source range that covers the "0" initializer.
17790bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17791 SourceLocation EndLoc = InitRange.getEnd();
17792 if (EndLoc.isValid())
17793 Method->setRangeEnd(EndLoc);
17794
17795 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17796 Method->setPure();
17797 return false;
17798 }
17799
17800 if (!Method->isInvalidDecl())
17801 Diag(Method->getLocation(), diag::err_non_virtual_pure)
17802 << Method->getDeclName() << InitRange;
17803 return true;
17804}
17805
17806void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17807 if (D->getFriendObjectKind())
17808 Diag(D->getLocation(), diag::err_pure_friend);
17809 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17810 CheckPureMethod(M, ZeroLoc);
17811 else
17812 Diag(D->getLocation(), diag::err_illegal_initializer);
17813}
17814
17815/// Determine whether the given declaration is a global variable or
17816/// static data member.
17817static bool isNonlocalVariable(const Decl *D) {
17818 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17819 return Var->hasGlobalStorage();
17820
17821 return false;
17822}
17823
17824/// Invoked when we are about to parse an initializer for the declaration
17825/// 'Dcl'.
17826///
17827/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17828/// static data member of class X, names should be looked up in the scope of
17829/// class X. If the declaration had a scope specifier, a scope will have
17830/// been created and passed in for this purpose. Otherwise, S will be null.
17831void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17832 // If there is no declaration, there was an error parsing it.
17833 if (!D || D->isInvalidDecl())
17834 return;
17835
17836 // We will always have a nested name specifier here, but this declaration
17837 // might not be out of line if the specifier names the current namespace:
17838 // extern int n;
17839 // int ::n = 0;
17840 if (S && D->isOutOfLine())
17841 EnterDeclaratorContext(S, D->getDeclContext());
17842
17843 // If we are parsing the initializer for a static data member, push a
17844 // new expression evaluation context that is associated with this static
17845 // data member.
17846 if (isNonlocalVariable(D))
17847 PushExpressionEvaluationContext(
17848 ExpressionEvaluationContext::PotentiallyEvaluated, D);
17849}
17850
17851/// Invoked after we are finished parsing an initializer for the declaration D.
17852void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17853 // If there is no declaration, there was an error parsing it.
17854 if (!D || D->isInvalidDecl())
17855 return;
17856
17857 if (isNonlocalVariable(D))
17858 PopExpressionEvaluationContext();
17859
17860 if (S && D->isOutOfLine())
17861 ExitDeclaratorContext(S);
17862}
17863
17864/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17865/// C++ if/switch/while/for statement.
17866/// e.g: "if (int x = f()) {...}"
17867DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17868 // C++ 6.4p2:
17869 // The declarator shall not specify a function or an array.
17870 // The type-specifier-seq shall not contain typedef and shall not declare a
17871 // new class or enumeration.
17872 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&(static_cast <bool> (D.getDeclSpec().getStorageClassSpec
() != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class of condition decl."
) ? void (0) : __assert_fail ("D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class of condition decl.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 17873, __extension__ __PRETTY_FUNCTION__
))
17873 "Parser allowed 'typedef' as storage class of condition decl.")(static_cast <bool> (D.getDeclSpec().getStorageClassSpec
() != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class of condition decl."
) ? void (0) : __assert_fail ("D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class of condition decl.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 17873, __extension__ __PRETTY_FUNCTION__
))
;
17874
17875 Decl *Dcl = ActOnDeclarator(S, D);
17876 if (!Dcl)
17877 return true;
17878
17879 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17880 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17881 << D.getSourceRange();
17882 return true;
17883 }
17884
17885 return Dcl;
17886}
17887
17888void Sema::LoadExternalVTableUses() {
17889 if (!ExternalSource)
17890 return;
17891
17892 SmallVector<ExternalVTableUse, 4> VTables;
17893 ExternalSource->ReadUsedVTables(VTables);
17894 SmallVector<VTableUse, 4> NewUses;
17895 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17896 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17897 = VTablesUsed.find(VTables[I].Record);
17898 // Even if a definition wasn't required before, it may be required now.
17899 if (Pos != VTablesUsed.end()) {
17900 if (!Pos->second && VTables[I].DefinitionRequired)
17901 Pos->second = true;
17902 continue;
17903 }
17904
17905 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17906 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17907 }
17908
17909 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17910}
17911
17912void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17913 bool DefinitionRequired) {
17914 // Ignore any vtable uses in unevaluated operands or for classes that do
17915 // not have a vtable.
17916 if (!Class->isDynamicClass() || Class->isDependentContext() ||
17917 CurContext->isDependentContext() || isUnevaluatedContext())
17918 return;
17919 // Do not mark as used if compiling for the device outside of the target
17920 // region.
17921 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17922 !isInOpenMPDeclareTargetContext() &&
17923 !isInOpenMPTargetExecutionDirective()) {
17924 if (!DefinitionRequired)
17925 MarkVirtualMembersReferenced(Loc, Class);
17926 return;
17927 }
17928
17929 // Try to insert this class into the map.
17930 LoadExternalVTableUses();
17931 Class = Class->getCanonicalDecl();
17932 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17933 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17934 if (!Pos.second) {
17935 // If we already had an entry, check to see if we are promoting this vtable
17936 // to require a definition. If so, we need to reappend to the VTableUses
17937 // list, since we may have already processed the first entry.
17938 if (DefinitionRequired && !Pos.first->second) {
17939 Pos.first->second = true;
17940 } else {
17941 // Otherwise, we can early exit.
17942 return;
17943 }
17944 } else {
17945 // The Microsoft ABI requires that we perform the destructor body
17946 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17947 // the deleting destructor is emitted with the vtable, not with the
17948 // destructor definition as in the Itanium ABI.
17949 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17950 CXXDestructorDecl *DD = Class->getDestructor();
17951 if (DD && DD->isVirtual() && !DD->isDeleted()) {
17952 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17953 // If this is an out-of-line declaration, marking it referenced will
17954 // not do anything. Manually call CheckDestructor to look up operator
17955 // delete().
17956 ContextRAII SavedContext(*this, DD);
17957 CheckDestructor(DD);
17958 } else {
17959 MarkFunctionReferenced(Loc, Class->getDestructor());
17960 }
17961 }
17962 }
17963 }
17964
17965 // Local classes need to have their virtual members marked
17966 // immediately. For all other classes, we mark their virtual members
17967 // at the end of the translation unit.
17968 if (Class->isLocalClass())
17969 MarkVirtualMembersReferenced(Loc, Class);
17970 else
17971 VTableUses.push_back(std::make_pair(Class, Loc));
17972}
17973
17974bool Sema::DefineUsedVTables() {
17975 LoadExternalVTableUses();
17976 if (VTableUses.empty())
17977 return false;
17978
17979 // Note: The VTableUses vector could grow as a result of marking
17980 // the members of a class as "used", so we check the size each
17981 // time through the loop and prefer indices (which are stable) to
17982 // iterators (which are not).
17983 bool DefinedAnything = false;
17984 for (unsigned I = 0; I != VTableUses.size(); ++I) {
17985 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17986 if (!Class)
17987 continue;
17988 TemplateSpecializationKind ClassTSK =
17989 Class->getTemplateSpecializationKind();
17990
17991 SourceLocation Loc = VTableUses[I].second;
17992
17993 bool DefineVTable = true;
17994
17995 // If this class has a key function, but that key function is
17996 // defined in another translation unit, we don't need to emit the
17997 // vtable even though we're using it.
17998 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17999 if (KeyFunction && !KeyFunction->hasBody()) {
18000 // The key function is in another translation unit.
18001 DefineVTable = false;
18002 TemplateSpecializationKind TSK =
18003 KeyFunction->getTemplateSpecializationKind();
18004 assert(TSK != TSK_ExplicitInstantiationDefinition &&(static_cast <bool> (TSK != TSK_ExplicitInstantiationDefinition
&& TSK != TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? void (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 18006, __extension__ __PRETTY_FUNCTION__
))
18005 TSK != TSK_ImplicitInstantiation &&(static_cast <bool> (TSK != TSK_ExplicitInstantiationDefinition
&& TSK != TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? void (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 18006, __extension__ __PRETTY_FUNCTION__
))
18006 "Instantiations don't have key functions")(static_cast <bool> (TSK != TSK_ExplicitInstantiationDefinition
&& TSK != TSK_ImplicitInstantiation && "Instantiations don't have key functions"
) ? void (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 18006, __extension__ __PRETTY_FUNCTION__
))
;
18007 (void)TSK;
18008 } else if (!KeyFunction) {
18009 // If we have a class with no key function that is the subject
18010 // of an explicit instantiation declaration, suppress the
18011 // vtable; it will live with the explicit instantiation
18012 // definition.
18013 bool IsExplicitInstantiationDeclaration =
18014 ClassTSK == TSK_ExplicitInstantiationDeclaration;
18015 for (auto *R : Class->redecls()) {
18016 TemplateSpecializationKind TSK
18017 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18018 if (TSK == TSK_ExplicitInstantiationDeclaration)
18019 IsExplicitInstantiationDeclaration = true;
18020 else if (TSK == TSK_ExplicitInstantiationDefinition) {
18021 IsExplicitInstantiationDeclaration = false;
18022 break;
18023 }
18024 }
18025
18026 if (IsExplicitInstantiationDeclaration)
18027 DefineVTable = false;
18028 }
18029
18030 // The exception specifications for all virtual members may be needed even
18031 // if we are not providing an authoritative form of the vtable in this TU.
18032 // We may choose to emit it available_externally anyway.
18033 if (!DefineVTable) {
18034 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
18035 continue;
18036 }
18037
18038 // Mark all of the virtual members of this class as referenced, so
18039 // that we can build a vtable. Then, tell the AST consumer that a
18040 // vtable for this class is required.
18041 DefinedAnything = true;
18042 MarkVirtualMembersReferenced(Loc, Class);
18043 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18044 if (VTablesUsed[Canonical])
18045 Consumer.HandleVTable(Class);
18046
18047 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18048 // no key function or the key function is inlined. Don't warn in C++ ABIs
18049 // that lack key functions, since the user won't be able to make one.
18050 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
18051 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18052 ClassTSK != TSK_ExplicitInstantiationDefinition) {
18053 const FunctionDecl *KeyFunctionDef = nullptr;
18054 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18055 KeyFunctionDef->isInlined()))
18056 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18057 }
18058 }
18059 VTableUses.clear();
18060
18061 return DefinedAnything;
18062}
18063
18064void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
18065 const CXXRecordDecl *RD) {
18066 for (const auto *I : RD->methods())
18067 if (I->isVirtual() && !I->isPure())
18068 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18069}
18070
18071void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
18072 const CXXRecordDecl *RD,
18073 bool ConstexprOnly) {
18074 // Mark all functions which will appear in RD's vtable as used.
18075 CXXFinalOverriderMap FinalOverriders;
18076 RD->getFinalOverriders(FinalOverriders);
18077 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18078 E = FinalOverriders.end();
18079 I != E; ++I) {
18080 for (OverridingMethods::const_iterator OI = I->second.begin(),
18081 OE = I->second.end();
18082 OI != OE; ++OI) {
18083 assert(OI->second.size() > 0 && "no final overrider")(static_cast <bool> (OI->second.size() > 0 &&
"no final overrider") ? void (0) : __assert_fail ("OI->second.size() > 0 && \"no final overrider\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 18083, __extension__ __PRETTY_FUNCTION__
))
;
18084 CXXMethodDecl *Overrider = OI->second.front().Method;
18085
18086 // C++ [basic.def.odr]p2:
18087 // [...] A virtual member function is used if it is not pure. [...]
18088 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
18089 MarkFunctionReferenced(Loc, Overrider);
18090 }
18091 }
18092
18093 // Only classes that have virtual bases need a VTT.
18094 if (RD->getNumVBases() == 0)
18095 return;
18096
18097 for (const auto &I : RD->bases()) {
18098 const auto *Base =
18099 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18100 if (Base->getNumVBases() == 0)
18101 continue;
18102 MarkVirtualMembersReferenced(Loc, Base);
18103 }
18104}
18105
18106/// SetIvarInitializers - This routine builds initialization ASTs for the
18107/// Objective-C implementation whose ivars need be initialized.
18108void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
18109 if (!getLangOpts().CPlusPlus)
18110 return;
18111 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
18112 SmallVector<ObjCIvarDecl*, 8> ivars;
18113 CollectIvarsToConstructOrDestruct(OID, ivars);
18114 if (ivars.empty())
18115 return;
18116 SmallVector<CXXCtorInitializer*, 32> AllToInit;
18117 for (unsigned i = 0; i < ivars.size(); i++) {
18118 FieldDecl *Field = ivars[i];
18119 if (Field->isInvalidDecl())
18120 continue;
18121
18122 CXXCtorInitializer *Member;
18123 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
18124 InitializationKind InitKind =
18125 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
18126
18127 InitializationSequence InitSeq(*this, InitEntity, InitKind, std::nullopt);
18128 ExprResult MemberInit =
18129 InitSeq.Perform(*this, InitEntity, InitKind, std::nullopt);
18130 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
18131 // Note, MemberInit could actually come back empty if no initialization
18132 // is required (e.g., because it would call a trivial default constructor)
18133 if (!MemberInit.get() || MemberInit.isInvalid())
18134 continue;
18135
18136 Member =
18137 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
18138 SourceLocation(),
18139 MemberInit.getAs<Expr>(),
18140 SourceLocation());
18141 AllToInit.push_back(Member);
18142
18143 // Be sure that the destructor is accessible and is marked as referenced.
18144 if (const RecordType *RecordTy =
18145 Context.getBaseElementType(Field->getType())
18146 ->getAs<RecordType>()) {
18147 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
18148 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
18149 MarkFunctionReferenced(Field->getLocation(), Destructor);
18150 CheckDestructorAccess(Field->getLocation(), Destructor,
18151 PDiag(diag::err_access_dtor_ivar)
18152 << Context.getBaseElementType(Field->getType()));
18153 }
18154 }
18155 }
18156 ObjCImplementation->setIvarInitializers(Context,
18157 AllToInit.data(), AllToInit.size());
18158 }
18159}
18160
18161static
18162void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
18163 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
18164 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
18165 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
18166 Sema &S) {
18167 if (Ctor->isInvalidDecl())
18168 return;
18169
18170 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
18171
18172 // Target may not be determinable yet, for instance if this is a dependent
18173 // call in an uninstantiated template.
18174 if (Target) {
18175 const FunctionDecl *FNTarget = nullptr;
18176 (void)Target->hasBody(FNTarget);
18177 Target = const_cast<CXXConstructorDecl*>(
18178 cast_or_null<CXXConstructorDecl>(FNTarget));
18179 }
18180
18181 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18182 // Avoid dereferencing a null pointer here.
18183 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18184
18185 if (!Current.insert(Canonical).second)
18186 return;
18187
18188 // We know that beyond here, we aren't chaining into a cycle.
18189 if (!Target || !Target->isDelegatingConstructor() ||
18190 Target->isInvalidDecl() || Valid.count(TCanonical)) {
18191 Valid.insert(Current.begin(), Current.end());
18192 Current.clear();
18193 // We've hit a cycle.
18194 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18195 Current.count(TCanonical)) {
18196 // If we haven't diagnosed this cycle yet, do so now.
18197 if (!Invalid.count(TCanonical)) {
18198 S.Diag((*Ctor->init_begin())->getSourceLocation(),
18199 diag::warn_delegating_ctor_cycle)
18200 << Ctor;
18201
18202 // Don't add a note for a function delegating directly to itself.
18203 if (TCanonical != Canonical)
18204 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18205
18206 CXXConstructorDecl *C = Target;
18207 while (C->getCanonicalDecl() != Canonical) {
18208 const FunctionDecl *FNTarget = nullptr;
18209 (void)C->getTargetConstructor()->hasBody(FNTarget);
18210 assert(FNTarget && "Ctor cycle through bodiless function")(static_cast <bool> (FNTarget && "Ctor cycle through bodiless function"
) ? void (0) : __assert_fail ("FNTarget && \"Ctor cycle through bodiless function\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 18210, __extension__ __PRETTY_FUNCTION__
))
;
18211
18212 C = const_cast<CXXConstructorDecl*>(
18213 cast<CXXConstructorDecl>(FNTarget));
18214 S.Diag(C->getLocation(), diag::note_which_delegates_to);
18215 }
18216 }
18217
18218 Invalid.insert(Current.begin(), Current.end());
18219 Current.clear();
18220 } else {
18221 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18222 }
18223}
18224
18225
18226void Sema::CheckDelegatingCtorCycles() {
18227 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
18228
18229 for (DelegatingCtorDeclsType::iterator
18230 I = DelegatingCtorDecls.begin(ExternalSource.get()),
18231 E = DelegatingCtorDecls.end();
18232 I != E; ++I)
18233 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18234
18235 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18236 (*CI)->setInvalidDecl();
18237}
18238
18239namespace {
18240 /// AST visitor that finds references to the 'this' expression.
18241 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18242 Sema &S;
18243
18244 public:
18245 explicit FindCXXThisExpr(Sema &S) : S(S) { }
18246
18247 bool VisitCXXThisExpr(CXXThisExpr *E) {
18248 S.Diag(E->getLocation(), diag::err_this_static_member_func)
18249 << E->isImplicit();
18250 return false;
18251 }
18252 };
18253}
18254
18255bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
18256 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18257 if (!TSInfo)
18258 return false;
18259
18260 TypeLoc TL = TSInfo->getTypeLoc();
18261 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18262 if (!ProtoTL)
18263 return false;
18264
18265 // C++11 [expr.prim.general]p3:
18266 // [The expression this] shall not appear before the optional
18267 // cv-qualifier-seq and it shall not appear within the declaration of a
18268 // static member function (although its type and value category are defined
18269 // within a static member function as they are within a non-static member
18270 // function). [ Note: this is because declaration matching does not occur
18271 // until the complete declarator is known. - end note ]
18272 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18273 FindCXXThisExpr Finder(*this);
18274
18275 // If the return type came after the cv-qualifier-seq, check it now.
18276 if (Proto->hasTrailingReturn() &&
18277 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18278 return true;
18279
18280 // Check the exception specification.
18281 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18282 return true;
18283
18284 // Check the trailing requires clause
18285 if (Expr *E = Method->getTrailingRequiresClause())
18286 if (!Finder.TraverseStmt(E))
18287 return true;
18288
18289 return checkThisInStaticMemberFunctionAttributes(Method);
18290}
18291
18292bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
18293 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18294 if (!TSInfo)
18295 return false;
18296
18297 TypeLoc TL = TSInfo->getTypeLoc();
18298 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18299 if (!ProtoTL)
18300 return false;
18301
18302 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18303 FindCXXThisExpr Finder(*this);
18304
18305 switch (Proto->getExceptionSpecType()) {
18306 case EST_Unparsed:
18307 case EST_Uninstantiated:
18308 case EST_Unevaluated:
18309 case EST_BasicNoexcept:
18310 case EST_NoThrow:
18311 case EST_DynamicNone:
18312 case EST_MSAny:
18313 case EST_None:
18314 break;
18315
18316 case EST_DependentNoexcept:
18317 case EST_NoexceptFalse:
18318 case EST_NoexceptTrue:
18319 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18320 return true;
18321 [[fallthrough]];
18322
18323 case EST_Dynamic:
18324 for (const auto &E : Proto->exceptions()) {
18325 if (!Finder.TraverseType(E))
18326 return true;
18327 }
18328 break;
18329 }
18330
18331 return false;
18332}
18333
18334bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
18335 FindCXXThisExpr Finder(*this);
18336
18337 // Check attributes.
18338 for (const auto *A : Method->attrs()) {
18339 // FIXME: This should be emitted by tblgen.
18340 Expr *Arg = nullptr;
18341 ArrayRef<Expr *> Args;
18342 if (const auto *G = dyn_cast<GuardedByAttr>(A))
18343 Arg = G->getArg();
18344 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18345 Arg = G->getArg();
18346 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18347 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
18348 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18349 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
18350 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18351 Arg = ETLF->getSuccessValue();
18352 Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size());
18353 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18354 Arg = STLF->getSuccessValue();
18355 Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size());
18356 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18357 Arg = LR->getArg();
18358 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18359 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
18360 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18361 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18362 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18363 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18364 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18365 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
18366 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18367 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
18368
18369 if (Arg && !Finder.TraverseStmt(Arg))
18370 return true;
18371
18372 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18373 if (!Finder.TraverseStmt(Args[I]))
18374 return true;
18375 }
18376 }
18377
18378 return false;
18379}
18380
18381void Sema::checkExceptionSpecification(
18382 bool IsTopLevel, ExceptionSpecificationType EST,
18383 ArrayRef<ParsedType> DynamicExceptions,
18384 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18385 SmallVectorImpl<QualType> &Exceptions,
18386 FunctionProtoType::ExceptionSpecInfo &ESI) {
18387 Exceptions.clear();
18388 ESI.Type = EST;
18389 if (EST == EST_Dynamic) {
18390 Exceptions.reserve(DynamicExceptions.size());
18391 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18392 // FIXME: Preserve type source info.
18393 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18394
18395 if (IsTopLevel) {
18396 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
18397 collectUnexpandedParameterPacks(ET, Unexpanded);
18398 if (!Unexpanded.empty()) {
18399 DiagnoseUnexpandedParameterPacks(
18400 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18401 Unexpanded);
18402 continue;
18403 }
18404 }
18405
18406 // Check that the type is valid for an exception spec, and
18407 // drop it if not.
18408 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18409 Exceptions.push_back(ET);
18410 }
18411 ESI.Exceptions = Exceptions;
18412 return;
18413 }
18414
18415 if (isComputedNoexcept(EST)) {
18416 assert((NoexceptExpr->isTypeDependent() ||(static_cast <bool> ((NoexceptExpr->isTypeDependent(
) || NoexceptExpr->getType()->getCanonicalTypeUnqualified
() == Context.BoolTy) && "Parser should have made sure that the expression is boolean"
) ? void (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 18419, __extension__ __PRETTY_FUNCTION__
))
18417 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==(static_cast <bool> ((NoexceptExpr->isTypeDependent(
) || NoexceptExpr->getType()->getCanonicalTypeUnqualified
() == Context.BoolTy) && "Parser should have made sure that the expression is boolean"
) ? void (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 18419, __extension__ __PRETTY_FUNCTION__
))
18418 Context.BoolTy) &&(static_cast <bool> ((NoexceptExpr->isTypeDependent(
) || NoexceptExpr->getType()->getCanonicalTypeUnqualified
() == Context.BoolTy) && "Parser should have made sure that the expression is boolean"
) ? void (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 18419, __extension__ __PRETTY_FUNCTION__
))
18419 "Parser should have made sure that the expression is boolean")(static_cast <bool> ((NoexceptExpr->isTypeDependent(
) || NoexceptExpr->getType()->getCanonicalTypeUnqualified
() == Context.BoolTy) && "Parser should have made sure that the expression is boolean"
) ? void (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 18419, __extension__ __PRETTY_FUNCTION__
))
;
18420 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18421 ESI.Type = EST_BasicNoexcept;
18422 return;
18423 }
18424
18425 ESI.NoexceptExpr = NoexceptExpr;
18426 return;
18427 }
18428}
18429
18430void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
18431 ExceptionSpecificationType EST,
18432 SourceRange SpecificationRange,
18433 ArrayRef<ParsedType> DynamicExceptions,
18434 ArrayRef<SourceRange> DynamicExceptionRanges,
18435 Expr *NoexceptExpr) {
18436 if (!MethodD)
18437 return;
18438
18439 // Dig out the method we're referring to.
18440 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18441 MethodD = FunTmpl->getTemplatedDecl();
18442
18443 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18444 if (!Method)
18445 return;
18446
18447 // Check the exception specification.
18448 llvm::SmallVector<QualType, 4> Exceptions;
18449 FunctionProtoType::ExceptionSpecInfo ESI;
18450 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18451 DynamicExceptionRanges, NoexceptExpr, Exceptions,
18452 ESI);
18453
18454 // Update the exception specification on the function type.
18455 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18456
18457 if (Method->isStatic())
18458 checkThisInStaticMemberFunctionExceptionSpec(Method);
18459
18460 if (Method->isVirtual()) {
18461 // Check overrides, which we previously had to delay.
18462 for (const CXXMethodDecl *O : Method->overridden_methods())
18463 CheckOverridingFunctionExceptionSpec(Method, O);
18464 }
18465}
18466
18467/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18468///
18469MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
18470 SourceLocation DeclStart, Declarator &D,
18471 Expr *BitWidth,
18472 InClassInitStyle InitStyle,
18473 AccessSpecifier AS,
18474 const ParsedAttr &MSPropertyAttr) {
18475 IdentifierInfo *II = D.getIdentifier();
18476 if (!II) {
18477 Diag(DeclStart, diag::err_anonymous_property);
18478 return nullptr;
18479 }
18480 SourceLocation Loc = D.getIdentifierLoc();
18481
18482 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18483 QualType T = TInfo->getType();
18484 if (getLangOpts().CPlusPlus) {
18485 CheckExtraCXXDefaultArguments(D);
18486
18487 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18488 UPPC_DataMemberType)) {
18489 D.setInvalidType();
18490 T = Context.IntTy;
18491 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18492 }
18493 }
18494
18495 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18496
18497 if (D.getDeclSpec().isInlineSpecified())
18498 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18499 << getLangOpts().CPlusPlus17;
18500 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18501 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18502 diag::err_invalid_thread)
18503 << DeclSpec::getSpecifierName(TSCS);
18504
18505 // Check to see if this name was declared as a member previously
18506 NamedDecl *PrevDecl = nullptr;
18507 LookupResult Previous(*this, II, Loc, LookupMemberName,
18508 ForVisibleRedeclaration);
18509 LookupName(Previous, S);
18510 switch (Previous.getResultKind()) {
18511 case LookupResult::Found:
18512 case LookupResult::FoundUnresolvedValue:
18513 PrevDecl = Previous.getAsSingle<NamedDecl>();
18514 break;
18515
18516 case LookupResult::FoundOverloaded:
18517 PrevDecl = Previous.getRepresentativeDecl();
18518 break;
18519
18520 case LookupResult::NotFound:
18521 case LookupResult::NotFoundInCurrentInstantiation:
18522 case LookupResult::Ambiguous:
18523 break;
18524 }
18525
18526 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18527 // Maybe we will complain about the shadowed template parameter.
18528 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18529 // Just pretend that we didn't see the previous declaration.
18530 PrevDecl = nullptr;
18531 }
18532
18533 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18534 PrevDecl = nullptr;
18535
18536 SourceLocation TSSL = D.getBeginLoc();
18537 MSPropertyDecl *NewPD =
18538 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18539 MSPropertyAttr.getPropertyDataGetter(),
18540 MSPropertyAttr.getPropertyDataSetter());
18541 ProcessDeclAttributes(TUScope, NewPD, D);
18542 NewPD->setAccess(AS);
18543
18544 if (NewPD->isInvalidDecl())
18545 Record->setInvalidDecl();
18546
18547 if (D.getDeclSpec().isModulePrivateSpecified())
18548 NewPD->setModulePrivate();
18549
18550 if (NewPD->isInvalidDecl() && PrevDecl) {
18551 // Don't introduce NewFD into scope; there's already something
18552 // with the same name in the same scope.
18553 } else if (II) {
18554 PushOnScopeChains(NewPD, S);
18555 } else
18556 Record->addDecl(NewPD);
18557
18558 return NewPD;
18559}
18560
18561void Sema::ActOnStartFunctionDeclarationDeclarator(
18562 Declarator &Declarator, unsigned TemplateParameterDepth) {
18563 auto &Info = InventedParameterInfos.emplace_back();
18564 TemplateParameterList *ExplicitParams = nullptr;
18565 ArrayRef<TemplateParameterList *> ExplicitLists =
18566 Declarator.getTemplateParameterLists();
18567 if (!ExplicitLists.empty()) {
18568 bool IsMemberSpecialization, IsInvalid;
18569 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18570 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
18571 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18572 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18573 /*SuppressDiagnostic=*/true);
18574 }
18575 if (ExplicitParams) {
18576 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18577 llvm::append_range(Info.TemplateParams, *ExplicitParams);
18578 Info.NumExplicitTemplateParams = ExplicitParams->size();
18579 } else {
18580 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18581 Info.NumExplicitTemplateParams = 0;
18582 }
18583}
18584
18585void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
18586 auto &FSI = InventedParameterInfos.back();
18587 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18588 if (FSI.NumExplicitTemplateParams != 0) {
18589 TemplateParameterList *ExplicitParams =
18590 Declarator.getTemplateParameterLists().back();
18591 Declarator.setInventedTemplateParameterList(
18592 TemplateParameterList::Create(
18593 Context, ExplicitParams->getTemplateLoc(),
18594 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18595 ExplicitParams->getRAngleLoc(),
18596 ExplicitParams->getRequiresClause()));
18597 } else {
18598 Declarator.setInventedTemplateParameterList(
18599 TemplateParameterList::Create(
18600 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18601 SourceLocation(), /*RequiresClause=*/nullptr));
18602 }
18603 }
18604 InventedParameterInfos.pop_back();
18605}