Bug Summary

File:build/source/clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 669, column 34
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-17/lib/clang/17 -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 _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -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-17/lib/clang/17/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/= -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-05-10-133810-16478-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/EnterExpressionEvaluationContext.h"
38#include "clang/Sema/Initialization.h"
39#include "clang/Sema/Lookup.h"
40#include "clang/Sema/ParsedTemplate.h"
41#include "clang/Sema/Scope.h"
42#include "clang/Sema/ScopeInfo.h"
43#include "clang/Sema/SemaInternal.h"
44#include "clang/Sema/Template.h"
45#include "llvm/ADT/STLExtras.h"
46#include "llvm/ADT/ScopeExit.h"
47#include "llvm/ADT/SmallString.h"
48#include "llvm/ADT/StringExtras.h"
49#include <map>
50#include <optional>
51#include <set>
52
53using namespace clang;
54
55//===----------------------------------------------------------------------===//
56// CheckDefaultArgumentVisitor
57//===----------------------------------------------------------------------===//
58
59namespace {
60/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
61/// the default argument of a parameter to determine whether it
62/// contains any ill-formed subexpressions. For example, this will
63/// diagnose the use of local variables or parameters within the
64/// default argument expression.
65class CheckDefaultArgumentVisitor
66 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
67 Sema &S;
68 const Expr *DefaultArg;
69
70public:
71 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
72 : S(S), DefaultArg(DefaultArg) {}
73
74 bool VisitExpr(const Expr *Node);
75 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
76 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
77 bool VisitLambdaExpr(const LambdaExpr *Lambda);
78 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
79};
80
81/// VisitExpr - Visit all of the children of this expression.
82bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
83 bool IsInvalid = false;
84 for (const Stmt *SubStmt : Node->children())
85 IsInvalid |= Visit(SubStmt);
86 return IsInvalid;
87}
88
89/// VisitDeclRefExpr - Visit a reference to a declaration, to
90/// determine whether this declaration can be used in the default
91/// argument expression.
92bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
93 const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
94
95 if (!isa<VarDecl, BindingDecl>(Decl))
96 return false;
97
98 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
99 // C++ [dcl.fct.default]p9:
100 // [...] parameters of a function shall not be used in default
101 // argument expressions, even if they are not evaluated. [...]
102 //
103 // C++17 [dcl.fct.default]p9 (by CWG 2082):
104 // [...] A parameter shall not appear as a potentially-evaluated
105 // expression in a default argument. [...]
106 //
107 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
108 return S.Diag(DRE->getBeginLoc(),
109 diag::err_param_default_argument_references_param)
110 << Param->getDeclName() << DefaultArg->getSourceRange();
111 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
112 // C++ [dcl.fct.default]p7:
113 // Local variables shall not be used in default argument
114 // expressions.
115 //
116 // C++17 [dcl.fct.default]p7 (by CWG 2082):
117 // A local variable shall not appear as a potentially-evaluated
118 // expression in a default argument.
119 //
120 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
121 // Note: A local variable cannot be odr-used (6.3) in a default
122 // argument.
123 //
124 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
125 return S.Diag(DRE->getBeginLoc(),
126 diag::err_param_default_argument_references_local)
127 << Decl << DefaultArg->getSourceRange();
128 }
129 return false;
130}
131
132/// VisitCXXThisExpr - Visit a C++ "this" expression.
133bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
134 // C++ [dcl.fct.default]p8:
135 // The keyword this shall not be used in a default argument of a
136 // member function.
137 return S.Diag(ThisE->getBeginLoc(),
138 diag::err_param_default_argument_references_this)
139 << ThisE->getSourceRange();
140}
141
142bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
143 const PseudoObjectExpr *POE) {
144 bool Invalid = false;
145 for (const Expr *E : POE->semantics()) {
146 // Look through bindings.
147 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
148 E = OVE->getSourceExpr();
149 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", 149, __extension__ __PRETTY_FUNCTION__
))
;
150 }
151
152 Invalid |= Visit(E);
153 }
154 return Invalid;
155}
156
157bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
158 // [expr.prim.lambda.capture]p9
159 // a lambda-expression appearing in a default argument cannot implicitly or
160 // explicitly capture any local entity. Such a lambda-expression can still
161 // have an init-capture if any full-expression in its initializer satisfies
162 // the constraints of an expression appearing in a default argument.
163 bool Invalid = false;
164 for (const LambdaCapture &LC : Lambda->captures()) {
165 if (!Lambda->isInitCapture(&LC))
166 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
167 // Init captures are always VarDecl.
168 auto *D = cast<VarDecl>(LC.getCapturedVar());
169 Invalid |= Visit(D->getInit());
170 }
171 return Invalid;
172}
173} // namespace
174
175void
176Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
177 const CXXMethodDecl *Method) {
178 // If we have an MSAny spec already, don't bother.
179 if (!Method || ComputedEST == EST_MSAny)
180 return;
181
182 const FunctionProtoType *Proto
183 = Method->getType()->getAs<FunctionProtoType>();
184 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
185 if (!Proto)
186 return;
187
188 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
189
190 // If we have a throw-all spec at this point, ignore the function.
191 if (ComputedEST == EST_None)
192 return;
193
194 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
195 EST = EST_BasicNoexcept;
196
197 switch (EST) {
198 case EST_Unparsed:
199 case EST_Uninstantiated:
200 case EST_Unevaluated:
201 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", 201)
;
202
203 // If this function can throw any exceptions, make a note of that.
204 case EST_MSAny:
205 case EST_None:
206 // FIXME: Whichever we see last of MSAny and None determines our result.
207 // We should make a consistent, order-independent choice here.
208 ClearExceptions();
209 ComputedEST = EST;
210 return;
211 case EST_NoexceptFalse:
212 ClearExceptions();
213 ComputedEST = EST_None;
214 return;
215 // FIXME: If the call to this decl is using any of its default arguments, we
216 // need to search them for potentially-throwing calls.
217 // If this function has a basic noexcept, it doesn't affect the outcome.
218 case EST_BasicNoexcept:
219 case EST_NoexceptTrue:
220 case EST_NoThrow:
221 return;
222 // If we're still at noexcept(true) and there's a throw() callee,
223 // change to that specification.
224 case EST_DynamicNone:
225 if (ComputedEST == EST_BasicNoexcept)
226 ComputedEST = EST_DynamicNone;
227 return;
228 case EST_DependentNoexcept:
229 llvm_unreachable(::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "clang/lib/Sema/SemaDeclCXX.cpp", 230)
230 "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", 230)
;
231 case EST_Dynamic:
232 break;
233 }
234 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", 234, __extension__ __PRETTY_FUNCTION__
))
;
235 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", 236, __extension__ __PRETTY_FUNCTION__
))
236 "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", 236, __extension__ __PRETTY_FUNCTION__
))
;
237 ComputedEST = EST_Dynamic;
238 // Record the exceptions in this function's exception specification.
239 for (const auto &E : Proto->exceptions())
240 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
241 Exceptions.push_back(E);
242}
243
244void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
245 if (!S || ComputedEST == EST_MSAny)
246 return;
247
248 // FIXME:
249 //
250 // C++0x [except.spec]p14:
251 // [An] implicit exception-specification specifies the type-id T if and
252 // only if T is allowed by the exception-specification of a function directly
253 // invoked by f's implicit definition; f shall allow all exceptions if any
254 // function it directly invokes allows all exceptions, and f shall allow no
255 // exceptions if every function it directly invokes allows no exceptions.
256 //
257 // Note in particular that if an implicit exception-specification is generated
258 // for a function containing a throw-expression, that specification can still
259 // be noexcept(true).
260 //
261 // Note also that 'directly invoked' is not defined in the standard, and there
262 // is no indication that we should only consider potentially-evaluated calls.
263 //
264 // Ultimately we should implement the intent of the standard: the exception
265 // specification should be the set of exceptions which can be thrown by the
266 // implicit definition. For now, we assume that any non-nothrow expression can
267 // throw any exception.
268
269 if (Self->canThrow(S))
270 ComputedEST = EST_None;
271}
272
273ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
274 SourceLocation EqualLoc) {
275 if (RequireCompleteType(Param->getLocation(), Param->getType(),
276 diag::err_typecheck_decl_incomplete_type))
277 return true;
278
279 // C++ [dcl.fct.default]p5
280 // A default argument expression is implicitly converted (clause
281 // 4) to the parameter type. The default argument expression has
282 // the same semantic constraints as the initializer expression in
283 // a declaration of a variable of the parameter type, using the
284 // copy-initialization semantics (8.5).
285 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
286 Param);
287 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
288 EqualLoc);
289 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
290 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
291 if (Result.isInvalid())
292 return true;
293 Arg = Result.getAs<Expr>();
294
295 CheckCompletedExpr(Arg, EqualLoc);
296 Arg = MaybeCreateExprWithCleanups(Arg);
297
298 return Arg;
299}
300
301void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
302 SourceLocation EqualLoc) {
303 // Add the default argument to the parameter
304 Param->setDefaultArg(Arg);
305
306 // We have already instantiated this parameter; provide each of the
307 // instantiations with the uninstantiated default argument.
308 UnparsedDefaultArgInstantiationsMap::iterator InstPos
309 = UnparsedDefaultArgInstantiations.find(Param);
310 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
311 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
312 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
313
314 // We're done tracking this parameter's instantiations.
315 UnparsedDefaultArgInstantiations.erase(InstPos);
316 }
317}
318
319/// ActOnParamDefaultArgument - Check whether the default argument
320/// provided for a function parameter is well-formed. If so, attach it
321/// to the parameter declaration.
322void
323Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
324 Expr *DefaultArg) {
325 if (!param || !DefaultArg)
326 return;
327
328 ParmVarDecl *Param = cast<ParmVarDecl>(param);
329 UnparsedDefaultArgLocs.erase(Param);
330
331 auto Fail = [&] {
332 Param->setInvalidDecl();
333 Param->setDefaultArg(new (Context) OpaqueValueExpr(
334 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
335 };
336
337 // Default arguments are only permitted in C++
338 if (!getLangOpts().CPlusPlus) {
339 Diag(EqualLoc, diag::err_param_default_argument)
340 << DefaultArg->getSourceRange();
341 return Fail();
342 }
343
344 // Check for unexpanded parameter packs.
345 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
346 return Fail();
347 }
348
349 // C++11 [dcl.fct.default]p3
350 // A default argument expression [...] shall not be specified for a
351 // parameter pack.
352 if (Param->isParameterPack()) {
353 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
354 << DefaultArg->getSourceRange();
355 // Recover by discarding the default argument.
356 Param->setDefaultArg(nullptr);
357 return;
358 }
359
360 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
361 if (Result.isInvalid())
362 return Fail();
363
364 DefaultArg = Result.getAs<Expr>();
365
366 // Check that the default argument is well-formed
367 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
368 if (DefaultArgChecker.Visit(DefaultArg))
369 return Fail();
370
371 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
372}
373
374/// ActOnParamUnparsedDefaultArgument - We've seen a default
375/// argument for a function parameter, but we can't parse it yet
376/// because we're inside a class definition. Note that this default
377/// argument will be parsed later.
378void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
379 SourceLocation EqualLoc,
380 SourceLocation ArgLoc) {
381 if (!param)
382 return;
383
384 ParmVarDecl *Param = cast<ParmVarDecl>(param);
385 Param->setUnparsedDefaultArg();
386 UnparsedDefaultArgLocs[Param] = ArgLoc;
387}
388
389/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
390/// the default argument for the parameter param failed.
391void Sema::ActOnParamDefaultArgumentError(Decl *param,
392 SourceLocation EqualLoc) {
393 if (!param)
394 return;
395
396 ParmVarDecl *Param = cast<ParmVarDecl>(param);
397 Param->setInvalidDecl();
398 UnparsedDefaultArgLocs.erase(Param);
399 Param->setDefaultArg(new (Context) OpaqueValueExpr(
400 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
401}
402
403/// CheckExtraCXXDefaultArguments - Check for any extra default
404/// arguments in the declarator, which is not a function declaration
405/// or definition and therefore is not permitted to have default
406/// arguments. This routine should be invoked for every declarator
407/// that is not a function declaration or definition.
408void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
409 // C++ [dcl.fct.default]p3
410 // A default argument expression shall be specified only in the
411 // parameter-declaration-clause of a function declaration or in a
412 // template-parameter (14.1). It shall not be specified for a
413 // parameter pack. If it is specified in a
414 // parameter-declaration-clause, it shall not occur within a
415 // declarator or abstract-declarator of a parameter-declaration.
416 bool MightBeFunction = D.isFunctionDeclarationContext();
417 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
418 DeclaratorChunk &chunk = D.getTypeObject(i);
419 if (chunk.Kind == DeclaratorChunk::Function) {
420 if (MightBeFunction) {
421 // This is a function declaration. It can have default arguments, but
422 // keep looking in case its return type is a function type with default
423 // arguments.
424 MightBeFunction = false;
425 continue;
426 }
427 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
428 ++argIdx) {
429 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
430 if (Param->hasUnparsedDefaultArg()) {
431 std::unique_ptr<CachedTokens> Toks =
432 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
433 SourceRange SR;
434 if (Toks->size() > 1)
435 SR = SourceRange((*Toks)[1].getLocation(),
436 Toks->back().getLocation());
437 else
438 SR = UnparsedDefaultArgLocs[Param];
439 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
440 << SR;
441 } else if (Param->getDefaultArg()) {
442 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
443 << Param->getDefaultArg()->getSourceRange();
444 Param->setDefaultArg(nullptr);
445 }
446 }
447 } else if (chunk.Kind != DeclaratorChunk::Paren) {
448 MightBeFunction = false;
449 }
450 }
451}
452
453static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
454 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
455 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
456 });
457}
458
459/// MergeCXXFunctionDecl - Merge two declarations of the same C++
460/// function, once we already know that they have the same
461/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
462/// error, false otherwise.
463bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
464 Scope *S) {
465 bool Invalid = false;
466
467 // The declaration context corresponding to the scope is the semantic
468 // parent, unless this is a local function declaration, in which case
469 // it is that surrounding function.
470 DeclContext *ScopeDC = New->isLocalExternDecl()
1
Assuming the condition is true
2
'?' condition is true
471 ? New->getLexicalDeclContext()
472 : New->getDeclContext();
473
474 // Find the previous declaration for the purpose of default arguments.
475 FunctionDecl *PrevForDefaultArgs = Old;
476 for (/**/; PrevForDefaultArgs;
3
Assuming pointer value is null
4
Loop condition is false. Execution continues on line 524
477 // Don't bother looking back past the latest decl if this is a local
478 // extern declaration; nothing else could work.
479 PrevForDefaultArgs = New->isLocalExternDecl()
480 ? nullptr
481 : PrevForDefaultArgs->getPreviousDecl()) {
482 // Ignore hidden declarations.
483 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
484 continue;
485
486 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
487 !New->isCXXClassMember()) {
488 // Ignore default arguments of old decl if they are not in
489 // the same scope and this is not an out-of-line definition of
490 // a member function.
491 continue;
492 }
493
494 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
495 // If only one of these is a local function declaration, then they are
496 // declared in different scopes, even though isDeclInScope may think
497 // they're in the same scope. (If both are local, the scope check is
498 // sufficient, and if neither is local, then they are in the same scope.)
499 continue;
500 }
501
502 // We found the right previous declaration.
503 break;
504 }
505
506 // C++ [dcl.fct.default]p4:
507 // For non-template functions, default arguments can be added in
508 // later declarations of a function in the same
509 // scope. Declarations in different scopes have completely
510 // distinct sets of default arguments. That is, declarations in
511 // inner scopes do not acquire default arguments from
512 // declarations in outer scopes, and vice versa. In a given
513 // function declaration, all parameters subsequent to a
514 // parameter with a default argument shall have default
515 // arguments supplied in this or previous declarations. A
516 // default argument shall not be redefined by a later
517 // declaration (not even to the same value).
518 //
519 // C++ [dcl.fct.default]p6:
520 // Except for member functions of class templates, the default arguments
521 // in a member function definition that appears outside of the class
522 // definition are added to the set of default arguments provided by the
523 // member function declaration in the class definition.
524 for (unsigned p = 0, NumParams = PrevForDefaultArgs
4.1
'PrevForDefaultArgs' is null
5
'?' condition is false
525 ? PrevForDefaultArgs->getNumParams() 526 : 0; 527 p < NumParams; ++p) { 528 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 529 ParmVarDecl *NewParam = New->getParamDecl(p); 530 531 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 532 bool NewParamHasDfl = NewParam->hasDefaultArg(); 533 534 if (OldParamHasDfl && NewParamHasDfl) { 535 unsigned DiagDefaultParamID = 536 diag::err_param_default_argument_redefinition; 537 538 // MSVC accepts that default parameters be redefined for member functions 539 // of template class. The new default parameter's value is ignored. 540 Invalid = true; 541 if (getLangOpts().MicrosoftExt) { 542 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 543 if (MD && MD->getParent()->getDescribedClassTemplate()) { 544 // Merge the old default argument into the new parameter. 545 NewParam->setHasInheritedDefaultArg(); 546 if (OldParam->hasUninstantiatedDefaultArg()) 547 NewParam->setUninstantiatedDefaultArg( 548 OldParam->getUninstantiatedDefaultArg()); 549 else 550 NewParam->setDefaultArg(OldParam->getInit()); 551 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 552 Invalid = false; 553 } 554 } 555 556 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 557 // hint here. Alternatively, we could walk the type-source information 558 // for NewParam to find the last source location in the type... but it 559 // isn't worth the effort right now. This is the kind of test case that 560 // is hard to get right: 561 // int f(int); 562 // void g(int (*fp)(int) = f); 563 // void g(int (*fp)(int) = &f); 564 Diag(NewParam->getLocation(), DiagDefaultParamID) 565 << NewParam->getDefaultArgRange(); 566 567 // Look for the function declaration where the default argument was 568 // actually written, which may be a declaration prior to Old. 569 for (auto Older = PrevForDefaultArgs; 570 OldParam->hasInheritedDefaultArg(); /**/) { 571 Older = Older->getPreviousDecl(); 572 OldParam = Older->getParamDecl(p); 573 } 574 575 Diag(OldParam->getLocation(), diag::note_previous_definition) 576 << OldParam->getDefaultArgRange(); 577 } else if (OldParamHasDfl) { 578 // Merge the old default argument into the new parameter unless the new 579 // function is a friend declaration in a template class. In the latter 580 // case the default arguments will be inherited when the friend 581 // declaration will be instantiated. 582 if (New->getFriendObjectKind() == Decl::FOK_None || 583 !New->getLexicalDeclContext()->isDependentContext()) { 584 // It's important to use getInit() here; getDefaultArg() 585 // strips off any top-level ExprWithCleanups. 586 NewParam->setHasInheritedDefaultArg(); 587 if (OldParam->hasUnparsedDefaultArg()) 588 NewParam->setUnparsedDefaultArg(); 589 else if (OldParam->hasUninstantiatedDefaultArg()) 590 NewParam->setUninstantiatedDefaultArg( 591 OldParam->getUninstantiatedDefaultArg()); 592 else 593 NewParam->setDefaultArg(OldParam->getInit()); 594 } 595 } else if (NewParamHasDfl) { 596 if (New->getDescribedFunctionTemplate()) { 597 // Paragraph 4, quoted above, only applies to non-template functions. 598 Diag(NewParam->getLocation(), 599 diag::err_param_default_argument_template_redecl) 600 << NewParam->getDefaultArgRange(); 601 Diag(PrevForDefaultArgs->getLocation(), 602 diag::note_template_prev_declaration) 603 << false; 604 } else if (New->getTemplateSpecializationKind() 605 != TSK_ImplicitInstantiation && 606 New->getTemplateSpecializationKind() != TSK_Undeclared) { 607 // C++ [temp.expr.spec]p21: 608 // Default function arguments shall not be specified in a declaration 609 // or a definition for one of the following explicit specializations: 610 // - the explicit specialization of a function template; 611 // - the explicit specialization of a member function template; 612 // - the explicit specialization of a member function of a class 613 // template where the class template specialization to which the 614 // member function specialization belongs is implicitly 615 // instantiated. 616 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 617 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 618 << New->getDeclName() 619 << NewParam->getDefaultArgRange(); 620 } else if (New->getDeclContext()->isDependentContext()) { 621 // C++ [dcl.fct.default]p6 (DR217): 622 // Default arguments for a member function of a class template shall 623 // be specified on the initial declaration of the member function 624 // within the class template. 625 // 626 // Reading the tea leaves a bit in DR217 and its reference to DR205 627 // leads me to the conclusion that one cannot add default function 628 // arguments for an out-of-line definition of a member function of a 629 // dependent type. 630 int WhichKind = 2; 631 if (CXXRecordDecl *Record 632 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 633 if (Record->getDescribedClassTemplate()) 634 WhichKind = 0; 635 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 636 WhichKind = 1; 637 else 638 WhichKind = 2; 639 } 640 641 Diag(NewParam->getLocation(), 642 diag::err_param_default_argument_member_template_redecl) 643 << WhichKind 644 << NewParam->getDefaultArgRange(); 645 } 646 } 647 } 648 649 // DR1344: If a default argument is added outside a class definition and that 650 // default argument makes the function a special member function, the program 651 // is ill-formed. This can only happen for constructors. 652 if (isa<CXXConstructorDecl>(New) &&
6
Assuming 'New' is not a 'CXXConstructorDecl'
653 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 654 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 655 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 656 if (NewSM != OldSM) { 657 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 658 assert(NewParam->hasDefaultArg())(static_cast <bool> (NewParam->hasDefaultArg()) ? void
(0) : __assert_fail ("NewParam->hasDefaultArg()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 658, __extension__ __PRETTY_FUNCTION__))
; 659 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 660 << NewParam->getDefaultArgRange() << NewSM; 661 Diag(Old->getLocation(), diag::note_previous_declaration); 662 } 663 } 664 665 const FunctionDecl *Def; 666 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 667 // template has a constexpr specifier then all its declarations shall 668 // contain the constexpr specifier. 669 if (New->getConstexprKind() != Old->getConstexprKind()) {
7
Called C++ object pointer is null
670 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 671 << New << static_cast<int>(New->getConstexprKind()) 672 << static_cast<int>(Old->getConstexprKind()); 673 Diag(Old->getLocation(), diag::note_previous_declaration); 674 Invalid = true; 675 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 676 Old->isDefined(Def) && 677 // If a friend function is inlined but does not have 'inline' 678 // specifier, it is a definition. Do not report attribute conflict 679 // in this case, redefinition will be diagnosed later. 680 (New->isInlineSpecified() || 681 New->getFriendObjectKind() == Decl::FOK_None)) { 682 // C++11 [dcl.fcn.spec]p4: 683 // If the definition of a function appears in a translation unit before its 684 // first declaration as inline, the program is ill-formed. 685 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 686 Diag(Def->getLocation(), diag::note_previous_definition); 687 Invalid = true; 688 } 689 690 // C++17 [temp.deduct.guide]p3: 691 // Two deduction guide declarations in the same translation unit 692 // for the same class template shall not have equivalent 693 // parameter-declaration-clauses. 694 if (isa<CXXDeductionGuideDecl>(New) && 695 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 696 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 697 Diag(Old->getLocation(), diag::note_previous_declaration); 698 } 699 700 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 701 // argument expression, that declaration shall be a definition and shall be 702 // the only declaration of the function or function template in the 703 // translation unit. 704 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 705 functionDeclHasDefaultArgument(Old)) { 706 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 707 Diag(Old->getLocation(), diag::note_previous_declaration); 708 Invalid = true; 709 } 710 711 // C++11 [temp.friend]p4 (DR329): 712 // When a function is defined in a friend function declaration in a class 713 // template, the function is instantiated when the function is odr-used. 714 // The same restrictions on multiple declarations and definitions that 715 // apply to non-template function declarations and definitions also apply 716 // to these implicit definitions. 717 const FunctionDecl *OldDefinition = nullptr; 718 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() && 719 Old->isDefined(OldDefinition, true)) 720 CheckForFunctionRedefinition(New, OldDefinition); 721 722 return Invalid; 723} 724 725NamedDecl * 726Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 727 MultiTemplateParamsArg TemplateParamLists) { 728 assert(D.isDecompositionDeclarator())(static_cast <bool> (D.isDecompositionDeclarator()) ? void
(0) : __assert_fail ("D.isDecompositionDeclarator()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 728, __extension__ __PRETTY_FUNCTION__))
; 729 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 730 731 // The syntax only allows a decomposition declarator as a simple-declaration, 732 // a for-range-declaration, or a condition in Clang, but we parse it in more 733 // cases than that. 734 if (!D.mayHaveDecompositionDeclarator()) { 735 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 736 << Decomp.getSourceRange(); 737 return nullptr; 738 } 739 740 if (!TemplateParamLists.empty()) { 741 // FIXME: There's no rule against this, but there are also no rules that 742 // would actually make it usable, so we reject it for now. 743 Diag(TemplateParamLists.front()->getTemplateLoc(), 744 diag::err_decomp_decl_template); 745 return nullptr; 746 } 747 748 Diag(Decomp.getLSquareLoc(), 749 !getLangOpts().CPlusPlus17 750 ? diag::ext_decomp_decl 751 : D.getContext() == DeclaratorContext::Condition 752 ? diag::ext_decomp_decl_cond 753 : diag::warn_cxx14_compat_decomp_decl) 754 << Decomp.getSourceRange(); 755 756 // The semantic context is always just the current context. 757 DeclContext *const DC = CurContext; 758 759 // C++17 [dcl.dcl]/8: 760 // The decl-specifier-seq shall contain only the type-specifier auto 761 // and cv-qualifiers. 762 // C++20 [dcl.dcl]/8: 763 // If decl-specifier-seq contains any decl-specifier other than static, 764 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 765 // C++23 [dcl.pre]/6: 766 // Each decl-specifier in the decl-specifier-seq shall be static, 767 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier. 768 auto &DS = D.getDeclSpec(); 769 { 770 // Note: While constrained-auto needs to be checked, we do so separately so 771 // we can emit a better diagnostic. 772 SmallVector<StringRef, 8> BadSpecifiers; 773 SmallVector<SourceLocation, 8> BadSpecifierLocs; 774 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 775 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 776 if (auto SCS = DS.getStorageClassSpec()) { 777 if (SCS == DeclSpec::SCS_static) { 778 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 779 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 780 } else { 781 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 782 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 783 } 784 } 785 if (auto TSCS = DS.getThreadStorageClassSpec()) { 786 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 787 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 788 } 789 if (DS.hasConstexprSpecifier()) { 790 BadSpecifiers.push_back( 791 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 792 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 793 } 794 if (DS.isInlineSpecified()) { 795 BadSpecifiers.push_back("inline"); 796 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 797 } 798 799 if (!BadSpecifiers.empty()) { 800 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 801 Err << (int)BadSpecifiers.size() 802 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 803 // Don't add FixItHints to remove the specifiers; we do still respect 804 // them when building the underlying variable. 805 for (auto Loc : BadSpecifierLocs) 806 Err << SourceRange(Loc, Loc); 807 } else if (!CPlusPlus20Specifiers.empty()) { 808 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 809 getLangOpts().CPlusPlus20 810 ? diag::warn_cxx17_compat_decomp_decl_spec 811 : diag::ext_decomp_decl_spec); 812 Warn << (int)CPlusPlus20Specifiers.size() 813 << llvm::join(CPlusPlus20Specifiers.begin(), 814 CPlusPlus20Specifiers.end(), " "); 815 for (auto Loc : CPlusPlus20SpecifierLocs) 816 Warn << SourceRange(Loc, Loc); 817 } 818 // We can't recover from it being declared as a typedef. 819 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 820 return nullptr; 821 } 822 823 // C++2a [dcl.struct.bind]p1: 824 // A cv that includes volatile is deprecated 825 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 826 getLangOpts().CPlusPlus20) 827 Diag(DS.getVolatileSpecLoc(), 828 diag::warn_deprecated_volatile_structured_binding); 829 830 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 831 QualType R = TInfo->getType(); 832 833 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 834 UPPC_DeclarationType)) 835 D.setInvalidType(); 836 837 // The syntax only allows a single ref-qualifier prior to the decomposition 838 // declarator. No other declarator chunks are permitted. Also check the type 839 // specifier here. 840 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 841 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 842 (D.getNumTypeObjects() == 1 && 843 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 844 Diag(Decomp.getLSquareLoc(), 845 (D.hasGroupingParens() || 846 (D.getNumTypeObjects() && 847 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 848 ? diag::err_decomp_decl_parens 849 : diag::err_decomp_decl_type) 850 << R; 851 852 // In most cases, there's no actual problem with an explicitly-specified 853 // type, but a function type won't work here, and ActOnVariableDeclarator 854 // shouldn't be called for such a type. 855 if (R->isFunctionType()) 856 D.setInvalidType(); 857 } 858 859 // Constrained auto is prohibited by [decl.pre]p6, so check that here. 860 if (DS.isConstrainedAuto()) { 861 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId(); 862 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", 863, __extension__ __PRETTY_FUNCTION__
))
863 "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", 863, __extension__ __PRETTY_FUNCTION__
))
; 864 865 SourceRange TemplRange{TemplRep->TemplateNameLoc, 866 TemplRep->RAngleLoc.isValid() 867 ? TemplRep->RAngleLoc 868 : TemplRep->TemplateNameLoc}; 869 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint) 870 << TemplRange << FixItHint::CreateRemoval(TemplRange); 871 } 872 873 // Build the BindingDecls. 874 SmallVector<BindingDecl*, 8> Bindings; 875 876 // Build the BindingDecls. 877 for (auto &B : D.getDecompositionDeclarator().bindings()) { 878 // Check for name conflicts. 879 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 880 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 881 ForVisibleRedeclaration); 882 LookupName(Previous, S, 883 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 884 885 // It's not permitted to shadow a template parameter name. 886 if (Previous.isSingleResult() && 887 Previous.getFoundDecl()->isTemplateParameter()) { 888 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 889 Previous.getFoundDecl()); 890 Previous.clear(); 891 } 892 893 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 894 895 // Find the shadowed declaration before filtering for scope. 896 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 897 ? getShadowedDeclaration(BD, Previous) 898 : nullptr; 899 900 bool ConsiderLinkage = DC->isFunctionOrMethod() && 901 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 902 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 903 /*AllowInlineNamespace*/false); 904 905 if (!Previous.empty()) { 906 auto *Old = Previous.getRepresentativeDecl(); 907 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 908 Diag(Old->getLocation(), diag::note_previous_definition); 909 } else if (ShadowedDecl && !D.isRedeclaration()) { 910 CheckShadow(BD, ShadowedDecl, Previous); 911 } 912 PushOnScopeChains(BD, S, true); 913 Bindings.push_back(BD); 914 ParsingInitForAutoVars.insert(BD); 915 } 916 917 // There are no prior lookup results for the variable itself, because it 918 // is unnamed. 919 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 920 Decomp.getLSquareLoc()); 921 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 922 ForVisibleRedeclaration); 923 924 // Build the variable that holds the non-decomposed object. 925 bool AddToScope = true; 926 NamedDecl *New = 927 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 928 MultiTemplateParamsArg(), AddToScope, Bindings); 929 if (AddToScope) { 930 S->AddDecl(New); 931 CurContext->addHiddenDecl(New); 932 } 933 934 if (isInOpenMPDeclareTargetContext()) 935 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 936 937 return New; 938} 939 940static bool checkSimpleDecomposition( 941 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 942 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 943 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 944 if ((int64_t)Bindings.size() != NumElems) { 945 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 946 << DecompType << (unsigned)Bindings.size() 947 << (unsigned)NumElems.getLimitedValue(UINT_MAX(2147483647 *2U +1U)) 948 << toString(NumElems, 10) << (NumElems < Bindings.size()); 949 return true; 950 } 951 952 unsigned I = 0; 953 for (auto *B : Bindings) { 954 SourceLocation Loc = B->getLocation(); 955 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 956 if (E.isInvalid()) 957 return true; 958 E = GetInit(Loc, E.get(), I++); 959 if (E.isInvalid()) 960 return true; 961 B->setBinding(ElemType, E.get()); 962 } 963 964 return false; 965} 966 967static bool checkArrayLikeDecomposition(Sema &S, 968 ArrayRef<BindingDecl *> Bindings, 969 ValueDecl *Src, QualType DecompType, 970 const llvm::APSInt &NumElems, 971 QualType ElemType) { 972 return checkSimpleDecomposition( 973 S, Bindings, Src, DecompType, NumElems, ElemType, 974 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 975 ExprResult E = S.ActOnIntegerConstant(Loc, I); 976 if (E.isInvalid()) 977 return ExprError(); 978 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 979 }); 980} 981 982static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 983 ValueDecl *Src, QualType DecompType, 984 const ConstantArrayType *CAT) { 985 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 986 llvm::APSInt(CAT->getSize()), 987 CAT->getElementType()); 988} 989 990static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 991 ValueDecl *Src, QualType DecompType, 992 const VectorType *VT) { 993 return checkArrayLikeDecomposition( 994 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 995 S.Context.getQualifiedType(VT->getElementType(), 996 DecompType.getQualifiers())); 997} 998 999static bool checkComplexDecomposition(Sema &S, 1000 ArrayRef<BindingDecl *> Bindings, 1001 ValueDecl *Src, QualType DecompType, 1002 const ComplexType *CT) { 1003 return checkSimpleDecomposition( 1004 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 1005 S.Context.getQualifiedType(CT->getElementType(), 1006 DecompType.getQualifiers()), 1007 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 1008 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 1009 }); 1010} 1011 1012static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 1013 TemplateArgumentListInfo &Args, 1014 const TemplateParameterList *Params) { 1015 SmallString<128> SS; 1016 llvm::raw_svector_ostream OS(SS); 1017 bool First = true; 1018 unsigned I = 0; 1019 for (auto &Arg : Args.arguments()) { 1020 if (!First) 1021 OS << ", "; 1022 Arg.getArgument().print(PrintingPolicy, OS, 1023 TemplateParameterList::shouldIncludeTypeForArgument( 1024 PrintingPolicy, Params, I)); 1025 First = false; 1026 I++; 1027 } 1028 return std::string(OS.str()); 1029} 1030 1031static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 1032 SourceLocation Loc, StringRef Trait, 1033 TemplateArgumentListInfo &Args, 1034 unsigned DiagID) { 1035 auto DiagnoseMissing = [&] { 1036 if (DiagID) 1037 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 1038 Args, /*Params*/ nullptr); 1039 return true; 1040 }; 1041 1042 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 1043 NamespaceDecl *Std = S.getStdNamespace(); 1044 if (!Std) 1045 return DiagnoseMissing(); 1046 1047 // Look up the trait itself, within namespace std. We can diagnose various 1048 // problems with this lookup even if we've been asked to not diagnose a 1049 // missing specialization, because this can only fail if the user has been 1050 // declaring their own names in namespace std or we don't support the 1051 // standard library implementation in use. 1052 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 1053 Loc, Sema::LookupOrdinaryName); 1054 if (!S.LookupQualifiedName(Result, Std)) 1055 return DiagnoseMissing(); 1056 if (Result.isAmbiguous()) 1057 return true; 1058 1059 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1060 if (!TraitTD) { 1061 Result.suppressDiagnostics(); 1062 NamedDecl *Found = *Result.begin(); 1063 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1064 S.Diag(Found->getLocation(), diag::note_declared_at); 1065 return true; 1066 } 1067 1068 // Build the template-id. 1069 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1070 if (TraitTy.isNull()) 1071 return true; 1072 if (!S.isCompleteType(Loc, TraitTy)) { 1073 if (DiagID) 1074 S.RequireCompleteType( 1075 Loc, TraitTy, DiagID, 1076 printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1077 TraitTD->getTemplateParameters())); 1078 return true; 1079 } 1080 1081 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1082 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", 1082, __extension__ __PRETTY_FUNCTION__
))
; 1083 1084 // Look up the member of the trait type. 1085 S.LookupQualifiedName(TraitMemberLookup, RD); 1086 return TraitMemberLookup.isAmbiguous(); 1087} 1088 1089static TemplateArgumentLoc 1090getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1091 uint64_t I) { 1092 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1093 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1094} 1095 1096static TemplateArgumentLoc 1097getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1098 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1099} 1100 1101namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1102 1103static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1104 llvm::APSInt &Size) { 1105 EnterExpressionEvaluationContext ContextRAII( 1106 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1107 1108 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1109 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1110 1111 // Form template argument list for tuple_size<T>. 1112 TemplateArgumentListInfo Args(Loc, Loc); 1113 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1114 1115 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1116 // it's not tuple-like. 1117 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1118 R.empty()) 1119 return IsTupleLike::NotTupleLike; 1120 1121 // If we get this far, we've committed to the tuple interpretation, but 1122 // we can still fail if there actually isn't a usable ::value. 1123 1124 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1125 LookupResult &R; 1126 TemplateArgumentListInfo &Args; 1127 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1128 : R(R), Args(Args) {} 1129 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1130 SourceLocation Loc) override { 1131 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1132 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1133 /*Params*/ nullptr); 1134 } 1135 } Diagnoser(R, Args); 1136 1137 ExprResult E = 1138 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1139 if (E.isInvalid()) 1140 return IsTupleLike::Error; 1141 1142 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser); 1143 if (E.isInvalid()) 1144 return IsTupleLike::Error; 1145 1146 return IsTupleLike::TupleLike; 1147} 1148 1149/// \return std::tuple_element<I, T>::type. 1150static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1151 unsigned I, QualType T) { 1152 // Form template argument list for tuple_element<I, T>. 1153 TemplateArgumentListInfo Args(Loc, Loc); 1154 Args.addArgument( 1155 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1156 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1157 1158 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1159 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1160 if (lookupStdTypeTraitMember( 1161 S, R, Loc, "tuple_element", Args, 1162 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1163 return QualType(); 1164 1165 auto *TD = R.getAsSingle<TypeDecl>(); 1166 if (!TD) { 1167 R.suppressDiagnostics(); 1168 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1169 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1170 /*Params*/ nullptr); 1171 if (!R.empty()) 1172 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1173 return QualType(); 1174 } 1175 1176 return S.Context.getTypeDeclType(TD); 1177} 1178 1179namespace { 1180struct InitializingBinding { 1181 Sema &S; 1182 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1183 Sema::CodeSynthesisContext Ctx; 1184 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1185 Ctx.PointOfInstantiation = BD->getLocation(); 1186 Ctx.Entity = BD; 1187 S.pushCodeSynthesisContext(Ctx); 1188 } 1189 ~InitializingBinding() { 1190 S.popCodeSynthesisContext(); 1191 } 1192}; 1193} 1194 1195static bool checkTupleLikeDecomposition(Sema &S, 1196 ArrayRef<BindingDecl *> Bindings, 1197 VarDecl *Src, QualType DecompType, 1198 const llvm::APSInt &TupleSize) { 1199 if ((int64_t)Bindings.size() != TupleSize) { 1200 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1201 << DecompType << (unsigned)Bindings.size() 1202 << (unsigned)TupleSize.getLimitedValue(UINT_MAX(2147483647 *2U +1U)) 1203 << toString(TupleSize, 10) << (TupleSize < Bindings.size()); 1204 return true; 1205 } 1206 1207 if (Bindings.empty()) 1208 return false; 1209 1210 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1211 1212 // [dcl.decomp]p3: 1213 // The unqualified-id get is looked up in the scope of E by class member 1214 // access lookup ... 1215 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1216 bool UseMemberGet = false; 1217 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1218 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1219 S.LookupQualifiedName(MemberGet, RD); 1220 if (MemberGet.isAmbiguous()) 1221 return true; 1222 // ... and if that finds at least one declaration that is a function 1223 // template whose first template parameter is a non-type parameter ... 1224 for (NamedDecl *D : MemberGet) { 1225 if (FunctionTemplateDecl *FTD = 1226 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1227 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1228 if (TPL->size() != 0 && 1229 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1230 // ... the initializer is e.get<i>(). 1231 UseMemberGet = true; 1232 break; 1233 } 1234 } 1235 } 1236 } 1237 1238 unsigned I = 0; 1239 for (auto *B : Bindings) { 1240 InitializingBinding InitContext(S, B); 1241 SourceLocation Loc = B->getLocation(); 1242 1243 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1244 if (E.isInvalid()) 1245 return true; 1246 1247 // e is an lvalue if the type of the entity is an lvalue reference and 1248 // an xvalue otherwise 1249 if (!Src->getType()->isLValueReferenceType()) 1250 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1251 E.get(), nullptr, VK_XValue, 1252 FPOptionsOverride()); 1253 1254 TemplateArgumentListInfo Args(Loc, Loc); 1255 Args.addArgument( 1256 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1257 1258 if (UseMemberGet) { 1259 // if [lookup of member get] finds at least one declaration, the 1260 // initializer is e.get<i-1>(). 1261 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1262 CXXScopeSpec(), SourceLocation(), nullptr, 1263 MemberGet, &Args, nullptr); 1264 if (E.isInvalid()) 1265 return true; 1266 1267 E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc); 1268 } else { 1269 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1270 // in the associated namespaces. 1271 Expr *Get = UnresolvedLookupExpr::Create( 1272 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1273 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1274 UnresolvedSetIterator(), UnresolvedSetIterator()); 1275 1276 Expr *Arg = E.get(); 1277 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1278 } 1279 if (E.isInvalid()) 1280 return true; 1281 Expr *Init = E.get(); 1282 1283 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1284 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1285 if (T.isNull()) 1286 return true; 1287 1288 // each vi is a variable of type "reference to T" initialized with the 1289 // initializer, where the reference is an lvalue reference if the 1290 // initializer is an lvalue and an rvalue reference otherwise 1291 QualType RefType = 1292 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1293 if (RefType.isNull()) 1294 return true; 1295 auto *RefVD = VarDecl::Create( 1296 S.Context, Src->getDeclContext(), Loc, Loc, 1297 B->getDeclName().getAsIdentifierInfo(), RefType, 1298 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1299 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1300 RefVD->setTSCSpec(Src->getTSCSpec()); 1301 RefVD->setImplicit(); 1302 if (Src->isInlineSpecified()) 1303 RefVD->setInlineSpecified(); 1304 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1305 1306 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1307 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1308 InitializationSequence Seq(S, Entity, Kind, Init); 1309 E = Seq.Perform(S, Entity, Kind, Init); 1310 if (E.isInvalid()) 1311 return true; 1312 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1313 if (E.isInvalid()) 1314 return true; 1315 RefVD->setInit(E.get()); 1316 S.CheckCompleteVariableDeclaration(RefVD); 1317 1318 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1319 DeclarationNameInfo(B->getDeclName(), Loc), 1320 RefVD); 1321 if (E.isInvalid()) 1322 return true; 1323 1324 B->setBinding(T, E.get()); 1325 I++; 1326 } 1327 1328 return false; 1329} 1330 1331/// Find the base class to decompose in a built-in decomposition of a class type. 1332/// This base class search is, unfortunately, not quite like any other that we 1333/// perform anywhere else in C++. 1334static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1335 const CXXRecordDecl *RD, 1336 CXXCastPath &BasePath) { 1337 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1338 CXXBasePath &Path) { 1339 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1340 }; 1341 1342 const CXXRecordDecl *ClassWithFields = nullptr; 1343 AccessSpecifier AS = AS_public; 1344 if (RD->hasDirectFields()) 1345 // [dcl.decomp]p4: 1346 // Otherwise, all of E's non-static data members shall be public direct 1347 // members of E ... 1348 ClassWithFields = RD; 1349 else { 1350 // ... or of ... 1351 CXXBasePaths Paths; 1352 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1353 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1354 // If no classes have fields, just decompose RD itself. (This will work 1355 // if and only if zero bindings were provided.) 1356 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1357 } 1358 1359 CXXBasePath *BestPath = nullptr; 1360 for (auto &P : Paths) { 1361 if (!BestPath) 1362 BestPath = &P; 1363 else if (!S.Context.hasSameType(P.back().Base->getType(), 1364 BestPath->back().Base->getType())) { 1365 // ... the same ... 1366 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1367 << false << RD << BestPath->back().Base->getType() 1368 << P.back().Base->getType(); 1369 return DeclAccessPair(); 1370 } else if (P.Access < BestPath->Access) { 1371 BestPath = &P; 1372 } 1373 } 1374 1375 // ... unambiguous ... 1376 QualType BaseType = BestPath->back().Base->getType(); 1377 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1378 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1379 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1380 return DeclAccessPair(); 1381 } 1382 1383 // ... [accessible, implied by other rules] base class of E. 1384 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1385 *BestPath, diag::err_decomp_decl_inaccessible_base); 1386 AS = BestPath->Access; 1387 1388 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1389 S.BuildBasePathArray(Paths, BasePath); 1390 } 1391 1392 // The above search did not check whether the selected class itself has base 1393 // classes with fields, so check that now. 1394 CXXBasePaths Paths; 1395 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1396 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1397 << (ClassWithFields == RD) << RD << ClassWithFields 1398 << Paths.front().back().Base->getType(); 1399 return DeclAccessPair(); 1400 } 1401 1402 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1403} 1404 1405static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1406 ValueDecl *Src, QualType DecompType, 1407 const CXXRecordDecl *OrigRD) { 1408 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1409 diag::err_incomplete_type)) 1410 return true; 1411 1412 CXXCastPath BasePath; 1413 DeclAccessPair BasePair = 1414 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1415 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1416 if (!RD) 1417 return true; 1418 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1419 DecompType.getQualifiers()); 1420 1421 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1422 unsigned NumFields = llvm::count_if( 1423 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1424 assert(Bindings.size() != NumFields)(static_cast <bool> (Bindings.size() != NumFields) ? void
(0) : __assert_fail ("Bindings.size() != NumFields", "clang/lib/Sema/SemaDeclCXX.cpp"
, 1424, __extension__ __PRETTY_FUNCTION__))
; 1425 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1426 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields 1427 << (NumFields < Bindings.size()); 1428 return true; 1429 }; 1430 1431 // all of E's non-static data members shall be [...] well-formed 1432 // when named as e.name in the context of the structured binding, 1433 // E shall not have an anonymous union member, ... 1434 unsigned I = 0; 1435 for (auto *FD : RD->fields()) { 1436 if (FD->isUnnamedBitfield()) 1437 continue; 1438 1439 // All the non-static data members are required to be nameable, so they 1440 // must all have names. 1441 if (!FD->getDeclName()) { 1442 if (RD->isLambda()) { 1443 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda); 1444 S.Diag(RD->getLocation(), diag::note_lambda_decl); 1445 return true; 1446 } 1447 1448 if (FD->isAnonymousStructOrUnion()) { 1449 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1450 << DecompType << FD->getType()->isUnionType(); 1451 S.Diag(FD->getLocation(), diag::note_declared_at); 1452 return true; 1453 } 1454 1455 // FIXME: Are there any other ways we could have an anonymous member? 1456 } 1457 1458 // We have a real field to bind. 1459 if (I >= Bindings.size()) 1460 return DiagnoseBadNumberOfBindings(); 1461 auto *B = Bindings[I++]; 1462 SourceLocation Loc = B->getLocation(); 1463 1464 // The field must be accessible in the context of the structured binding. 1465 // We already checked that the base class is accessible. 1466 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1467 // const_cast here. 1468 S.CheckStructuredBindingMemberAccess( 1469 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1470 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1471 BasePair.getAccess(), FD->getAccess()))); 1472 1473 // Initialize the binding to Src.FD. 1474 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1475 if (E.isInvalid()) 1476 return true; 1477 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1478 VK_LValue, &BasePath); 1479 if (E.isInvalid()) 1480 return true; 1481 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1482 CXXScopeSpec(), FD, 1483 DeclAccessPair::make(FD, FD->getAccess()), 1484 DeclarationNameInfo(FD->getDeclName(), Loc)); 1485 if (E.isInvalid()) 1486 return true; 1487 1488 // If the type of the member is T, the referenced type is cv T, where cv is 1489 // the cv-qualification of the decomposition expression. 1490 // 1491 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1492 // 'const' to the type of the field. 1493 Qualifiers Q = DecompType.getQualifiers(); 1494 if (FD->isMutable()) 1495 Q.removeConst(); 1496 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1497 } 1498 1499 if (I != Bindings.size()) 1500 return DiagnoseBadNumberOfBindings(); 1501 1502 return false; 1503} 1504 1505void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1506 QualType DecompType = DD->getType(); 1507 1508 // If the type of the decomposition is dependent, then so is the type of 1509 // each binding. 1510 if (DecompType->isDependentType()) { 1511 for (auto *B : DD->bindings()) 1512 B->setType(Context.DependentTy); 1513 return; 1514 } 1515 1516 DecompType = DecompType.getNonReferenceType(); 1517 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1518 1519 // C++1z [dcl.decomp]/2: 1520 // If E is an array type [...] 1521 // As an extension, we also support decomposition of built-in complex and 1522 // vector types. 1523 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1524 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1525 DD->setInvalidDecl(); 1526 return; 1527 } 1528 if (auto *VT = DecompType->getAs<VectorType>()) { 1529 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1530 DD->setInvalidDecl(); 1531 return; 1532 } 1533 if (auto *CT = DecompType->getAs<ComplexType>()) { 1534 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1535 DD->setInvalidDecl(); 1536 return; 1537 } 1538 1539 // C++1z [dcl.decomp]/3: 1540 // if the expression std::tuple_size<E>::value is a well-formed integral 1541 // constant expression, [...] 1542 llvm::APSInt TupleSize(32); 1543 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1544 case IsTupleLike::Error: 1545 DD->setInvalidDecl(); 1546 return; 1547 1548 case IsTupleLike::TupleLike: 1549 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1550 DD->setInvalidDecl(); 1551 return; 1552 1553 case IsTupleLike::NotTupleLike: 1554 break; 1555 } 1556 1557 // C++1z [dcl.dcl]/8: 1558 // [E shall be of array or non-union class type] 1559 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1560 if (!RD || RD->isUnion()) { 1561 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1562 << DD << !RD << DecompType; 1563 DD->setInvalidDecl(); 1564 return; 1565 } 1566 1567 // C++1z [dcl.decomp]/4: 1568 // all of E's non-static data members shall be [...] direct members of 1569 // E or of the same unambiguous public base class of E, ... 1570 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1571 DD->setInvalidDecl(); 1572} 1573 1574/// Merge the exception specifications of two variable declarations. 1575/// 1576/// This is called when there's a redeclaration of a VarDecl. The function 1577/// checks if the redeclaration might have an exception specification and 1578/// validates compatibility and merges the specs if necessary. 1579void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1580 // Shortcut if exceptions are disabled. 1581 if (!getLangOpts().CXXExceptions) 1582 return; 1583 1584 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", 1585, __extension__ __PRETTY_FUNCTION__
))
1585 "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", 1585, __extension__ __PRETTY_FUNCTION__
))
; 1586 1587 QualType NewType = New->getType(); 1588 QualType OldType = Old->getType(); 1589 1590 // We're only interested in pointers and references to functions, as well 1591 // as pointers to member functions. 1592 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1593 NewType = R->getPointeeType(); 1594 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1595 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1596 NewType = P->getPointeeType(); 1597 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1598 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1599 NewType = M->getPointeeType(); 1600 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1601 } 1602 1603 if (!NewType->isFunctionProtoType()) 1604 return; 1605 1606 // There's lots of special cases for functions. For function pointers, system 1607 // libraries are hopefully not as broken so that we don't need these 1608 // workarounds. 1609 if (CheckEquivalentExceptionSpec( 1610 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1611 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1612 New->setInvalidDecl(); 1613 } 1614} 1615 1616/// CheckCXXDefaultArguments - Verify that the default arguments for a 1617/// function declaration are well-formed according to C++ 1618/// [dcl.fct.default]. 1619void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1620 unsigned NumParams = FD->getNumParams(); 1621 unsigned ParamIdx = 0; 1622 1623 // This checking doesn't make sense for explicit specializations; their 1624 // default arguments are determined by the declaration we're specializing, 1625 // not by FD. 1626 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1627 return; 1628 if (auto *FTD = FD->getDescribedFunctionTemplate()) 1629 if (FTD->isMemberSpecialization()) 1630 return; 1631 1632 // Find first parameter with a default argument 1633 for (; ParamIdx < NumParams; ++ParamIdx) { 1634 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1635 if (Param->hasDefaultArg()) 1636 break; 1637 } 1638 1639 // C++20 [dcl.fct.default]p4: 1640 // In a given function declaration, each parameter subsequent to a parameter 1641 // with a default argument shall have a default argument supplied in this or 1642 // a previous declaration, unless the parameter was expanded from a 1643 // parameter pack, or shall be a function parameter pack. 1644 for (; ParamIdx < NumParams; ++ParamIdx) { 1645 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1646 if (!Param->hasDefaultArg() && !Param->isParameterPack() && 1647 !(CurrentInstantiationScope && 1648 CurrentInstantiationScope->isLocalPackExpansion(Param))) { 1649 if (Param->isInvalidDecl()) 1650 /* We already complained about this parameter. */; 1651 else if (Param->getIdentifier()) 1652 Diag(Param->getLocation(), 1653 diag::err_param_default_argument_missing_name) 1654 << Param->getIdentifier(); 1655 else 1656 Diag(Param->getLocation(), 1657 diag::err_param_default_argument_missing); 1658 } 1659 } 1660} 1661 1662/// Check that the given type is a literal type. Issue a diagnostic if not, 1663/// if Kind is Diagnose. 1664/// \return \c true if a problem has been found (and optionally diagnosed). 1665template <typename... Ts> 1666static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1667 SourceLocation Loc, QualType T, unsigned DiagID, 1668 Ts &&...DiagArgs) { 1669 if (T->isDependentType()) 1670 return false; 1671 1672 switch (Kind) { 1673 case Sema::CheckConstexprKind::Diagnose: 1674 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1675 std::forward<Ts>(DiagArgs)...); 1676 1677 case Sema::CheckConstexprKind::CheckValid: 1678 return !T->isLiteralType(SemaRef.Context); 1679 } 1680 1681 llvm_unreachable("unknown CheckConstexprKind")::llvm::llvm_unreachable_internal("unknown CheckConstexprKind"
, "clang/lib/Sema/SemaDeclCXX.cpp", 1681)
; 1682} 1683 1684/// Determine whether a destructor cannot be constexpr due to 1685static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1686 const CXXDestructorDecl *DD, 1687 Sema::CheckConstexprKind Kind) { 1688 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1689 const CXXRecordDecl *RD = 1690 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1691 if (!RD || RD->hasConstexprDestructor()) 1692 return true; 1693 1694 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1695 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1696 << static_cast<int>(DD->getConstexprKind()) << !FD 1697 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1698 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1699 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1700 } 1701 return false; 1702 }; 1703 1704 const CXXRecordDecl *RD = DD->getParent(); 1705 for (const CXXBaseSpecifier &B : RD->bases()) 1706 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1707 return false; 1708 for (const FieldDecl *FD : RD->fields()) 1709 if (!Check(FD->getLocation(), FD->getType(), FD)) 1710 return false; 1711 return true; 1712} 1713 1714/// Check whether a function's parameter types are all literal types. If so, 1715/// return true. If not, produce a suitable diagnostic and return false. 1716static bool CheckConstexprParameterTypes(Sema &SemaRef, 1717 const FunctionDecl *FD, 1718 Sema::CheckConstexprKind Kind) { 1719 unsigned ArgIndex = 0; 1720 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1721 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1722 e = FT->param_type_end(); 1723 i != e; ++i, ++ArgIndex) { 1724 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1725 assert(PD && "null in a parameter list")(static_cast <bool> (PD && "null in a parameter list"
) ? void (0) : __assert_fail ("PD && \"null in a parameter list\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 1725, __extension__ __PRETTY_FUNCTION__
))
; 1726 SourceLocation ParamLoc = PD->getLocation(); 1727 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1728 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1729 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1730 FD->isConsteval())) 1731 return false; 1732 } 1733 return true; 1734} 1735 1736/// Check whether a function's return type is a literal type. If so, return 1737/// true. If not, produce a suitable diagnostic and return false. 1738static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1739 Sema::CheckConstexprKind Kind) { 1740 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1741 diag::err_constexpr_non_literal_return, 1742 FD->isConsteval())) 1743 return false; 1744 return true; 1745} 1746 1747/// Get diagnostic %select index for tag kind for 1748/// record diagnostic message. 1749/// WARNING: Indexes apply to particular diagnostics only! 1750/// 1751/// \returns diagnostic %select index. 1752static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1753 switch (Tag) { 1754 case TTK_Struct: return 0; 1755 case TTK_Interface: return 1; 1756 case TTK_Class: return 2; 1757 default: llvm_unreachable("Invalid tag kind for record diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for record diagnostic!"
, "clang/lib/Sema/SemaDeclCXX.cpp", 1757)
; 1758 } 1759} 1760 1761static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1762 Stmt *Body, 1763 Sema::CheckConstexprKind Kind); 1764 1765// Check whether a function declaration satisfies the requirements of a 1766// constexpr function definition or a constexpr constructor definition. If so, 1767// return true. If not, produce appropriate diagnostics (unless asked not to by 1768// Kind) and return false. 1769// 1770// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1771bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1772 CheckConstexprKind Kind) { 1773 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1774 if (MD && MD->isInstance()) { 1775 // C++11 [dcl.constexpr]p4: 1776 // The definition of a constexpr constructor shall satisfy the following 1777 // constraints: 1778 // - the class shall not have any virtual base classes; 1779 // 1780 // FIXME: This only applies to constructors and destructors, not arbitrary 1781 // member functions. 1782 const CXXRecordDecl *RD = MD->getParent(); 1783 if (RD->getNumVBases()) { 1784 if (Kind == CheckConstexprKind::CheckValid) 1785 return false; 1786 1787 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1788 << isa<CXXConstructorDecl>(NewFD) 1789 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1790 for (const auto &I : RD->vbases()) 1791 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1792 << I.getSourceRange(); 1793 return false; 1794 } 1795 } 1796 1797 if (!isa<CXXConstructorDecl>(NewFD)) { 1798 // C++11 [dcl.constexpr]p3: 1799 // The definition of a constexpr function shall satisfy the following 1800 // constraints: 1801 // - it shall not be virtual; (removed in C++20) 1802 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1803 if (Method && Method->isVirtual()) { 1804 if (getLangOpts().CPlusPlus20) { 1805 if (Kind == CheckConstexprKind::Diagnose) 1806 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1807 } else { 1808 if (Kind == CheckConstexprKind::CheckValid) 1809 return false; 1810 1811 Method = Method->getCanonicalDecl(); 1812 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1813 1814 // If it's not obvious why this function is virtual, find an overridden 1815 // function which uses the 'virtual' keyword. 1816 const CXXMethodDecl *WrittenVirtual = Method; 1817 while (!WrittenVirtual->isVirtualAsWritten()) 1818 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1819 if (WrittenVirtual != Method) 1820 Diag(WrittenVirtual->getLocation(), 1821 diag::note_overridden_virtual_function); 1822 return false; 1823 } 1824 } 1825 1826 // - its return type shall be a literal type; 1827 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1828 return false; 1829 } 1830 1831 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1832 // A destructor can be constexpr only if the defaulted destructor could be; 1833 // we don't need to check the members and bases if we already know they all 1834 // have constexpr destructors. 1835 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1836 if (Kind == CheckConstexprKind::CheckValid) 1837 return false; 1838 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1839 return false; 1840 } 1841 } 1842 1843 // - each of its parameter types shall be a literal type; 1844 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1845 return false; 1846 1847 Stmt *Body = NewFD->getBody(); 1848 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", 1849, __extension__ __PRETTY_FUNCTION__
))
1849 "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", 1849, __extension__ __PRETTY_FUNCTION__
))
; 1850 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1851} 1852 1853/// Check the given declaration statement is legal within a constexpr function 1854/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1855/// 1856/// \return true if the body is OK (maybe only as an extension), false if we 1857/// have diagnosed a problem. 1858static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1859 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1860 Sema::CheckConstexprKind Kind) { 1861 // C++11 [dcl.constexpr]p3 and p4: 1862 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1863 // contain only 1864 for (const auto *DclIt : DS->decls()) { 1865 switch (DclIt->getKind()) { 1866 case Decl::StaticAssert: 1867 case Decl::Using: 1868 case Decl::UsingShadow: 1869 case Decl::UsingDirective: 1870 case Decl::UnresolvedUsingTypename: 1871 case Decl::UnresolvedUsingValue: 1872 case Decl::UsingEnum: 1873 // - static_assert-declarations 1874 // - using-declarations, 1875 // - using-directives, 1876 // - using-enum-declaration 1877 continue; 1878 1879 case Decl::Typedef: 1880 case Decl::TypeAlias: { 1881 // - typedef declarations and alias-declarations that do not define 1882 // classes or enumerations, 1883 const auto *TN = cast<TypedefNameDecl>(DclIt); 1884 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1885 // Don't allow variably-modified types in constexpr functions. 1886 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1887 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1888 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1889 << TL.getSourceRange() << TL.getType() 1890 << isa<CXXConstructorDecl>(Dcl); 1891 } 1892 return false; 1893 } 1894 continue; 1895 } 1896 1897 case Decl::Enum: 1898 case Decl::CXXRecord: 1899 // C++1y allows types to be defined, not just declared. 1900 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1901 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1902 SemaRef.Diag(DS->getBeginLoc(), 1903 SemaRef.getLangOpts().CPlusPlus14 1904 ? diag::warn_cxx11_compat_constexpr_type_definition 1905 : diag::ext_constexpr_type_definition) 1906 << isa<CXXConstructorDecl>(Dcl); 1907 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1908 return false; 1909 } 1910 } 1911 continue; 1912 1913 case Decl::EnumConstant: 1914 case Decl::IndirectField: 1915 case Decl::ParmVar: 1916 // These can only appear with other declarations which are banned in 1917 // C++11 and permitted in C++1y, so ignore them. 1918 continue; 1919 1920 case Decl::Var: 1921 case Decl::Decomposition: { 1922 // C++1y [dcl.constexpr]p3 allows anything except: 1923 // a definition of a variable of non-literal type or of static or 1924 // thread storage duration or [before C++2a] for which no 1925 // initialization is performed. 1926 const auto *VD = cast<VarDecl>(DclIt); 1927 if (VD->isThisDeclarationADefinition()) { 1928 if (VD->isStaticLocal()) { 1929 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1930 SemaRef.Diag(VD->getLocation(), 1931 SemaRef.getLangOpts().CPlusPlus23 1932 ? diag::warn_cxx20_compat_constexpr_var 1933 : diag::ext_constexpr_static_var) 1934 << isa<CXXConstructorDecl>(Dcl) 1935 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1936 } else if (!SemaRef.getLangOpts().CPlusPlus23) { 1937 return false; 1938 } 1939 } 1940 if (SemaRef.LangOpts.CPlusPlus23) { 1941 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1942 diag::warn_cxx20_compat_constexpr_var, 1943 isa<CXXConstructorDecl>(Dcl), 1944 /*variable of non-literal type*/ 2); 1945 } else if (CheckLiteralType( 1946 SemaRef, Kind, VD->getLocation(), VD->getType(), 1947 diag::err_constexpr_local_var_non_literal_type, 1948 isa<CXXConstructorDecl>(Dcl))) { 1949 return false; 1950 } 1951 if (!VD->getType()->isDependentType() && 1952 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1953 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1954 SemaRef.Diag( 1955 VD->getLocation(), 1956 SemaRef.getLangOpts().CPlusPlus20 1957 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1958 : diag::ext_constexpr_local_var_no_init) 1959 << isa<CXXConstructorDecl>(Dcl); 1960 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1961 return false; 1962 } 1963 continue; 1964 } 1965 } 1966 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1967 SemaRef.Diag(VD->getLocation(), 1968 SemaRef.getLangOpts().CPlusPlus14 1969 ? diag::warn_cxx11_compat_constexpr_local_var 1970 : diag::ext_constexpr_local_var) 1971 << isa<CXXConstructorDecl>(Dcl); 1972 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1973 return false; 1974 } 1975 continue; 1976 } 1977 1978 case Decl::NamespaceAlias: 1979 case Decl::Function: 1980 // These are disallowed in C++11 and permitted in C++1y. Allow them 1981 // everywhere as an extension. 1982 if (!Cxx1yLoc.isValid()) 1983 Cxx1yLoc = DS->getBeginLoc(); 1984 continue; 1985 1986 default: 1987 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1988 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1989 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1990 } 1991 return false; 1992 } 1993 } 1994 1995 return true; 1996} 1997 1998/// Check that the given field is initialized within a constexpr constructor. 1999/// 2000/// \param Dcl The constexpr constructor being checked. 2001/// \param Field The field being checked. This may be a member of an anonymous 2002/// struct or union nested within the class being checked. 2003/// \param Inits All declarations, including anonymous struct/union members and 2004/// indirect members, for which any initialization was provided. 2005/// \param Diagnosed Whether we've emitted the error message yet. Used to attach 2006/// multiple notes for different members to the same error. 2007/// \param Kind Whether we're diagnosing a constructor as written or determining 2008/// whether the formal requirements are satisfied. 2009/// \return \c false if we're checking for validity and the constructor does 2010/// not satisfy the requirements on a constexpr constructor. 2011static bool CheckConstexprCtorInitializer(Sema &SemaRef, 2012 const FunctionDecl *Dcl, 2013 FieldDecl *Field, 2014 llvm::SmallSet<Decl*, 16> &Inits, 2015 bool &Diagnosed, 2016 Sema::CheckConstexprKind Kind) { 2017 // In C++20 onwards, there's nothing to check for validity. 2018 if (Kind == Sema::CheckConstexprKind::CheckValid && 2019 SemaRef.getLangOpts().CPlusPlus20) 2020 return true; 2021 2022 if (Field->isInvalidDecl()) 2023 return true; 2024 2025 if (Field->isUnnamedBitfield()) 2026 return true; 2027 2028 // Anonymous unions with no variant members and empty anonymous structs do not 2029 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 2030 // indirect fields don't need initializing. 2031 if (Field->isAnonymousStructOrUnion() && 2032 (Field->getType()->isUnionType() 2033 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 2034 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 2035 return true; 2036 2037 if (!Inits.count(Field)) { 2038 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2039 if (!Diagnosed) { 2040 SemaRef.Diag(Dcl->getLocation(), 2041 SemaRef.getLangOpts().CPlusPlus20 2042 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 2043 : diag::ext_constexpr_ctor_missing_init); 2044 Diagnosed = true; 2045 } 2046 SemaRef.Diag(Field->getLocation(), 2047 diag::note_constexpr_ctor_missing_init); 2048 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2049 return false; 2050 } 2051 } else if (Field->isAnonymousStructOrUnion()) { 2052 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 2053 for (auto *I : RD->fields()) 2054 // If an anonymous union contains an anonymous struct of which any member 2055 // is initialized, all members must be initialized. 2056 if (!RD->isUnion() || Inits.count(I)) 2057 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2058 Kind)) 2059 return false; 2060 } 2061 return true; 2062} 2063 2064/// Check the provided statement is allowed in a constexpr function 2065/// definition. 2066static bool 2067CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 2068 SmallVectorImpl<SourceLocation> &ReturnStmts, 2069 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 2070 SourceLocation &Cxx2bLoc, 2071 Sema::CheckConstexprKind Kind) { 2072 // - its function-body shall be [...] a compound-statement that contains only 2073 switch (S->getStmtClass()) { 2074 case Stmt::NullStmtClass: 2075 // - null statements, 2076 return true; 2077 2078 case Stmt::DeclStmtClass: 2079 // - static_assert-declarations 2080 // - using-declarations, 2081 // - using-directives, 2082 // - typedef declarations and alias-declarations that do not define 2083 // classes or enumerations, 2084 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 2085 return false; 2086 return true; 2087 2088 case Stmt::ReturnStmtClass: 2089 // - and exactly one return statement; 2090 if (isa<CXXConstructorDecl>(Dcl)) { 2091 // C++1y allows return statements in constexpr constructors. 2092 if (!Cxx1yLoc.isValid()) 2093 Cxx1yLoc = S->getBeginLoc(); 2094 return true; 2095 } 2096 2097 ReturnStmts.push_back(S->getBeginLoc()); 2098 return true; 2099 2100 case Stmt::AttributedStmtClass: 2101 // Attributes on a statement don't affect its formal kind and hence don't 2102 // affect its validity in a constexpr function. 2103 return CheckConstexprFunctionStmt( 2104 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts, 2105 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind); 2106 2107 case Stmt::CompoundStmtClass: { 2108 // C++1y allows compound-statements. 2109 if (!Cxx1yLoc.isValid()) 2110 Cxx1yLoc = S->getBeginLoc(); 2111 2112 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2113 for (auto *BodyIt : CompStmt->body()) { 2114 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2115 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2116 return false; 2117 } 2118 return true; 2119 } 2120 2121 case Stmt::IfStmtClass: { 2122 // C++1y allows if-statements. 2123 if (!Cxx1yLoc.isValid()) 2124 Cxx1yLoc = S->getBeginLoc(); 2125 2126 IfStmt *If = cast<IfStmt>(S); 2127 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2128 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2129 return false; 2130 if (If->getElse() && 2131 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2132 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2133 return false; 2134 return true; 2135 } 2136 2137 case Stmt::WhileStmtClass: 2138 case Stmt::DoStmtClass: 2139 case Stmt::ForStmtClass: 2140 case Stmt::CXXForRangeStmtClass: 2141 case Stmt::ContinueStmtClass: 2142 // C++1y allows all of these. We don't allow them as extensions in C++11, 2143 // because they don't make sense without variable mutation. 2144 if (!SemaRef.getLangOpts().CPlusPlus14) 2145 break; 2146 if (!Cxx1yLoc.isValid()) 2147 Cxx1yLoc = S->getBeginLoc(); 2148 for (Stmt *SubStmt : S->children()) { 2149 if (SubStmt && 2150 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2151 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2152 return false; 2153 } 2154 return true; 2155 2156 case Stmt::SwitchStmtClass: 2157 case Stmt::CaseStmtClass: 2158 case Stmt::DefaultStmtClass: 2159 case Stmt::BreakStmtClass: 2160 // C++1y allows switch-statements, and since they don't need variable 2161 // mutation, we can reasonably allow them in C++11 as an extension. 2162 if (!Cxx1yLoc.isValid()) 2163 Cxx1yLoc = S->getBeginLoc(); 2164 for (Stmt *SubStmt : S->children()) { 2165 if (SubStmt && 2166 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2167 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2168 return false; 2169 } 2170 return true; 2171 2172 case Stmt::LabelStmtClass: 2173 case Stmt::GotoStmtClass: 2174 if (Cxx2bLoc.isInvalid()) 2175 Cxx2bLoc = S->getBeginLoc(); 2176 for (Stmt *SubStmt : S->children()) { 2177 if (SubStmt && 2178 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2179 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2180 return false; 2181 } 2182 return true; 2183 2184 case Stmt::GCCAsmStmtClass: 2185 case Stmt::MSAsmStmtClass: 2186 // C++2a allows inline assembly statements. 2187 case Stmt::CXXTryStmtClass: 2188 if (Cxx2aLoc.isInvalid()) 2189 Cxx2aLoc = S->getBeginLoc(); 2190 for (Stmt *SubStmt : S->children()) { 2191 if (SubStmt && 2192 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2193 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2194 return false; 2195 } 2196 return true; 2197 2198 case Stmt::CXXCatchStmtClass: 2199 // Do not bother checking the language mode (already covered by the 2200 // try block check). 2201 if (!CheckConstexprFunctionStmt( 2202 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts, 2203 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2204 return false; 2205 return true; 2206 2207 default: 2208 if (!isa<Expr>(S)) 2209 break; 2210 2211 // C++1y allows expression-statements. 2212 if (!Cxx1yLoc.isValid()) 2213 Cxx1yLoc = S->getBeginLoc(); 2214 return true; 2215 } 2216 2217 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2218 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2219 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2220 } 2221 return false; 2222} 2223 2224/// Check the body for the given constexpr function declaration only contains 2225/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2226/// 2227/// \return true if the body is OK, false if we have found or diagnosed a 2228/// problem. 2229static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2230 Stmt *Body, 2231 Sema::CheckConstexprKind Kind) { 2232 SmallVector<SourceLocation, 4> ReturnStmts; 2233 2234 if (isa<CXXTryStmt>(Body)) { 2235 // C++11 [dcl.constexpr]p3: 2236 // The definition of a constexpr function shall satisfy the following 2237 // constraints: [...] 2238 // - its function-body shall be = delete, = default, or a 2239 // compound-statement 2240 // 2241 // C++11 [dcl.constexpr]p4: 2242 // In the definition of a constexpr constructor, [...] 2243 // - its function-body shall not be a function-try-block; 2244 // 2245 // This restriction is lifted in C++2a, as long as inner statements also 2246 // apply the general constexpr rules. 2247 switch (Kind) { 2248 case Sema::CheckConstexprKind::CheckValid: 2249 if (!SemaRef.getLangOpts().CPlusPlus20) 2250 return false; 2251 break; 2252 2253 case Sema::CheckConstexprKind::Diagnose: 2254 SemaRef.Diag(Body->getBeginLoc(), 2255 !SemaRef.getLangOpts().CPlusPlus20 2256 ? diag::ext_constexpr_function_try_block_cxx20 2257 : diag::warn_cxx17_compat_constexpr_function_try_block) 2258 << isa<CXXConstructorDecl>(Dcl); 2259 break; 2260 } 2261 } 2262 2263 // - its function-body shall be [...] a compound-statement that contains only 2264 // [... list of cases ...] 2265 // 2266 // Note that walking the children here is enough to properly check for 2267 // CompoundStmt and CXXTryStmt body. 2268 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc; 2269 for (Stmt *SubStmt : Body->children()) { 2270 if (SubStmt && 2271 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2272 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) 2273 return false; 2274 } 2275 2276 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2277 // If this is only valid as an extension, report that we don't satisfy the 2278 // constraints of the current language. 2279 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) || 2280 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2281 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2282 return false; 2283 } else if (Cxx2bLoc.isValid()) { 2284 SemaRef.Diag(Cxx2bLoc, 2285 SemaRef.getLangOpts().CPlusPlus23 2286 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt 2287 : diag::ext_constexpr_body_invalid_stmt_cxx23) 2288 << isa<CXXConstructorDecl>(Dcl); 2289 } else if (Cxx2aLoc.isValid()) { 2290 SemaRef.Diag(Cxx2aLoc, 2291 SemaRef.getLangOpts().CPlusPlus20 2292 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2293 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2294 << isa<CXXConstructorDecl>(Dcl); 2295 } else if (Cxx1yLoc.isValid()) { 2296 SemaRef.Diag(Cxx1yLoc, 2297 SemaRef.getLangOpts().CPlusPlus14 2298 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2299 : diag::ext_constexpr_body_invalid_stmt) 2300 << isa<CXXConstructorDecl>(Dcl); 2301 } 2302 2303 if (const CXXConstructorDecl *Constructor 2304 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2305 const CXXRecordDecl *RD = Constructor->getParent(); 2306 // DR1359: 2307 // - every non-variant non-static data member and base class sub-object 2308 // shall be initialized; 2309 // DR1460: 2310 // - if the class is a union having variant members, exactly one of them 2311 // shall be initialized; 2312 if (RD->isUnion()) { 2313 if (Constructor->getNumCtorInitializers() == 0 && 2314 RD->hasVariantMembers()) { 2315 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2316 SemaRef.Diag( 2317 Dcl->getLocation(), 2318 SemaRef.getLangOpts().CPlusPlus20 2319 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2320 : diag::ext_constexpr_union_ctor_no_init); 2321 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2322 return false; 2323 } 2324 } 2325 } else if (!Constructor->isDependentContext() && 2326 !Constructor->isDelegatingConstructor()) { 2327 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", 2327, __extension__ __PRETTY_FUNCTION__
))
; 2328 2329 // Skip detailed checking if we have enough initializers, and we would 2330 // allow at most one initializer per member. 2331 bool AnyAnonStructUnionMembers = false; 2332 unsigned Fields = 0; 2333 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2334 E = RD->field_end(); I != E; ++I, ++Fields) { 2335 if (I->isAnonymousStructOrUnion()) { 2336 AnyAnonStructUnionMembers = true; 2337 break; 2338 } 2339 } 2340 // DR1460: 2341 // - if the class is a union-like class, but is not a union, for each of 2342 // its anonymous union members having variant members, exactly one of 2343 // them shall be initialized; 2344 if (AnyAnonStructUnionMembers || 2345 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2346 // Check initialization of non-static data members. Base classes are 2347 // always initialized so do not need to be checked. Dependent bases 2348 // might not have initializers in the member initializer list. 2349 llvm::SmallSet<Decl*, 16> Inits; 2350 for (const auto *I: Constructor->inits()) { 2351 if (FieldDecl *FD = I->getMember()) 2352 Inits.insert(FD); 2353 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2354 Inits.insert(ID->chain_begin(), ID->chain_end()); 2355 } 2356 2357 bool Diagnosed = false; 2358 for (auto *I : RD->fields()) 2359 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2360 Kind)) 2361 return false; 2362 } 2363 } 2364 } else { 2365 if (ReturnStmts.empty()) { 2366 // C++1y doesn't require constexpr functions to contain a 'return' 2367 // statement. We still do, unless the return type might be void, because 2368 // otherwise if there's no return statement, the function cannot 2369 // be used in a core constant expression. 2370 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2371 (Dcl->getReturnType()->isVoidType() || 2372 Dcl->getReturnType()->isDependentType()); 2373 switch (Kind) { 2374 case Sema::CheckConstexprKind::Diagnose: 2375 SemaRef.Diag(Dcl->getLocation(), 2376 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2377 : diag::err_constexpr_body_no_return) 2378 << Dcl->isConsteval(); 2379 if (!OK) 2380 return false; 2381 break; 2382 2383 case Sema::CheckConstexprKind::CheckValid: 2384 // The formal requirements don't include this rule in C++14, even 2385 // though the "must be able to produce a constant expression" rules 2386 // still imply it in some cases. 2387 if (!SemaRef.getLangOpts().CPlusPlus14) 2388 return false; 2389 break; 2390 } 2391 } else if (ReturnStmts.size() > 1) { 2392 switch (Kind) { 2393 case Sema::CheckConstexprKind::Diagnose: 2394 SemaRef.Diag( 2395 ReturnStmts.back(), 2396 SemaRef.getLangOpts().CPlusPlus14 2397 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2398 : diag::ext_constexpr_body_multiple_return); 2399 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2400 SemaRef.Diag(ReturnStmts[I], 2401 diag::note_constexpr_body_previous_return); 2402 break; 2403 2404 case Sema::CheckConstexprKind::CheckValid: 2405 if (!SemaRef.getLangOpts().CPlusPlus14) 2406 return false; 2407 break; 2408 } 2409 } 2410 } 2411 2412 // C++11 [dcl.constexpr]p5: 2413 // if no function argument values exist such that the function invocation 2414 // substitution would produce a constant expression, the program is 2415 // ill-formed; no diagnostic required. 2416 // C++11 [dcl.constexpr]p3: 2417 // - every constructor call and implicit conversion used in initializing the 2418 // return value shall be one of those allowed in a constant expression. 2419 // C++11 [dcl.constexpr]p4: 2420 // - every constructor involved in initializing non-static data members and 2421 // base class sub-objects shall be a constexpr constructor. 2422 // 2423 // Note that this rule is distinct from the "requirements for a constexpr 2424 // function", so is not checked in CheckValid mode. 2425 SmallVector<PartialDiagnosticAt, 8> Diags; 2426 if (Kind == Sema::CheckConstexprKind::Diagnose && 2427 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2428 SemaRef.Diag(Dcl->getLocation(), 2429 diag::ext_constexpr_function_never_constant_expr) 2430 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2431 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2432 SemaRef.Diag(Diags[I].first, Diags[I].second); 2433 // Don't return false here: we allow this for compatibility in 2434 // system headers. 2435 } 2436 2437 return true; 2438} 2439 2440/// Get the class that is directly named by the current context. This is the 2441/// class for which an unqualified-id in this scope could name a constructor 2442/// or destructor. 2443/// 2444/// If the scope specifier denotes a class, this will be that class. 2445/// If the scope specifier is empty, this will be the class whose 2446/// member-specification we are currently within. Otherwise, there 2447/// is no such class. 2448CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2449 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", 2449, __extension__ __PRETTY_FUNCTION__
))
; 2450 2451 if (SS && SS->isInvalid()) 2452 return nullptr; 2453 2454 if (SS && SS->isNotEmpty()) { 2455 DeclContext *DC = computeDeclContext(*SS, true); 2456 return dyn_cast_or_null<CXXRecordDecl>(DC); 2457 } 2458 2459 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2460} 2461 2462/// isCurrentClassName - Determine whether the identifier II is the 2463/// name of the class type currently being defined. In the case of 2464/// nested classes, this will only return true if II is the name of 2465/// the innermost class. 2466bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2467 const CXXScopeSpec *SS) { 2468 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2469 return CurDecl && &II == CurDecl->getIdentifier(); 2470} 2471 2472/// Determine whether the identifier II is a typo for the name of 2473/// the class type currently being defined. If so, update it to the identifier 2474/// that should have been used. 2475bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2476 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", 2476, __extension__ __PRETTY_FUNCTION__
))
; 2477 2478 if (!getLangOpts().SpellChecking) 2479 return false; 2480 2481 CXXRecordDecl *CurDecl; 2482 if (SS && SS->isSet() && !SS->isInvalid()) { 2483 DeclContext *DC = computeDeclContext(*SS, true); 2484 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2485 } else 2486 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2487 2488 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2489 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2490 < II->getLength()) { 2491 II = CurDecl->getIdentifier(); 2492 return true; 2493 } 2494 2495 return false; 2496} 2497 2498/// Determine whether the given class is a base class of the given 2499/// class, including looking at dependent bases. 2500static bool findCircularInheritance(const CXXRecordDecl *Class, 2501 const CXXRecordDecl *Current) { 2502 SmallVector<const CXXRecordDecl*, 8> Queue; 2503 2504 Class = Class->getCanonicalDecl(); 2505 while (true) { 2506 for (const auto &I : Current->bases()) { 2507 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2508 if (!Base) 2509 continue; 2510 2511 Base = Base->getDefinition(); 2512 if (!Base) 2513 continue; 2514 2515 if (Base->getCanonicalDecl() == Class) 2516 return true; 2517 2518 Queue.push_back(Base); 2519 } 2520 2521 if (Queue.empty()) 2522 return false; 2523 2524 Current = Queue.pop_back_val(); 2525 } 2526 2527 return false; 2528} 2529 2530/// Check the validity of a C++ base class specifier. 2531/// 2532/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2533/// and returns NULL otherwise. 2534CXXBaseSpecifier * 2535Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2536 SourceRange SpecifierRange, 2537 bool Virtual, AccessSpecifier Access, 2538 TypeSourceInfo *TInfo, 2539 SourceLocation EllipsisLoc) { 2540 // In HLSL, unspecified class access is public rather than private. 2541 if (getLangOpts().HLSL && Class->getTagKind() == TTK_Class && 2542 Access == AS_none) 2543 Access = AS_public; 2544 2545 QualType BaseType = TInfo->getType(); 2546 if (BaseType->containsErrors()) { 2547 // Already emitted a diagnostic when parsing the error type. 2548 return nullptr; 2549 } 2550 // C++ [class.union]p1: 2551 // A union shall not have base classes. 2552 if (Class->isUnion()) { 2553 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2554 << SpecifierRange; 2555 return nullptr; 2556 } 2557 2558 if (EllipsisLoc.isValid() && 2559 !TInfo->getType()->containsUnexpandedParameterPack()) { 2560 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2561 << TInfo->getTypeLoc().getSourceRange(); 2562 EllipsisLoc = SourceLocation(); 2563 } 2564 2565 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2566 2567 if (BaseType->isDependentType()) { 2568 // Make sure that we don't have circular inheritance among our dependent 2569 // bases. For non-dependent bases, the check for completeness below handles 2570 // this. 2571 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2572 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2573 ((BaseDecl = BaseDecl->getDefinition()) && 2574 findCircularInheritance(Class, BaseDecl))) { 2575 Diag(BaseLoc, diag::err_circular_inheritance) 2576 << BaseType << Context.getTypeDeclType(Class); 2577 2578 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2579 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2580 << BaseType; 2581 2582 return nullptr; 2583 } 2584 } 2585 2586 // Make sure that we don't make an ill-formed AST where the type of the 2587 // Class is non-dependent and its attached base class specifier is an 2588 // dependent type, which violates invariants in many clang code paths (e.g. 2589 // constexpr evaluator). If this case happens (in errory-recovery mode), we 2590 // explicitly mark the Class decl invalid. The diagnostic was already 2591 // emitted. 2592 if (!Class->getTypeForDecl()->isDependentType()) 2593 Class->setInvalidDecl(); 2594 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2595 Class->getTagKind() == TTK_Class, 2596 Access, TInfo, EllipsisLoc); 2597 } 2598 2599 // Base specifiers must be record types. 2600 if (!BaseType->isRecordType()) { 2601 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2602 return nullptr; 2603 } 2604 2605 // C++ [class.union]p1: 2606 // A union shall not be used as a base class. 2607 if (BaseType->isUnionType()) { 2608 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2609 return nullptr; 2610 } 2611 2612 // For the MS ABI, propagate DLL attributes to base class templates. 2613 if (Context.getTargetInfo().getCXXABI().isMicrosoft() || 2614 Context.getTargetInfo().getTriple().isPS()) { 2615 if (Attr *ClassAttr = getDLLAttr(Class)) { 2616 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2617 BaseType->getAsCXXRecordDecl())) { 2618 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2619 BaseLoc); 2620 } 2621 } 2622 } 2623 2624 // C++ [class.derived]p2: 2625 // The class-name in a base-specifier shall not be an incompletely 2626 // defined class. 2627 if (RequireCompleteType(BaseLoc, BaseType, 2628 diag::err_incomplete_base_class, SpecifierRange)) { 2629 Class->setInvalidDecl(); 2630 return nullptr; 2631 } 2632 2633 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2634 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2635 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", 2635, __extension__ __PRETTY_FUNCTION__
))
; 2636 BaseDecl = BaseDecl->getDefinition(); 2637 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", 2637, __extension__ __PRETTY_FUNCTION__
))
; 2638 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2639 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", 2639, __extension__ __PRETTY_FUNCTION__
))
; 2640 2641 // Microsoft docs say: 2642 // "If a base-class has a code_seg attribute, derived classes must have the 2643 // same attribute." 2644 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2645 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2646 if ((DerivedCSA || BaseCSA) && 2647 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2648 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2649 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2650 << CXXBaseDecl; 2651 return nullptr; 2652 } 2653 2654 // A class which contains a flexible array member is not suitable for use as a 2655 // base class: 2656 // - If the layout determines that a base comes before another base, 2657 // the flexible array member would index into the subsequent base. 2658 // - If the layout determines that base comes before the derived class, 2659 // the flexible array member would index into the derived class. 2660 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2661 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2662 << CXXBaseDecl->getDeclName(); 2663 return nullptr; 2664 } 2665 2666 // C++ [class]p3: 2667 // If a class is marked final and it appears as a base-type-specifier in 2668 // base-clause, the program is ill-formed. 2669 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2670 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2671 << CXXBaseDecl->getDeclName() 2672 << FA->isSpelledAsSealed(); 2673 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2674 << CXXBaseDecl->getDeclName() << FA->getRange(); 2675 return nullptr; 2676 } 2677 2678 if (BaseDecl->isInvalidDecl()) 2679 Class->setInvalidDecl(); 2680 2681 // Create the base specifier. 2682 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2683 Class->getTagKind() == TTK_Class, 2684 Access, TInfo, EllipsisLoc); 2685} 2686 2687/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2688/// one entry in the base class list of a class specifier, for 2689/// example: 2690/// class foo : public bar, virtual private baz { 2691/// 'public bar' and 'virtual private baz' are each base-specifiers. 2692BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2693 const ParsedAttributesView &Attributes, 2694 bool Virtual, AccessSpecifier Access, 2695 ParsedType basetype, SourceLocation BaseLoc, 2696 SourceLocation EllipsisLoc) { 2697 if (!classdecl) 2698 return true; 2699 2700 AdjustDeclIfTemplate(classdecl); 2701 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2702 if (!Class) 2703 return true; 2704 2705 // We haven't yet attached the base specifiers. 2706 Class->setIsParsingBaseSpecifiers(); 2707 2708 // We do not support any C++11 attributes on base-specifiers yet. 2709 // Diagnose any attributes we see. 2710 for (const ParsedAttr &AL : Attributes) { 2711 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2712 continue; 2713 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2714 ? (unsigned)diag::warn_unknown_attribute_ignored 2715 : (unsigned)diag::err_base_specifier_attribute) 2716 << AL << AL.getRange(); 2717 } 2718 2719 TypeSourceInfo *TInfo = nullptr; 2720 GetTypeFromParser(basetype, &TInfo); 2721 2722 if (EllipsisLoc.isInvalid() && 2723 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2724 UPPC_BaseType)) 2725 return true; 2726 2727 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2728 Virtual, Access, TInfo, 2729 EllipsisLoc)) 2730 return BaseSpec; 2731 else 2732 Class->setInvalidDecl(); 2733 2734 return true; 2735} 2736 2737/// Use small set to collect indirect bases. As this is only used 2738/// locally, there's no need to abstract the small size parameter. 2739typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2740 2741/// Recursively add the bases of Type. Don't add Type itself. 2742static void 2743NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2744 const QualType &Type) 2745{ 2746 // Even though the incoming type is a base, it might not be 2747 // a class -- it could be a template parm, for instance. 2748 if (auto Rec = Type->getAs<RecordType>()) { 2749 auto Decl = Rec->getAsCXXRecordDecl(); 2750 2751 // Iterate over its bases. 2752 for (const auto &BaseSpec : Decl->bases()) { 2753 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2754 .getUnqualifiedType(); 2755 if (Set.insert(Base).second) 2756 // If we've not already seen it, recurse. 2757 NoteIndirectBases(Context, Set, Base); 2758 } 2759 } 2760} 2761 2762/// Performs the actual work of attaching the given base class 2763/// specifiers to a C++ class. 2764bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2765 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2766 if (Bases.empty()) 2767 return false; 2768 2769 // Used to keep track of which base types we have already seen, so 2770 // that we can properly diagnose redundant direct base types. Note 2771 // that the key is always the unqualified canonical type of the base 2772 // class. 2773 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2774 2775 // Used to track indirect bases so we can see if a direct base is 2776 // ambiguous. 2777 IndirectBaseSet IndirectBaseTypes; 2778 2779 // Copy non-redundant base specifiers into permanent storage. 2780 unsigned NumGoodBases = 0; 2781 bool Invalid = false; 2782 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2783 QualType NewBaseType 2784 = Context.getCanonicalType(Bases[idx]->getType()); 2785 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2786 2787 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2788 if (KnownBase) { 2789 // C++ [class.mi]p3: 2790 // A class shall not be specified as a direct base class of a 2791 // derived class more than once. 2792 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2793 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2794 2795 // Delete the duplicate base class specifier; we're going to 2796 // overwrite its pointer later. 2797 Context.Deallocate(Bases[idx]); 2798 2799 Invalid = true; 2800 } else { 2801 // Okay, add this new base class. 2802 KnownBase = Bases[idx]; 2803 Bases[NumGoodBases++] = Bases[idx]; 2804 2805 if (NewBaseType->isDependentType()) 2806 continue; 2807 // Note this base's direct & indirect bases, if there could be ambiguity. 2808 if (Bases.size() > 1) 2809 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2810 2811 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2812 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2813 if (Class->isInterface() && 2814 (!RD->isInterfaceLike() || 2815 KnownBase->getAccessSpecifier() != AS_public)) { 2816 // The Microsoft extension __interface does not permit bases that 2817 // are not themselves public interfaces. 2818 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2819 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2820 << RD->getSourceRange(); 2821 Invalid = true; 2822 } 2823 if (RD->hasAttr<WeakAttr>()) 2824 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2825 } 2826 } 2827 } 2828 2829 // Attach the remaining base class specifiers to the derived class. 2830 Class->setBases(Bases.data(), NumGoodBases); 2831 2832 // Check that the only base classes that are duplicate are virtual. 2833 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2834 // Check whether this direct base is inaccessible due to ambiguity. 2835 QualType BaseType = Bases[idx]->getType(); 2836 2837 // Skip all dependent types in templates being used as base specifiers. 2838 // Checks below assume that the base specifier is a CXXRecord. 2839 if (BaseType->isDependentType()) 2840 continue; 2841 2842 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2843 .getUnqualifiedType(); 2844 2845 if (IndirectBaseTypes.count(CanonicalBase)) { 2846 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2847 /*DetectVirtual=*/true); 2848 bool found 2849 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2850 assert(found)(static_cast <bool> (found) ? void (0) : __assert_fail (
"found", "clang/lib/Sema/SemaDeclCXX.cpp", 2850, __extension__
__PRETTY_FUNCTION__))
; 2851 (void)found; 2852 2853 if (Paths.isAmbiguous(CanonicalBase)) 2854 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2855 << BaseType << getAmbiguousPathsDisplayString(Paths) 2856 << Bases[idx]->getSourceRange(); 2857 else 2858 assert(Bases[idx]->isVirtual())(static_cast <bool> (Bases[idx]->isVirtual()) ? void
(0) : __assert_fail ("Bases[idx]->isVirtual()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 2858, __extension__ __PRETTY_FUNCTION__))
; 2859 } 2860 2861 // Delete the base class specifier, since its data has been copied 2862 // into the CXXRecordDecl. 2863 Context.Deallocate(Bases[idx]); 2864 } 2865 2866 return Invalid; 2867} 2868 2869/// ActOnBaseSpecifiers - Attach the given base specifiers to the 2870/// class, after checking whether there are any duplicate base 2871/// classes. 2872void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2873 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2874 if (!ClassDecl || Bases.empty()) 2875 return; 2876 2877 AdjustDeclIfTemplate(ClassDecl); 2878 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2879} 2880 2881/// Determine whether the type \p Derived is a C++ class that is 2882/// derived from the type \p Base. 2883bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2884 if (!getLangOpts().CPlusPlus) 2885 return false; 2886 2887 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2888 if (!DerivedRD) 2889 return false; 2890 2891 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2892 if (!BaseRD) 2893 return false; 2894 2895 // If either the base or the derived type is invalid, don't try to 2896 // check whether one is derived from the other. 2897 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2898 return false; 2899 2900 // FIXME: In a modules build, do we need the entire path to be visible for us 2901 // to be able to use the inheritance relationship? 2902 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2903 return false; 2904 2905 return DerivedRD->isDerivedFrom(BaseRD); 2906} 2907 2908/// Determine whether the type \p Derived is a C++ class that is 2909/// derived from the type \p Base. 2910bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2911 CXXBasePaths &Paths) { 2912 if (!getLangOpts().CPlusPlus) 2913 return false; 2914 2915 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2916 if (!DerivedRD) 2917 return false; 2918 2919 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2920 if (!BaseRD) 2921 return false; 2922 2923 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2924 return false; 2925 2926 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2927} 2928 2929static void BuildBasePathArray(const CXXBasePath &Path, 2930 CXXCastPath &BasePathArray) { 2931 // We first go backward and check if we have a virtual base. 2932 // FIXME: It would be better if CXXBasePath had the base specifier for 2933 // the nearest virtual base. 2934 unsigned Start = 0; 2935 for (unsigned I = Path.size(); I != 0; --I) { 2936 if (Path[I - 1].Base->isVirtual()) { 2937 Start = I - 1; 2938 break; 2939 } 2940 } 2941 2942 // Now add all bases. 2943 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2944 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2945} 2946 2947 2948void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2949 CXXCastPath &BasePathArray) { 2950 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", 2950, __extension__ __PRETTY_FUNCTION__
))
; 2951 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", 2951, __extension__ __PRETTY_FUNCTION__
))
; 2952 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2953} 2954/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2955/// conversion (where Derived and Base are class types) is 2956/// well-formed, meaning that the conversion is unambiguous (and 2957/// that all of the base classes are accessible). Returns true 2958/// and emits a diagnostic if the code is ill-formed, returns false 2959/// otherwise. Loc is the location where this routine should point to 2960/// if there is an error, and Range is the source range to highlight 2961/// if there is an error. 2962/// 2963/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2964/// diagnostic for the respective type of error will be suppressed, but the 2965/// check for ill-formed code will still be performed. 2966bool 2967Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2968 unsigned InaccessibleBaseID, 2969 unsigned AmbiguousBaseConvID, 2970 SourceLocation Loc, SourceRange Range, 2971 DeclarationName Name, 2972 CXXCastPath *BasePath, 2973 bool IgnoreAccess) { 2974 // First, determine whether the path from Derived to Base is 2975 // ambiguous. This is slightly more expensive than checking whether 2976 // the Derived to Base conversion exists, because here we need to 2977 // explore multiple paths to determine if there is an ambiguity. 2978 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2979 /*DetectVirtual=*/false); 2980 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2981 if (!DerivationOkay) 2982 return true; 2983 2984 const CXXBasePath *Path = nullptr; 2985 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2986 Path = &Paths.front(); 2987 2988 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2989 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2990 // user to access such bases. 2991 if (!Path && getLangOpts().MSVCCompat) { 2992 for (const CXXBasePath &PossiblePath : Paths) { 2993 if (PossiblePath.size() == 1) { 2994 Path = &PossiblePath; 2995 if (AmbiguousBaseConvID) 2996 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2997 << Base << Derived << Range; 2998 break; 2999 } 3000 } 3001 } 3002 3003 if (Path) { 3004 if (!IgnoreAccess) { 3005 // Check that the base class can be accessed. 3006 switch ( 3007 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 3008 case AR_inaccessible: 3009 return true; 3010 case AR_accessible: 3011 case AR_dependent: 3012 case AR_delayed: 3013 break; 3014 } 3015 } 3016 3017 // Build a base path if necessary. 3018 if (BasePath) 3019 ::BuildBasePathArray(*Path, *BasePath); 3020 return false; 3021 } 3022 3023 if (AmbiguousBaseConvID) { 3024 // We know that the derived-to-base conversion is ambiguous, and 3025 // we're going to produce a diagnostic. Perform the derived-to-base 3026 // search just one more time to compute all of the possible paths so 3027 // that we can print them out. This is more expensive than any of 3028 // the previous derived-to-base checks we've done, but at this point 3029 // performance isn't as much of an issue. 3030 Paths.clear(); 3031 Paths.setRecordingPaths(true); 3032 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 3033 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", 3033, __extension__ __PRETTY_FUNCTION__
))
; 3034 (void)StillOkay; 3035 3036 // Build up a textual representation of the ambiguous paths, e.g., 3037 // D -> B -> A, that will be used to illustrate the ambiguous 3038 // conversions in the diagnostic. We only print one of the paths 3039 // to each base class subobject. 3040 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3041 3042 Diag(Loc, AmbiguousBaseConvID) 3043 << Derived << Base << PathDisplayStr << Range << Name; 3044 } 3045 return true; 3046} 3047 3048bool 3049Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 3050 SourceLocation Loc, SourceRange Range, 3051 CXXCastPath *BasePath, 3052 bool IgnoreAccess) { 3053 return CheckDerivedToBaseConversion( 3054 Derived, Base, diag::err_upcast_to_inaccessible_base, 3055 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 3056 BasePath, IgnoreAccess); 3057} 3058 3059 3060/// Builds a string representing ambiguous paths from a 3061/// specific derived class to different subobjects of the same base 3062/// class. 3063/// 3064/// This function builds a string that can be used in error messages 3065/// to show the different paths that one can take through the 3066/// inheritance hierarchy to go from the derived class to different 3067/// subobjects of a base class. The result looks something like this: 3068/// @code 3069/// struct D -> struct B -> struct A 3070/// struct D -> struct C -> struct A 3071/// @endcode 3072std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 3073 std::string PathDisplayStr; 3074 std::set<unsigned> DisplayedPaths; 3075 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3076 Path != Paths.end(); ++Path) { 3077 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 3078 // We haven't displayed a path to this particular base 3079 // class subobject yet. 3080 PathDisplayStr += "\n "; 3081 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 3082 for (CXXBasePath::const_iterator Element = Path->begin(); 3083 Element != Path->end(); ++Element) 3084 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 3085 } 3086 } 3087 3088 return PathDisplayStr; 3089} 3090 3091//===----------------------------------------------------------------------===// 3092// C++ class member Handling 3093//===----------------------------------------------------------------------===// 3094 3095/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 3096bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 3097 SourceLocation ColonLoc, 3098 const ParsedAttributesView &Attrs) { 3099 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", 3099, __extension__ __PRETTY_FUNCTION__
))
; 3100 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 3101 ASLoc, ColonLoc); 3102 CurContext->addHiddenDecl(ASDecl); 3103 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 3104} 3105 3106/// CheckOverrideControl - Check C++11 override control semantics. 3107void Sema::CheckOverrideControl(NamedDecl *D) { 3108 if (D->isInvalidDecl()) 3109 return; 3110 3111 // We only care about "override" and "final" declarations. 3112 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 3113 return; 3114 3115 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3116 3117 // We can't check dependent instance methods. 3118 if (MD && MD->isInstance() && 3119 (MD->getParent()->hasAnyDependentBases() || 3120 MD->getType()->isDependentType())) 3121 return; 3122 3123 if (MD && !MD->isVirtual()) { 3124 // If we have a non-virtual method, check if it hides a virtual method. 3125 // (In that case, it's most likely the method has the wrong type.) 3126 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3127 FindHiddenVirtualMethods(MD, OverloadedMethods); 3128 3129 if (!OverloadedMethods.empty()) { 3130 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3131 Diag(OA->getLocation(), 3132 diag::override_keyword_hides_virtual_member_function) 3133 << "override" << (OverloadedMethods.size() > 1); 3134 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3135 Diag(FA->getLocation(), 3136 diag::override_keyword_hides_virtual_member_function) 3137 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3138 << (OverloadedMethods.size() > 1); 3139 } 3140 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3141 MD->setInvalidDecl(); 3142 return; 3143 } 3144 // Fall through into the general case diagnostic. 3145 // FIXME: We might want to attempt typo correction here. 3146 } 3147 3148 if (!MD || !MD->isVirtual()) { 3149 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3150 Diag(OA->getLocation(), 3151 diag::override_keyword_only_allowed_on_virtual_member_functions) 3152 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3153 D->dropAttr<OverrideAttr>(); 3154 } 3155 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3156 Diag(FA->getLocation(), 3157 diag::override_keyword_only_allowed_on_virtual_member_functions) 3158 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3159 << FixItHint::CreateRemoval(FA->getLocation()); 3160 D->dropAttr<FinalAttr>(); 3161 } 3162 return; 3163 } 3164 3165 // C++11 [class.virtual]p5: 3166 // If a function is marked with the virt-specifier override and 3167 // does not override a member function of a base class, the program is 3168 // ill-formed. 3169 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3170 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3171 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3172 << MD->getDeclName(); 3173} 3174 3175void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3176 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3177 return; 3178 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3179 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3180 return; 3181 3182 SourceLocation Loc = MD->getLocation(); 3183 SourceLocation SpellingLoc = Loc; 3184 if (getSourceManager().isMacroArgExpansion(Loc)) 3185 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3186 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3187 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3188 return; 3189 3190 if (MD->size_overridden_methods() > 0) { 3191 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3192 unsigned DiagID = 3193 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3194 ? DiagInconsistent 3195 : DiagSuggest; 3196 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3197 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3198 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3199 }; 3200 if (isa<CXXDestructorDecl>(MD)) 3201 EmitDiag( 3202 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3203 diag::warn_suggest_destructor_marked_not_override_overriding); 3204 else 3205 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3206 diag::warn_suggest_function_marked_not_override_overriding); 3207 } 3208} 3209 3210/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3211/// function overrides a virtual member function marked 'final', according to 3212/// C++11 [class.virtual]p4. 3213bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3214 const CXXMethodDecl *Old) { 3215 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3216 if (!FA) 3217 return false; 3218 3219 Diag(New->getLocation(), diag::err_final_function_overridden) 3220 << New->getDeclName() 3221 << FA->isSpelledAsSealed(); 3222 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3223 return true; 3224} 3225 3226static bool InitializationHasSideEffects(const FieldDecl &FD) { 3227 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3228 // FIXME: Destruction of ObjC lifetime types has side-effects. 3229 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3230 return !RD->isCompleteDefinition() || 3231 !RD->hasTrivialDefaultConstructor() || 3232 !RD->hasTrivialDestructor(); 3233 return false; 3234} 3235 3236// Check if there is a field shadowing. 3237void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3238 DeclarationName FieldName, 3239 const CXXRecordDecl *RD, 3240 bool DeclIsField) { 3241 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3242 return; 3243 3244 // To record a shadowed field in a base 3245 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3246 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3247 CXXBasePath &Path) { 3248 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3249 // Record an ambiguous path directly 3250 if (Bases.find(Base) != Bases.end()) 3251 return true; 3252 for (const auto Field : Base->lookup(FieldName)) { 3253 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3254 Field->getAccess() != AS_private) { 3255 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", 3255, __extension__ __PRETTY_FUNCTION__
))
; 3256 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", 3256, __extension__ __PRETTY_FUNCTION__
))
; 3257 Bases[Base] = Field; 3258 return true; 3259 } 3260 } 3261 return false; 3262 }; 3263 3264 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3265 /*DetectVirtual=*/true); 3266 if (!RD->lookupInBases(FieldShadowed, Paths)) 3267 return; 3268 3269 for (const auto &P : Paths) { 3270 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3271 auto It = Bases.find(Base); 3272 // Skip duplicated bases 3273 if (It == Bases.end()) 3274 continue; 3275 auto BaseField = It->second; 3276 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", 3276, __extension__ __PRETTY_FUNCTION__
))
; 3277 if (AS_none != 3278 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3279 Diag(Loc, diag::warn_shadow_field) 3280 << FieldName << RD << Base << DeclIsField; 3281 Diag(BaseField->getLocation(), diag::note_shadow_field); 3282 Bases.erase(It); 3283 } 3284 } 3285} 3286 3287/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3288/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3289/// bitfield width if there is one, 'InitExpr' specifies the initializer if 3290/// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3291/// present (but parsing it has been deferred). 3292NamedDecl * 3293Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3294 MultiTemplateParamsArg TemplateParameterLists, 3295 Expr *BW, const VirtSpecifiers &VS, 3296 InClassInitStyle InitStyle) { 3297 const DeclSpec &DS = D.getDeclSpec(); 3298 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3299 DeclarationName Name = NameInfo.getName(); 3300 SourceLocation Loc = NameInfo.getLoc(); 3301 3302 // For anonymous bitfields, the location should point to the type. 3303 if (Loc.isInvalid()) 3304 Loc = D.getBeginLoc(); 3305 3306 Expr *BitWidth = static_cast<Expr*>(BW); 3307 3308 assert(isa<CXXRecordDecl>(CurContext))(static_cast <bool> (isa<CXXRecordDecl>(CurContext
)) ? void (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)"
, "clang/lib/Sema/SemaDeclCXX.cpp", 3308, __extension__ __PRETTY_FUNCTION__
))
; 3309 assert(!DS.isFriendSpecified())(static_cast <bool> (!DS.isFriendSpecified()) ? void (0
) : __assert_fail ("!DS.isFriendSpecified()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 3309, __extension__ __PRETTY_FUNCTION__))
; 3310 3311 bool isFunc = D.isDeclarationOfFunction(); 3312 const ParsedAttr *MSPropertyAttr = 3313 D.getDeclSpec().getAttributes().getMSPropertyAttr(); 3314 3315 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3316 // The Microsoft extension __interface only permits public member functions 3317 // and prohibits constructors, destructors, operators, non-public member 3318 // functions, static methods and data members. 3319 unsigned InvalidDecl; 3320 bool ShowDeclName = true; 3321 if (!isFunc && 3322 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3323 InvalidDecl = 0; 3324 else if (!isFunc) 3325 InvalidDecl = 1; 3326 else if (AS != AS_public) 3327 InvalidDecl = 2; 3328 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3329 InvalidDecl = 3; 3330 else switch (Name.getNameKind()) { 3331 case DeclarationName::CXXConstructorName: 3332 InvalidDecl = 4; 3333 ShowDeclName = false; 3334 break; 3335 3336 case DeclarationName::CXXDestructorName: 3337 InvalidDecl = 5; 3338 ShowDeclName = false; 3339 break; 3340 3341 case DeclarationName::CXXOperatorName: 3342 case DeclarationName::CXXConversionFunctionName: 3343 InvalidDecl = 6; 3344 break; 3345 3346 default: 3347 InvalidDecl = 0; 3348 break; 3349 } 3350 3351 if (InvalidDecl) { 3352 if (ShowDeclName) 3353 Diag(Loc, diag::err_invalid_member_in_interface) 3354 << (InvalidDecl-1) << Name; 3355 else 3356 Diag(Loc, diag::err_invalid_member_in_interface) 3357 << (InvalidDecl-1) << ""; 3358 return nullptr; 3359 } 3360 } 3361 3362 // C++ 9.2p6: A member shall not be declared to have automatic storage 3363 // duration (auto, register) or with the extern storage-class-specifier. 3364 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3365 // data members and cannot be applied to names declared const or static, 3366 // and cannot be applied to reference members. 3367 switch (DS.getStorageClassSpec()) { 3368 case DeclSpec::SCS_unspecified: 3369 case DeclSpec::SCS_typedef: 3370 case DeclSpec::SCS_static: 3371 break; 3372 case DeclSpec::SCS_mutable: 3373 if (isFunc) { 3374 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3375 3376 // FIXME: It would be nicer if the keyword was ignored only for this 3377 // declarator. Otherwise we could get follow-up errors. 3378 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3379 } 3380 break; 3381 default: 3382 Diag(DS.getStorageClassSpecLoc(), 3383 diag::err_storageclass_invalid_for_member); 3384 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3385 break; 3386 } 3387 3388 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3389 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3390 !isFunc); 3391 3392 if (DS.hasConstexprSpecifier() && isInstField) { 3393 SemaDiagnosticBuilder B = 3394 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3395 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3396 if (InitStyle == ICIS_NoInit) { 3397 B << 0 << 0; 3398 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3399 B << FixItHint::CreateRemoval(ConstexprLoc); 3400 else { 3401 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3402 D.getMutableDeclSpec().ClearConstexprSpec(); 3403 const char *PrevSpec; 3404 unsigned DiagID; 3405 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3406 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3407 (void)Failed; 3408 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", 3408, __extension__ __PRETTY_FUNCTION__
))
; 3409 } 3410 } else { 3411 B << 1; 3412 const char *PrevSpec; 3413 unsigned DiagID; 3414 if (D.getMutableDeclSpec().SetStorageClassSpec( 3415 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3416 Context.getPrintingPolicy())) { 3417 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", 3418, __extension__ __PRETTY_FUNCTION__
))
3418 "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", 3418, __extension__ __PRETTY_FUNCTION__
))
; 3419 B << 1; 3420 } else { 3421 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3422 isInstField = false; 3423 } 3424 } 3425 } 3426 3427 NamedDecl *Member; 3428 if (isInstField) { 3429 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3430 3431 // Data members must have identifiers for names. 3432 if (!Name.isIdentifier()) { 3433 Diag(Loc, diag::err_bad_variable_name) 3434 << Name; 3435 return nullptr; 3436 } 3437 3438 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3439 3440 // Member field could not be with "template" keyword. 3441 // So TemplateParameterLists should be empty in this case. 3442 if (TemplateParameterLists.size()) { 3443 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3444 if (TemplateParams->size()) { 3445 // There is no such thing as a member field template. 3446 Diag(D.getIdentifierLoc(), diag::err_template_member) 3447 << II 3448 << SourceRange(TemplateParams->getTemplateLoc(), 3449 TemplateParams->getRAngleLoc()); 3450 } else { 3451 // There is an extraneous 'template<>' for this member. 3452 Diag(TemplateParams->getTemplateLoc(), 3453 diag::err_template_member_noparams) 3454 << II 3455 << SourceRange(TemplateParams->getTemplateLoc(), 3456 TemplateParams->getRAngleLoc()); 3457 } 3458 return nullptr; 3459 } 3460 3461 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 3462 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments) 3463 << II 3464 << SourceRange(D.getName().TemplateId->LAngleLoc, 3465 D.getName().TemplateId->RAngleLoc) 3466 << D.getName().TemplateId->LAngleLoc; 3467 D.SetIdentifier(II, Loc); 3468 } 3469 3470 if (SS.isSet() && !SS.isInvalid()) { 3471 // The user provided a superfluous scope specifier inside a class 3472 // definition: 3473 // 3474 // class X { 3475 // int X::member; 3476 // }; 3477 if (DeclContext *DC = computeDeclContext(SS, false)) 3478 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3479 D.getName().getKind() == 3480 UnqualifiedIdKind::IK_TemplateId); 3481 else 3482 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3483 << Name << SS.getRange(); 3484 3485 SS.clear(); 3486 } 3487 3488 if (MSPropertyAttr) { 3489 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3490 BitWidth, InitStyle, AS, *MSPropertyAttr); 3491 if (!Member) 3492 return nullptr; 3493 isInstField = false; 3494 } else { 3495 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3496 BitWidth, InitStyle, AS); 3497 if (!Member) 3498 return nullptr; 3499 } 3500 3501 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3502 } else { 3503 Member = HandleDeclarator(S, D, TemplateParameterLists); 3504 if (!Member) 3505 return nullptr; 3506 3507 // Non-instance-fields can't have a bitfield. 3508 if (BitWidth) { 3509 if (Member->isInvalidDecl()) { 3510 // don't emit another diagnostic. 3511 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3512 // C++ 9.6p3: A bit-field shall not be a static member. 3513 // "static member 'A' cannot be a bit-field" 3514 Diag(Loc, diag::err_static_not_bitfield) 3515 << Name << BitWidth->getSourceRange(); 3516 } else if (isa<TypedefDecl>(Member)) { 3517 // "typedef member 'x' cannot be a bit-field" 3518 Diag(Loc, diag::err_typedef_not_bitfield) 3519 << Name << BitWidth->getSourceRange(); 3520 } else { 3521 // A function typedef ("typedef int f(); f a;"). 3522 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3523 Diag(Loc, diag::err_not_integral_type_bitfield) 3524 << Name << cast<ValueDecl>(Member)->getType() 3525 << BitWidth->getSourceRange(); 3526 } 3527 3528 BitWidth = nullptr; 3529 Member->setInvalidDecl(); 3530 } 3531 3532 NamedDecl *NonTemplateMember = Member; 3533 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3534 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3535 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3536 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3537 3538 Member->setAccess(AS); 3539 3540 // If we have declared a member function template or static data member 3541 // template, set the access of the templated declaration as well. 3542 if (NonTemplateMember != Member) 3543 NonTemplateMember->setAccess(AS); 3544 3545 // C++ [temp.deduct.guide]p3: 3546 // A deduction guide [...] for a member class template [shall be 3547 // declared] with the same access [as the template]. 3548 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3549 auto *TD = DG->getDeducedTemplate(); 3550 // Access specifiers are only meaningful if both the template and the 3551 // deduction guide are from the same scope. 3552 if (AS != TD->getAccess() && 3553 TD->getDeclContext()->getRedeclContext()->Equals( 3554 DG->getDeclContext()->getRedeclContext())) { 3555 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3556 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3557 << TD->getAccess(); 3558 const AccessSpecDecl *LastAccessSpec = nullptr; 3559 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3560 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3561 LastAccessSpec = AccessSpec; 3562 } 3563 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", 3563, __extension__ __PRETTY_FUNCTION__
))
; 3564 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3565 << AS; 3566 } 3567 } 3568 } 3569 3570 if (VS.isOverrideSpecified()) 3571 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc())); 3572 if (VS.isFinalSpecified()) 3573 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(), 3574 VS.isFinalSpelledSealed() 3575 ? FinalAttr::Keyword_sealed 3576 : FinalAttr::Keyword_final)); 3577 3578 if (VS.getLastLocation().isValid()) { 3579 // Update the end location of a method that has a virt-specifiers. 3580 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3581 MD->setRangeEnd(VS.getLastLocation()); 3582 } 3583 3584 CheckOverrideControl(Member); 3585 3586 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", 3586, __extension__ __PRETTY_FUNCTION__
))
; 3587 3588 if (isInstField) { 3589 FieldDecl *FD = cast<FieldDecl>(Member); 3590 FieldCollector->Add(FD); 3591 3592 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3593 // Remember all explicit private FieldDecls that have a name, no side 3594 // effects and are not part of a dependent type declaration. 3595 if (!FD->isImplicit() && FD->getDeclName() && 3596 FD->getAccess() == AS_private && 3597 !FD->hasAttr<UnusedAttr>() && 3598 !FD->getParent()->isDependentContext() && 3599 !InitializationHasSideEffects(*FD)) 3600 UnusedPrivateFields.insert(FD); 3601 } 3602 } 3603 3604 return Member; 3605} 3606 3607namespace { 3608 class UninitializedFieldVisitor 3609 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3610 Sema &S; 3611 // List of Decls to generate a warning on. Also remove Decls that become 3612 // initialized. 3613 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3614 // List of base classes of the record. Classes are removed after their 3615 // initializers. 3616 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3617 // Vector of decls to be removed from the Decl set prior to visiting the 3618 // nodes. These Decls may have been initialized in the prior initializer. 3619 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3620 // If non-null, add a note to the warning pointing back to the constructor. 3621 const CXXConstructorDecl *Constructor; 3622 // Variables to hold state when processing an initializer list. When 3623 // InitList is true, special case initialization of FieldDecls matching 3624 // InitListFieldDecl. 3625 bool InitList; 3626 FieldDecl *InitListFieldDecl; 3627 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3628 3629 public: 3630 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3631 UninitializedFieldVisitor(Sema &S, 3632 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3633 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3634 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3635 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3636 3637 // Returns true if the use of ME is not an uninitialized use. 3638 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3639 bool CheckReferenceOnly) { 3640 llvm::SmallVector<FieldDecl*, 4> Fields; 3641 bool ReferenceField = false; 3642 while (ME) { 3643 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3644 if (!FD) 3645 return false; 3646 Fields.push_back(FD); 3647 if (FD->getType()->isReferenceType()) 3648 ReferenceField = true; 3649 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3650 } 3651 3652 // Binding a reference to an uninitialized field is not an 3653 // uninitialized use. 3654 if (CheckReferenceOnly && !ReferenceField) 3655 return true; 3656 3657 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3658 // Discard the first field since it is the field decl that is being 3659 // initialized. 3660 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields))) 3661 UsedFieldIndex.push_back(FD->getFieldIndex()); 3662 3663 for (auto UsedIter = UsedFieldIndex.begin(), 3664 UsedEnd = UsedFieldIndex.end(), 3665 OrigIter = InitFieldIndex.begin(), 3666 OrigEnd = InitFieldIndex.end(); 3667 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3668 if (*UsedIter < *OrigIter) 3669 return true; 3670 if (*UsedIter > *OrigIter) 3671 break; 3672 } 3673 3674 return false; 3675 } 3676 3677 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3678 bool AddressOf) { 3679 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3680 return; 3681 3682 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3683 // or union. 3684 MemberExpr *FieldME = ME; 3685 3686 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3687 3688 Expr *Base = ME; 3689 while (MemberExpr *SubME = 3690 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3691 3692 if (isa<VarDecl>(SubME->getMemberDecl())) 3693 return; 3694 3695 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3696 if (!FD->isAnonymousStructOrUnion()) 3697 FieldME = SubME; 3698 3699 if (!FieldME->getType().isPODType(S.Context)) 3700 AllPODFields = false; 3701 3702 Base = SubME->getBase(); 3703 } 3704 3705 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3706 Visit(Base); 3707 return; 3708 } 3709 3710 if (AddressOf && AllPODFields) 3711 return; 3712 3713 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3714 3715 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3716 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3717 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3718 } 3719 3720 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3721 QualType T = BaseCast->getType(); 3722 if (T->isPointerType() && 3723 BaseClasses.count(T->getPointeeType())) { 3724 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3725 << T->getPointeeType() << FoundVD; 3726 } 3727 } 3728 } 3729 3730 if (!Decls.count(FoundVD)) 3731 return; 3732 3733 const bool IsReference = FoundVD->getType()->isReferenceType(); 3734 3735 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3736 // Special checking for initializer lists. 3737 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3738 return; 3739 } 3740 } else { 3741 // Prevent double warnings on use of unbounded references. 3742 if (CheckReferenceOnly && !IsReference) 3743 return; 3744 } 3745 3746 unsigned diag = IsReference 3747 ? diag::warn_reference_field_is_uninit 3748 : diag::warn_field_is_uninit; 3749 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3750 if (Constructor) 3751 S.Diag(Constructor->getLocation(), 3752 diag::note_uninit_in_this_constructor) 3753 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3754 3755 } 3756 3757 void HandleValue(Expr *E, bool AddressOf) { 3758 E = E->IgnoreParens(); 3759 3760 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3761 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3762 AddressOf /*AddressOf*/); 3763 return; 3764 } 3765 3766 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3767 Visit(CO->getCond()); 3768 HandleValue(CO->getTrueExpr(), AddressOf); 3769 HandleValue(CO->getFalseExpr(), AddressOf); 3770 return; 3771 } 3772 3773 if (BinaryConditionalOperator *BCO = 3774 dyn_cast<BinaryConditionalOperator>(E)) { 3775 Visit(BCO->getCond()); 3776 HandleValue(BCO->getFalseExpr(), AddressOf); 3777 return; 3778 } 3779 3780 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3781 HandleValue(OVE->getSourceExpr(), AddressOf); 3782 return; 3783 } 3784 3785 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3786 switch (BO->getOpcode()) { 3787 default: 3788 break; 3789 case(BO_PtrMemD): 3790 case(BO_PtrMemI): 3791 HandleValue(BO->getLHS(), AddressOf); 3792 Visit(BO->getRHS()); 3793 return; 3794 case(BO_Comma): 3795 Visit(BO->getLHS()); 3796 HandleValue(BO->getRHS(), AddressOf); 3797 return; 3798 } 3799 } 3800 3801 Visit(E); 3802 } 3803 3804 void CheckInitListExpr(InitListExpr *ILE) { 3805 InitFieldIndex.push_back(0); 3806 for (auto *Child : ILE->children()) { 3807 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3808 CheckInitListExpr(SubList); 3809 } else { 3810 Visit(Child); 3811 } 3812 ++InitFieldIndex.back(); 3813 } 3814 InitFieldIndex.pop_back(); 3815 } 3816 3817 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3818 FieldDecl *Field, const Type *BaseClass) { 3819 // Remove Decls that may have been initialized in the previous 3820 // initializer. 3821 for (ValueDecl* VD : DeclsToRemove) 3822 Decls.erase(VD); 3823 DeclsToRemove.clear(); 3824 3825 Constructor = FieldConstructor; 3826 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3827 3828 if (ILE && Field) { 3829 InitList = true; 3830 InitListFieldDecl = Field; 3831 InitFieldIndex.clear(); 3832 CheckInitListExpr(ILE); 3833 } else { 3834 InitList = false; 3835 Visit(E); 3836 } 3837 3838 if (Field) 3839 Decls.erase(Field); 3840 if (BaseClass) 3841 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3842 } 3843 3844 void VisitMemberExpr(MemberExpr *ME) { 3845 // All uses of unbounded reference fields will warn. 3846 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3847 } 3848 3849 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3850 if (E->getCastKind() == CK_LValueToRValue) { 3851 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3852 return; 3853 } 3854 3855 Inherited::VisitImplicitCastExpr(E); 3856 } 3857 3858 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3859 if (E->getConstructor()->isCopyConstructor()) { 3860 Expr *ArgExpr = E->getArg(0); 3861 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3862 if (ILE->getNumInits() == 1) 3863 ArgExpr = ILE->getInit(0); 3864 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3865 if (ICE->getCastKind() == CK_NoOp) 3866 ArgExpr = ICE->getSubExpr(); 3867 HandleValue(ArgExpr, false /*AddressOf*/); 3868 return; 3869 } 3870 Inherited::VisitCXXConstructExpr(E); 3871 } 3872 3873 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3874 Expr *Callee = E->getCallee(); 3875 if (isa<MemberExpr>(Callee)) { 3876 HandleValue(Callee, false /*AddressOf*/); 3877 for (auto *Arg : E->arguments()) 3878 Visit(Arg); 3879 return; 3880 } 3881 3882 Inherited::VisitCXXMemberCallExpr(E); 3883 } 3884 3885 void VisitCallExpr(CallExpr *E) { 3886 // Treat std::move as a use. 3887 if (E->isCallToStdMove()) { 3888 HandleValue(E->getArg(0), /*AddressOf=*/false); 3889 return; 3890 } 3891 3892 Inherited::VisitCallExpr(E); 3893 } 3894 3895 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3896 Expr *Callee = E->getCallee(); 3897 3898 if (isa<UnresolvedLookupExpr>(Callee)) 3899 return Inherited::VisitCXXOperatorCallExpr(E); 3900 3901 Visit(Callee); 3902 for (auto *Arg : E->arguments()) 3903 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3904 } 3905 3906 void VisitBinaryOperator(BinaryOperator *E) { 3907 // If a field assignment is detected, remove the field from the 3908 // uninitiailized field set. 3909 if (E->getOpcode() == BO_Assign) 3910 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3911 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3912 if (!FD->getType()->isReferenceType()) 3913 DeclsToRemove.push_back(FD); 3914 3915 if (E->isCompoundAssignmentOp()) { 3916 HandleValue(E->getLHS(), false /*AddressOf*/); 3917 Visit(E->getRHS()); 3918 return; 3919 } 3920 3921 Inherited::VisitBinaryOperator(E); 3922 } 3923 3924 void VisitUnaryOperator(UnaryOperator *E) { 3925 if (E->isIncrementDecrementOp()) { 3926 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3927 return; 3928 } 3929 if (E->getOpcode() == UO_AddrOf) { 3930 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3931 HandleValue(ME->getBase(), true /*AddressOf*/); 3932 return; 3933 } 3934 } 3935 3936 Inherited::VisitUnaryOperator(E); 3937 } 3938 }; 3939 3940 // Diagnose value-uses of fields to initialize themselves, e.g. 3941 // foo(foo) 3942 // where foo is not also a parameter to the constructor. 3943 // Also diagnose across field uninitialized use such as 3944 // x(y), y(x) 3945 // TODO: implement -Wuninitialized and fold this into that framework. 3946 static void DiagnoseUninitializedFields( 3947 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3948 3949 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3950 Constructor->getLocation())) { 3951 return; 3952 } 3953 3954 if (Constructor->isInvalidDecl()) 3955 return; 3956 3957 const CXXRecordDecl *RD = Constructor->getParent(); 3958 3959 if (RD->isDependentContext()) 3960 return; 3961 3962 // Holds fields that are uninitialized. 3963 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3964 3965 // At the beginning, all fields are uninitialized. 3966 for (auto *I : RD->decls()) { 3967 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3968 UninitializedFields.insert(FD); 3969 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3970 UninitializedFields.insert(IFD->getAnonField()); 3971 } 3972 } 3973 3974 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3975 for (const auto &I : RD->bases()) 3976 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3977 3978 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3979 return; 3980 3981 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3982 UninitializedFields, 3983 UninitializedBaseClasses); 3984 3985 for (const auto *FieldInit : Constructor->inits()) { 3986 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3987 break; 3988 3989 Expr *InitExpr = FieldInit->getInit(); 3990 if (!InitExpr) 3991 continue; 3992 3993 if (CXXDefaultInitExpr *Default = 3994 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3995 InitExpr = Default->getExpr(); 3996 if (!InitExpr) 3997 continue; 3998 // In class initializers will point to the constructor. 3999 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 4000 FieldInit->getAnyMember(), 4001 FieldInit->getBaseClass()); 4002 } else { 4003 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 4004 FieldInit->getAnyMember(), 4005 FieldInit->getBaseClass()); 4006 } 4007 } 4008 } 4009} // namespace 4010 4011/// Enter a new C++ default initializer scope. After calling this, the 4012/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 4013/// parsing or instantiating the initializer failed. 4014void Sema::ActOnStartCXXInClassMemberInitializer() { 4015 // Create a synthetic function scope to represent the call to the constructor 4016 // that notionally surrounds a use of this initializer. 4017 PushFunctionScope(); 4018} 4019 4020void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 4021 if (!D.isFunctionDeclarator()) 4022 return; 4023 auto &FTI = D.getFunctionTypeInfo(); 4024 if (!FTI.Params) 4025 return; 4026 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 4027 FTI.NumParams)) { 4028 auto *ParamDecl = cast<NamedDecl>(Param.Param); 4029 if (ParamDecl->getDeclName()) 4030 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 4031 } 4032} 4033 4034ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 4035 return ActOnRequiresClause(ConstraintExpr); 4036} 4037 4038ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { 4039 if (ConstraintExpr.isInvalid()) 4040 return ExprError(); 4041 4042 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr); 4043 if (ConstraintExpr.isInvalid()) 4044 return ExprError(); 4045 4046 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(), 4047 UPPC_RequiresClause)) 4048 return ExprError(); 4049 4050 return ConstraintExpr; 4051} 4052 4053ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD, 4054 Expr *InitExpr, 4055 SourceLocation InitLoc) { 4056 InitializedEntity Entity = 4057 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 4058 InitializationKind Kind = 4059 FD->getInClassInitStyle() == ICIS_ListInit 4060 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 4061 InitExpr->getBeginLoc(), 4062 InitExpr->getEndLoc()) 4063 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 4064 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 4065 return Seq.Perform(*this, Entity, Kind, InitExpr); 4066} 4067 4068/// This is invoked after parsing an in-class initializer for a 4069/// non-static C++ class member, and after instantiating an in-class initializer 4070/// in a class template. Such actions are deferred until the class is complete. 4071void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 4072 SourceLocation InitLoc, 4073 Expr *InitExpr) { 4074 // Pop the notional constructor scope we created earlier. 4075 PopFunctionScopeInfo(nullptr, D); 4076 4077 FieldDecl *FD = dyn_cast<FieldDecl>(D); 4078 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", 4079, __extension__ __PRETTY_FUNCTION__
))
4079 "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", 4079, __extension__ __PRETTY_FUNCTION__
))
; 4080 4081 if (!InitExpr) { 4082 D->setInvalidDecl(); 4083 if (FD) 4084 FD->removeInClassInitializer(); 4085 return; 4086 } 4087 4088 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 4089 FD->setInvalidDecl(); 4090 FD->removeInClassInitializer(); 4091 return; 4092 } 4093 4094 ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr, 4095 /*RecoverUncorrectedTypos=*/true); 4096 assert(Init.isUsable() && "Init should at least have a RecoveryExpr")(static_cast <bool> (Init.isUsable() && "Init should at least have a RecoveryExpr"
) ? void (0) : __assert_fail ("Init.isUsable() && \"Init should at least have a RecoveryExpr\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 4096, __extension__ __PRETTY_FUNCTION__
))
; 4097 if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) { 4098 Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc); 4099 // C++11 [class.base.init]p7: 4100 // The initialization of each base and member constitutes a 4101 // full-expression. 4102 if (!Init.isInvalid()) 4103 Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false); 4104 if (Init.isInvalid()) { 4105 FD->setInvalidDecl(); 4106 return; 4107 } 4108 } 4109 4110 FD->setInClassInitializer(Init.get()); 4111} 4112 4113/// Find the direct and/or virtual base specifiers that 4114/// correspond to the given base type, for use in base initialization 4115/// within a constructor. 4116static bool FindBaseInitializer(Sema &SemaRef, 4117 CXXRecordDecl *ClassDecl, 4118 QualType BaseType, 4119 const CXXBaseSpecifier *&DirectBaseSpec, 4120 const CXXBaseSpecifier *&VirtualBaseSpec) { 4121 // First, check for a direct base class. 4122 DirectBaseSpec = nullptr; 4123 for (const auto &Base : ClassDecl->bases()) { 4124 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 4125 // We found a direct base of this type. That's what we're 4126 // initializing. 4127 DirectBaseSpec = &Base; 4128 break; 4129 } 4130 } 4131 4132 // Check for a virtual base class. 4133 // FIXME: We might be able to short-circuit this if we know in advance that 4134 // there are no virtual bases. 4135 VirtualBaseSpec = nullptr; 4136 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 4137 // We haven't found a base yet; search the class hierarchy for a 4138 // virtual base class. 4139 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4140 /*DetectVirtual=*/false); 4141 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4142 SemaRef.Context.getTypeDeclType(ClassDecl), 4143 BaseType, Paths)) { 4144 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4145 Path != Paths.end(); ++Path) { 4146 if (Path->back().Base->isVirtual()) { 4147 VirtualBaseSpec = Path->back().Base; 4148 break; 4149 } 4150 } 4151 } 4152 } 4153 4154 return DirectBaseSpec || VirtualBaseSpec; 4155} 4156 4157/// Handle a C++ member initializer using braced-init-list syntax. 4158MemInitResult 4159Sema::ActOnMemInitializer(Decl *ConstructorD, 4160 Scope *S, 4161 CXXScopeSpec &SS, 4162 IdentifierInfo *MemberOrBase, 4163 ParsedType TemplateTypeTy, 4164 const DeclSpec &DS, 4165 SourceLocation IdLoc, 4166 Expr *InitList, 4167 SourceLocation EllipsisLoc) { 4168 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4169 DS, IdLoc, InitList, 4170 EllipsisLoc); 4171} 4172 4173/// Handle a C++ member initializer using parentheses syntax. 4174MemInitResult 4175Sema::ActOnMemInitializer(Decl *ConstructorD, 4176 Scope *S, 4177 CXXScopeSpec &SS, 4178 IdentifierInfo *MemberOrBase, 4179 ParsedType TemplateTypeTy, 4180 const DeclSpec &DS, 4181 SourceLocation IdLoc, 4182 SourceLocation LParenLoc, 4183 ArrayRef<Expr *> Args, 4184 SourceLocation RParenLoc, 4185 SourceLocation EllipsisLoc) { 4186 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4187 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4188 DS, IdLoc, List, EllipsisLoc); 4189} 4190 4191namespace { 4192 4193// Callback to only accept typo corrections that can be a valid C++ member 4194// initializer: either a non-static field member or a base class. 4195class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4196public: 4197 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4198 : ClassDecl(ClassDecl) {} 4199 4200 bool ValidateCandidate(const TypoCorrection &candidate) override { 4201 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4202 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4203 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4204 return isa<TypeDecl>(ND); 4205 } 4206 return false; 4207 } 4208 4209 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4210 return std::make_unique<MemInitializerValidatorCCC>(*this); 4211 } 4212 4213private: 4214 CXXRecordDecl *ClassDecl; 4215}; 4216 4217} 4218 4219ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4220 CXXScopeSpec &SS, 4221 ParsedType TemplateTypeTy, 4222 IdentifierInfo *MemberOrBase) { 4223 if (SS.getScopeRep() || TemplateTypeTy) 4224 return nullptr; 4225 for (auto *D : ClassDecl->lookup(MemberOrBase)) 4226 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) 4227 return cast<ValueDecl>(D); 4228 return nullptr; 4229} 4230 4231/// Handle a C++ member initializer. 4232MemInitResult 4233Sema::BuildMemInitializer(Decl *ConstructorD, 4234 Scope *S, 4235 CXXScopeSpec &SS, 4236 IdentifierInfo *MemberOrBase, 4237 ParsedType TemplateTypeTy, 4238 const DeclSpec &DS, 4239 SourceLocation IdLoc, 4240 Expr *Init, 4241 SourceLocation EllipsisLoc) { 4242 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr, 4243 /*RecoverUncorrectedTypos=*/true); 4244 if (!Res.isUsable()) 4245 return true; 4246 Init = Res.get(); 4247 4248 if (!ConstructorD) 4249 return true; 4250 4251 AdjustDeclIfTemplate(ConstructorD); 4252 4253 CXXConstructorDecl *Constructor 4254 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4255 if (!Constructor) { 4256 // The user wrote a constructor initializer on a function that is 4257 // not a C++ constructor. Ignore the error for now, because we may 4258 // have more member initializers coming; we'll diagnose it just 4259 // once in ActOnMemInitializers. 4260 return true; 4261 } 4262 4263 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4264 4265 // C++ [class.base.init]p2: 4266 // Names in a mem-initializer-id are looked up in the scope of the 4267 // constructor's class and, if not found in that scope, are looked 4268 // up in the scope containing the constructor's definition. 4269 // [Note: if the constructor's class contains a member with the 4270 // same name as a direct or virtual base class of the class, a 4271 // mem-initializer-id naming the member or base class and composed 4272 // of a single identifier refers to the class member. A 4273 // mem-initializer-id for the hidden base class may be specified 4274 // using a qualified name. ] 4275 4276 // Look for a member, first. 4277 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4278 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4279 if (EllipsisLoc.isValid()) 4280 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4281 << MemberOrBase 4282 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4283 4284 return BuildMemberInitializer(Member, Init, IdLoc); 4285 } 4286 // It didn't name a member, so see if it names a class. 4287 QualType BaseType; 4288 TypeSourceInfo *TInfo = nullptr; 4289 4290 if (TemplateTypeTy) { 4291 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4292 if (BaseType.isNull()) 4293 return true; 4294 } else if (DS.getTypeSpecType() == TST_decltype) { 4295 BaseType = BuildDecltypeType(DS.getRepAsExpr()); 4296 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4297 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4298 return true; 4299 } else { 4300 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4301 LookupParsedName(R, S, &SS); 4302 4303 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4304 if (!TyD) { 4305 if (R.isAmbiguous()) return true; 4306 4307 // We don't want access-control diagnostics here. 4308 R.suppressDiagnostics(); 4309 4310 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4311 bool NotUnknownSpecialization = false; 4312 DeclContext *DC = computeDeclContext(SS, false); 4313 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4314 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4315 4316 if (!NotUnknownSpecialization) { 4317 // When the scope specifier can refer to a member of an unknown 4318 // specialization, we take it as a type name. 4319 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4320 SS.getWithLocInContext(Context), 4321 *MemberOrBase, IdLoc); 4322 if (BaseType.isNull()) 4323 return true; 4324 4325 TInfo = Context.CreateTypeSourceInfo(BaseType); 4326 DependentNameTypeLoc TL = 4327 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4328 if (!TL.isNull()) { 4329 TL.setNameLoc(IdLoc); 4330 TL.setElaboratedKeywordLoc(SourceLocation()); 4331 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4332 } 4333 4334 R.clear(); 4335 R.setLookupName(MemberOrBase); 4336 } 4337 } 4338 4339 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) { 4340 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) { 4341 auto *TempSpec = cast<TemplateSpecializationType>( 4342 UnqualifiedBase->getInjectedClassNameSpecialization()); 4343 TemplateName TN = TempSpec->getTemplateName(); 4344 for (auto const &Base : ClassDecl->bases()) { 4345 auto BaseTemplate = 4346 Base.getType()->getAs<TemplateSpecializationType>(); 4347 if (BaseTemplate && Context.hasSameTemplateName( 4348 BaseTemplate->getTemplateName(), TN)) { 4349 Diag(IdLoc, diag::ext_unqualified_base_class) 4350 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4351 BaseType = Base.getType(); 4352 break; 4353 } 4354 } 4355 } 4356 } 4357 4358 // If no results were found, try to correct typos. 4359 TypoCorrection Corr; 4360 MemInitializerValidatorCCC CCC(ClassDecl); 4361 if (R.empty() && BaseType.isNull() && 4362 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4363 CCC, CTK_ErrorRecovery, ClassDecl))) { 4364 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4365 // We have found a non-static data member with a similar 4366 // name to what was typed; complain and initialize that 4367 // member. 4368 diagnoseTypo(Corr, 4369 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4370 << MemberOrBase << true); 4371 return BuildMemberInitializer(Member, Init, IdLoc); 4372 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4373 const CXXBaseSpecifier *DirectBaseSpec; 4374 const CXXBaseSpecifier *VirtualBaseSpec; 4375 if (FindBaseInitializer(*this, ClassDecl, 4376 Context.getTypeDeclType(Type), 4377 DirectBaseSpec, VirtualBaseSpec)) { 4378 // We have found a direct or virtual base class with a 4379 // similar name to what was typed; complain and initialize 4380 // that base class. 4381 diagnoseTypo(Corr, 4382 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4383 << MemberOrBase << false, 4384 PDiag() /*Suppress note, we provide our own.*/); 4385 4386 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4387 : VirtualBaseSpec; 4388 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4389 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4390 4391 TyD = Type; 4392 } 4393 } 4394 } 4395 4396 if (!TyD && BaseType.isNull()) { 4397 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4398 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4399 return true; 4400 } 4401 } 4402 4403 if (BaseType.isNull()) { 4404 BaseType = getElaboratedType(ETK_None, SS, Context.getTypeDeclType(TyD)); 4405 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4406 TInfo = Context.CreateTypeSourceInfo(BaseType); 4407 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4408 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4409 TL.setElaboratedKeywordLoc(SourceLocation()); 4410 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4411 } 4412 } 4413 4414 if (!TInfo) 4415 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4416 4417 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4418} 4419 4420MemInitResult 4421Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4422 SourceLocation IdLoc) { 4423 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4424 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4425 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", 4426, __extension__ __PRETTY_FUNCTION__
))
4426 "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", 4426, __extension__ __PRETTY_FUNCTION__
))
; 4427 4428 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4429 return true; 4430 4431 if (Member->isInvalidDecl()) 4432 return true; 4433 4434 MultiExprArg Args; 4435 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4436 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4437 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4438 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4439 } else { 4440 // Template instantiation doesn't reconstruct ParenListExprs for us. 4441 Args = Init; 4442 } 4443 4444 SourceRange InitRange = Init->getSourceRange(); 4445 4446 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4447 // Can't check initialization for a member of dependent type or when 4448 // any of the arguments are type-dependent expressions. 4449 DiscardCleanupsInEvaluationContext(); 4450 } else { 4451 bool InitList = false; 4452 if (isa<InitListExpr>(Init)) { 4453 InitList = true; 4454 Args = Init; 4455 } 4456 4457 // Initialize the member. 4458 InitializedEntity MemberEntity = 4459 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4460 : InitializedEntity::InitializeMember(IndirectMember, 4461 nullptr); 4462 InitializationKind Kind = 4463 InitList ? InitializationKind::CreateDirectList( 4464 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4465 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4466 InitRange.getEnd()); 4467 4468 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4469 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4470 nullptr); 4471 if (!MemberInit.isInvalid()) { 4472 // C++11 [class.base.init]p7: 4473 // The initialization of each base and member constitutes a 4474 // full-expression. 4475 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4476 /*DiscardedValue*/ false); 4477 } 4478 4479 if (MemberInit.isInvalid()) { 4480 // Args were sensible expressions but we couldn't initialize the member 4481 // from them. Preserve them in a RecoveryExpr instead. 4482 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4483 Member->getType()) 4484 .get(); 4485 if (!Init) 4486 return true; 4487 } else { 4488 Init = MemberInit.get(); 4489 } 4490 } 4491 4492 if (DirectMember) { 4493 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4494 InitRange.getBegin(), Init, 4495 InitRange.getEnd()); 4496 } else { 4497 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4498 InitRange.getBegin(), Init, 4499 InitRange.getEnd()); 4500 } 4501} 4502 4503MemInitResult 4504Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4505 CXXRecordDecl *ClassDecl) { 4506 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin(); 4507 if (!LangOpts.CPlusPlus11) 4508 return Diag(NameLoc, diag::err_delegating_ctor) 4509 << TInfo->getTypeLoc().getSourceRange(); 4510 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4511 4512 bool InitList = true; 4513 MultiExprArg Args = Init; 4514 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4515 InitList = false; 4516 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4517 } 4518 4519 SourceRange InitRange = Init->getSourceRange(); 4520 // Initialize the object. 4521 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4522 QualType(ClassDecl->getTypeForDecl(), 0)); 4523 InitializationKind Kind = 4524 InitList ? InitializationKind::CreateDirectList( 4525 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4526 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4527 InitRange.getEnd()); 4528 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4529 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4530 Args, nullptr); 4531 if (!DelegationInit.isInvalid()) { 4532 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", 4534, __extension__ __PRETTY_FUNCTION__
))
4533 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", 4534, __extension__ __PRETTY_FUNCTION__
))
4534 "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", 4534, __extension__ __PRETTY_FUNCTION__
))
; 4535 4536 // C++11 [class.base.init]p7: 4537 // The initialization of each base and member constitutes a 4538 // full-expression. 4539 DelegationInit = ActOnFinishFullExpr( 4540 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4541 } 4542 4543 if (DelegationInit.isInvalid()) { 4544 DelegationInit = 4545 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4546 QualType(ClassDecl->getTypeForDecl(), 0)); 4547 if (DelegationInit.isInvalid()) 4548 return true; 4549 } else { 4550 // If we are in a dependent context, template instantiation will 4551 // perform this type-checking again. Just save the arguments that we 4552 // received in a ParenListExpr. 4553 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4554 // of the information that we have about the base 4555 // initializer. However, deconstructing the ASTs is a dicey process, 4556 // and this approach is far more likely to get the corner cases right. 4557 if (CurContext->isDependentContext()) 4558 DelegationInit = Init; 4559 } 4560 4561 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4562 DelegationInit.getAs<Expr>(), 4563 InitRange.getEnd()); 4564} 4565 4566MemInitResult 4567Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4568 Expr *Init, CXXRecordDecl *ClassDecl, 4569 SourceLocation EllipsisLoc) { 4570 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc(); 4571 4572 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4573 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4574 << BaseType << BaseTInfo->getTypeLoc().getSourceRange(); 4575 4576 // C++ [class.base.init]p2: 4577 // [...] Unless the mem-initializer-id names a nonstatic data 4578 // member of the constructor's class or a direct or virtual base 4579 // of that class, the mem-initializer is ill-formed. A 4580 // mem-initializer-list can initialize a base class using any 4581 // name that denotes that base class type. 4582 4583 // We can store the initializers in "as-written" form and delay analysis until 4584 // instantiation if the constructor is dependent. But not for dependent 4585 // (broken) code in a non-template! SetCtorInitializers does not expect this. 4586 bool Dependent = CurContext->isDependentContext() && 4587 (BaseType->isDependentType() || Init->isTypeDependent()); 4588 4589 SourceRange InitRange = Init->getSourceRange(); 4590 if (EllipsisLoc.isValid()) { 4591 // This is a pack expansion. 4592 if (!BaseType->containsUnexpandedParameterPack()) { 4593 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4594 << SourceRange(BaseLoc, InitRange.getEnd()); 4595 4596 EllipsisLoc = SourceLocation(); 4597 } 4598 } else { 4599 // Check for any unexpanded parameter packs. 4600 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4601 return true; 4602 4603 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4604 return true; 4605 } 4606 4607 // Check for direct and virtual base classes. 4608 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4609 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4610 if (!Dependent) { 4611 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4612 BaseType)) 4613 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4614 4615 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4616 VirtualBaseSpec); 4617 4618 // C++ [base.class.init]p2: 4619 // Unless the mem-initializer-id names a nonstatic data member of the 4620 // constructor's class or a direct or virtual base of that class, the 4621 // mem-initializer is ill-formed. 4622 if (!DirectBaseSpec && !VirtualBaseSpec) { 4623 // If the class has any dependent bases, then it's possible that 4624 // one of those types will resolve to the same type as 4625 // BaseType. Therefore, just treat this as a dependent base 4626 // class initialization. FIXME: Should we try to check the 4627 // initialization anyway? It seems odd. 4628 if (ClassDecl->hasAnyDependentBases()) 4629 Dependent = true; 4630 else 4631 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4632 << BaseType << Context.getTypeDeclType(ClassDecl) 4633 << BaseTInfo->getTypeLoc().getSourceRange(); 4634 } 4635 } 4636 4637 if (Dependent) { 4638 DiscardCleanupsInEvaluationContext(); 4639 4640 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4641 /*IsVirtual=*/false, 4642 InitRange.getBegin(), Init, 4643 InitRange.getEnd(), EllipsisLoc); 4644 } 4645 4646 // C++ [base.class.init]p2: 4647 // If a mem-initializer-id is ambiguous because it designates both 4648 // a direct non-virtual base class and an inherited virtual base 4649 // class, the mem-initializer is ill-formed. 4650 if (DirectBaseSpec && VirtualBaseSpec) 4651 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4652 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4653 4654 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4655 if (!BaseSpec) 4656 BaseSpec = VirtualBaseSpec; 4657 4658 // Initialize the base. 4659 bool InitList = true; 4660 MultiExprArg Args = Init; 4661 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4662 InitList = false; 4663 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4664 } 4665 4666 InitializedEntity BaseEntity = 4667 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4668 InitializationKind Kind = 4669 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4670 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4671 InitRange.getEnd()); 4672 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4673 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4674 if (!BaseInit.isInvalid()) { 4675 // C++11 [class.base.init]p7: 4676 // The initialization of each base and member constitutes a 4677 // full-expression. 4678 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4679 /*DiscardedValue*/ false); 4680 } 4681 4682 if (BaseInit.isInvalid()) { 4683 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), 4684 Args, BaseType); 4685 if (BaseInit.isInvalid()) 4686 return true; 4687 } else { 4688 // If we are in a dependent context, template instantiation will 4689 // perform this type-checking again. Just save the arguments that we 4690 // received in a ParenListExpr. 4691 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4692 // of the information that we have about the base 4693 // initializer. However, deconstructing the ASTs is a dicey process, 4694 // and this approach is far more likely to get the corner cases right. 4695 if (CurContext->isDependentContext()) 4696 BaseInit = Init; 4697 } 4698 4699 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4700 BaseSpec->isVirtual(), 4701 InitRange.getBegin(), 4702 BaseInit.getAs<Expr>(), 4703 InitRange.getEnd(), EllipsisLoc); 4704} 4705 4706// Create a static_cast\<T&&>(expr). 4707static Expr *CastForMoving(Sema &SemaRef, Expr *E) { 4708 QualType TargetType = 4709 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false, 4710 SourceLocation(), DeclarationName()); 4711 SourceLocation ExprLoc = E->getBeginLoc(); 4712 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4713 TargetType, ExprLoc); 4714 4715 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4716 SourceRange(ExprLoc, ExprLoc), 4717 E->getSourceRange()).get(); 4718} 4719 4720/// ImplicitInitializerKind - How an implicit base or member initializer should 4721/// initialize its base or member. 4722enum ImplicitInitializerKind { 4723 IIK_Default, 4724 IIK_Copy, 4725 IIK_Move, 4726 IIK_Inherit 4727}; 4728 4729static bool 4730BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4731 ImplicitInitializerKind ImplicitInitKind, 4732 CXXBaseSpecifier *BaseSpec, 4733 bool IsInheritedVirtualBase, 4734 CXXCtorInitializer *&CXXBaseInit) { 4735 InitializedEntity InitEntity 4736 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4737 IsInheritedVirtualBase); 4738 4739 ExprResult BaseInit; 4740 4741 switch (ImplicitInitKind) { 4742 case IIK_Inherit: 4743 case IIK_Default: { 4744 InitializationKind InitKind 4745 = InitializationKind::CreateDefault(Constructor->getLocation()); 4746 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt); 4747 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt); 4748 break; 4749 } 4750 4751 case IIK_Move: 4752 case IIK_Copy: { 4753 bool Moving = ImplicitInitKind == IIK_Move; 4754 ParmVarDecl *Param = Constructor->getParamDecl(0); 4755 QualType ParamType = Param->getType().getNonReferenceType(); 4756 4757 Expr *CopyCtorArg = 4758 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4759 SourceLocation(), Param, false, 4760 Constructor->getLocation(), ParamType, 4761 VK_LValue, nullptr); 4762 4763 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4764 4765 // Cast to the base class to avoid ambiguities. 4766 QualType ArgTy = 4767 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4768 ParamType.getQualifiers()); 4769 4770 if (Moving) { 4771 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4772 } 4773 4774 CXXCastPath BasePath; 4775 BasePath.push_back(BaseSpec); 4776 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4777 CK_UncheckedDerivedToBase, 4778 Moving ? VK_XValue : VK_LValue, 4779 &BasePath).get(); 4780 4781 InitializationKind InitKind 4782 = InitializationKind::CreateDirect(Constructor->getLocation(), 4783 SourceLocation(), SourceLocation()); 4784 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4785 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4786 break; 4787 } 4788 } 4789 4790 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4791 if (BaseInit.isInvalid()) 4792 return true; 4793 4794 CXXBaseInit = 4795 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4796 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4797 SourceLocation()), 4798 BaseSpec->isVirtual(), 4799 SourceLocation(), 4800 BaseInit.getAs<Expr>(), 4801 SourceLocation(), 4802 SourceLocation()); 4803 4804 return false; 4805} 4806 4807static bool RefersToRValueRef(Expr *MemRef) { 4808 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4809 return Referenced->getType()->isRValueReferenceType(); 4810} 4811 4812static bool 4813BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4814 ImplicitInitializerKind ImplicitInitKind, 4815 FieldDecl *Field, IndirectFieldDecl *Indirect, 4816 CXXCtorInitializer *&CXXMemberInit) { 4817 if (Field->isInvalidDecl()) 4818 return true; 4819 4820 SourceLocation Loc = Constructor->getLocation(); 4821 4822 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4823 bool Moving = ImplicitInitKind == IIK_Move; 4824 ParmVarDecl *Param = Constructor->getParamDecl(0); 4825 QualType ParamType = Param->getType().getNonReferenceType(); 4826 4827 // Suppress copying zero-width bitfields. 4828 if (Field->isZeroLengthBitField(SemaRef.Context)) 4829 return false; 4830 4831 Expr *MemberExprBase = 4832 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4833 SourceLocation(), Param, false, 4834 Loc, ParamType, VK_LValue, nullptr); 4835 4836 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4837 4838 if (Moving) { 4839 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4840 } 4841 4842 // Build a reference to this field within the parameter. 4843 CXXScopeSpec SS; 4844 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4845 Sema::LookupMemberName); 4846 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4847 : cast<ValueDecl>(Field), AS_public); 4848 MemberLookup.resolveKind(); 4849 ExprResult CtorArg 4850 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4851 ParamType, Loc, 4852 /*IsArrow=*/false, 4853 SS, 4854 /*TemplateKWLoc=*/SourceLocation(), 4855 /*FirstQualifierInScope=*/nullptr, 4856 MemberLookup, 4857 /*TemplateArgs=*/nullptr, 4858 /*S*/nullptr); 4859 if (CtorArg.isInvalid()) 4860 return true; 4861 4862 // C++11 [class.copy]p15: 4863 // - if a member m has rvalue reference type T&&, it is direct-initialized 4864 // with static_cast<T&&>(x.m); 4865 if (RefersToRValueRef(CtorArg.get())) { 4866 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4867 } 4868 4869 InitializedEntity Entity = 4870 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4871 /*Implicit*/ true) 4872 : InitializedEntity::InitializeMember(Field, nullptr, 4873 /*Implicit*/ true); 4874 4875 // Direct-initialize to use the copy constructor. 4876 InitializationKind InitKind = 4877 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4878 4879 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4880 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4881 ExprResult MemberInit = 4882 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4883 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4884 if (MemberInit.isInvalid()) 4885 return true; 4886 4887 if (Indirect) 4888 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4889 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4890 else 4891 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4892 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4893 return false; 4894 } 4895 4896 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", 4897, __extension__ __PRETTY_FUNCTION__
))
4897 "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", 4897, __extension__ __PRETTY_FUNCTION__
))
; 4898 4899 QualType FieldBaseElementType = 4900 SemaRef.Context.getBaseElementType(Field->getType()); 4901 4902 if (FieldBaseElementType->isRecordType()) { 4903 InitializedEntity InitEntity = 4904 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4905 /*Implicit*/ true) 4906 : InitializedEntity::InitializeMember(Field, nullptr, 4907 /*Implicit*/ true); 4908 InitializationKind InitKind = 4909 InitializationKind::CreateDefault(Loc); 4910 4911 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt); 4912 ExprResult MemberInit = 4913 InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt); 4914 4915 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4916 if (MemberInit.isInvalid()) 4917 return true; 4918 4919 if (Indirect) 4920 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4921 Indirect, Loc, 4922 Loc, 4923 MemberInit.get(), 4924 Loc); 4925 else 4926 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4927 Field, Loc, Loc, 4928 MemberInit.get(), 4929 Loc); 4930 return false; 4931 } 4932 4933 if (!Field->getParent()->isUnion()) { 4934 if (FieldBaseElementType->isReferenceType()) { 4935 SemaRef.Diag(Constructor->getLocation(), 4936 diag::err_uninitialized_member_in_ctor) 4937 << (int)Constructor->isImplicit() 4938 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4939 << 0 << Field->getDeclName(); 4940 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4941 return true; 4942 } 4943 4944 if (FieldBaseElementType.isConstQualified()) { 4945 SemaRef.Diag(Constructor->getLocation(), 4946 diag::err_uninitialized_member_in_ctor) 4947 << (int)Constructor->isImplicit() 4948 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4949 << 1 << Field->getDeclName(); 4950 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4951 return true; 4952 } 4953 } 4954 4955 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4956 // ARC and Weak: 4957 // Default-initialize Objective-C pointers to NULL. 4958 CXXMemberInit 4959 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4960 Loc, Loc, 4961 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4962 Loc); 4963 return false; 4964 } 4965 4966 // Nothing to initialize. 4967 CXXMemberInit = nullptr; 4968 return false; 4969} 4970 4971namespace { 4972struct BaseAndFieldInfo { 4973 Sema &S; 4974 CXXConstructorDecl *Ctor; 4975 bool AnyErrorsInInits; 4976 ImplicitInitializerKind IIK; 4977 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4978 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4979 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4980 4981 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4982 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4983 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4984 if (Ctor->getInheritedConstructor()) 4985 IIK = IIK_Inherit; 4986 else if (Generated && Ctor->isCopyConstructor()) 4987 IIK = IIK_Copy; 4988 else if (Generated && Ctor->isMoveConstructor()) 4989 IIK = IIK_Move; 4990 else 4991 IIK = IIK_Default; 4992 } 4993 4994 bool isImplicitCopyOrMove() const { 4995 switch (IIK) { 4996 case IIK_Copy: 4997 case IIK_Move: 4998 return true; 4999 5000 case IIK_Default: 5001 case IIK_Inherit: 5002 return false; 5003 } 5004 5005 llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!"
, "clang/lib/Sema/SemaDeclCXX.cpp", 5005)
; 5006 } 5007 5008 bool addFieldInitializer(CXXCtorInitializer *Init) { 5009 AllToInit.push_back(Init); 5010 5011 // Check whether this initializer makes the field "used". 5012 if (Init->getInit()->HasSideEffects(S.Context)) 5013 S.UnusedPrivateFields.remove(Init->getAnyMember()); 5014 5015 return false; 5016 } 5017 5018 bool isInactiveUnionMember(FieldDecl *Field) { 5019 RecordDecl *Record = Field->getParent(); 5020 if (!Record->isUnion()) 5021 return false; 5022 5023 if (FieldDecl *Active = 5024 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 5025 return Active != Field->getCanonicalDecl(); 5026 5027 // In an implicit copy or move constructor, ignore any in-class initializer. 5028 if (isImplicitCopyOrMove()) 5029 return true; 5030 5031 // If there's no explicit initialization, the field is active only if it 5032 // has an in-class initializer... 5033 if (Field->hasInClassInitializer()) 5034 return false; 5035 // ... or it's an anonymous struct or union whose class has an in-class 5036 // initializer. 5037 if (!Field->isAnonymousStructOrUnion()) 5038 return true; 5039 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 5040 return !FieldRD->hasInClassInitializer(); 5041 } 5042 5043 /// Determine whether the given field is, or is within, a union member 5044 /// that is inactive (because there was an initializer given for a different 5045 /// member of the union, or because the union was not initialized at all). 5046 bool isWithinInactiveUnionMember(FieldDecl *Field, 5047 IndirectFieldDecl *Indirect) { 5048 if (!Indirect) 5049 return isInactiveUnionMember(Field); 5050 5051 for (auto *C : Indirect->chain()) { 5052 FieldDecl *Field = dyn_cast<FieldDecl>(C); 5053 if (Field && isInactiveUnionMember(Field)) 5054 return true; 5055 } 5056 return false; 5057 } 5058}; 5059} 5060 5061/// Determine whether the given type is an incomplete or zero-lenfgth 5062/// array type. 5063static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 5064 if (T->isIncompleteArrayType()) 5065 return true; 5066 5067 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 5068 if (!ArrayT->getSize()) 5069 return true; 5070 5071 T = ArrayT->getElementType(); 5072 } 5073 5074 return false; 5075} 5076 5077static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 5078 FieldDecl *Field, 5079 IndirectFieldDecl *Indirect = nullptr) { 5080 if (Field->isInvalidDecl()) 5081 return false; 5082 5083 // Overwhelmingly common case: we have a direct initializer for this field. 5084 if (CXXCtorInitializer *Init = 5085 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 5086 return Info.addFieldInitializer(Init); 5087 5088 // C++11 [class.base.init]p8: 5089 // if the entity is a non-static data member that has a 5090 // brace-or-equal-initializer and either 5091 // -- the constructor's class is a union and no other variant member of that 5092 // union is designated by a mem-initializer-id or 5093 // -- the constructor's class is not a union, and, if the entity is a member 5094 // of an anonymous union, no other member of that union is designated by 5095 // a mem-initializer-id, 5096 // the entity is initialized as specified in [dcl.init]. 5097 // 5098 // We also apply the same rules to handle anonymous structs within anonymous 5099 // unions. 5100 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 5101 return false; 5102 5103 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 5104 ExprResult DIE = 5105 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 5106 if (DIE.isInvalid()) 5107 return true; 5108 5109 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 5110 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 5111 5112 CXXCtorInitializer *Init; 5113 if (Indirect) 5114 Init = new (SemaRef.Context) 5115 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 5116 SourceLocation(), DIE.get(), SourceLocation()); 5117 else 5118 Init = new (SemaRef.Context) 5119 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 5120 SourceLocation(), DIE.get(), SourceLocation()); 5121 return Info.addFieldInitializer(Init); 5122 } 5123 5124 // Don't initialize incomplete or zero-length arrays. 5125 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 5126 return false; 5127 5128 // Don't try to build an implicit initializer if there were semantic 5129 // errors in any of the initializers (and therefore we might be 5130 // missing some that the user actually wrote). 5131 if (Info.AnyErrorsInInits) 5132 return false; 5133 5134 CXXCtorInitializer *Init = nullptr; 5135 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 5136 Indirect, Init)) 5137 return true; 5138 5139 if (!Init) 5140 return false; 5141 5142 return Info.addFieldInitializer(Init); 5143} 5144 5145bool 5146Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5147 CXXCtorInitializer *Initializer) { 5148 assert(Initializer->isDelegatingInitializer())(static_cast <bool> (Initializer->isDelegatingInitializer
()) ? void (0) : __assert_fail ("Initializer->isDelegatingInitializer()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 5148, __extension__ __PRETTY_FUNCTION__
))
; 5149 Constructor->setNumCtorInitializers(1); 5150 CXXCtorInitializer **initializer = 5151 new (Context) CXXCtorInitializer*[1]; 5152 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 5153 Constructor->setCtorInitializers(initializer); 5154 5155 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 5156 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 5157 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 5158 } 5159 5160 DelegatingCtorDecls.push_back(Constructor); 5161 5162 DiagnoseUninitializedFields(*this, Constructor); 5163 5164 return false; 5165} 5166 5167bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5168 ArrayRef<CXXCtorInitializer *> Initializers) { 5169 if (Constructor->isDependentContext()) { 5170 // Just store the initializers as written, they will be checked during 5171 // instantiation. 5172 if (!Initializers.empty()) { 5173 Constructor->setNumCtorInitializers(Initializers.size()); 5174 CXXCtorInitializer **baseOrMemberInitializers = 5175 new (Context) CXXCtorInitializer*[Initializers.size()]; 5176 memcpy(baseOrMemberInitializers, Initializers.data(), 5177 Initializers.size() * sizeof(CXXCtorInitializer*)); 5178 Constructor->setCtorInitializers(baseOrMemberInitializers); 5179 } 5180 5181 // Let template instantiation know whether we had errors. 5182 if (AnyErrors) 5183 Constructor->setInvalidDecl(); 5184 5185 return false; 5186 } 5187 5188 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5189 5190 // We need to build the initializer AST according to order of construction 5191 // and not what user specified in the Initializers list. 5192 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5193 if (!ClassDecl) 5194 return true; 5195 5196 bool HadError = false; 5197 5198 for (unsigned i = 0; i < Initializers.size(); i++) { 5199 CXXCtorInitializer *Member = Initializers[i]; 5200 5201 if (Member->isBaseInitializer()) 5202 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5203 else { 5204 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5205 5206 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5207 for (auto *C : F->chain()) { 5208 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5209 if (FD && FD->getParent()->isUnion()) 5210 Info.ActiveUnionMember.insert(std::make_pair( 5211 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5212 } 5213 } else if (FieldDecl *FD = Member->getMember()) { 5214 if (FD->getParent()->isUnion()) 5215 Info.ActiveUnionMember.insert(std::make_pair( 5216 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5217 } 5218 } 5219 } 5220 5221 // Keep track of the direct virtual bases. 5222 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5223 for (auto &I : ClassDecl->bases()) { 5224 if (I.isVirtual()) 5225 DirectVBases.insert(&I); 5226 } 5227 5228 // Push virtual bases before others. 5229 for (auto &VBase : ClassDecl->vbases()) { 5230 if (CXXCtorInitializer *Value 5231 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5232 // [class.base.init]p7, per DR257: 5233 // A mem-initializer where the mem-initializer-id names a virtual base 5234 // class is ignored during execution of a constructor of any class that 5235 // is not the most derived class. 5236 if (ClassDecl->isAbstract()) { 5237 // FIXME: Provide a fixit to remove the base specifier. This requires 5238 // tracking the location of the associated comma for a base specifier. 5239 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5240 << VBase.getType() << ClassDecl; 5241 DiagnoseAbstractType(ClassDecl); 5242 } 5243 5244 Info.AllToInit.push_back(Value); 5245 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5246 // [class.base.init]p8, per DR257: 5247 // If a given [...] base class is not named by a mem-initializer-id 5248 // [...] and the entity is not a virtual base class of an abstract 5249 // class, then [...] the entity is default-initialized. 5250 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5251 CXXCtorInitializer *CXXBaseInit; 5252 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5253 &VBase, IsInheritedVirtualBase, 5254 CXXBaseInit)) { 5255 HadError = true; 5256 continue; 5257 } 5258 5259 Info.AllToInit.push_back(CXXBaseInit); 5260 } 5261 } 5262 5263 // Non-virtual bases. 5264 for (auto &Base : ClassDecl->bases()) { 5265 // Virtuals are in the virtual base list and already constructed. 5266 if (Base.isVirtual()) 5267 continue; 5268 5269 if (CXXCtorInitializer *Value 5270 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5271 Info.AllToInit.push_back(Value); 5272 } else if (!AnyErrors) { 5273 CXXCtorInitializer *CXXBaseInit; 5274 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5275 &Base, /*IsInheritedVirtualBase=*/false, 5276 CXXBaseInit)) { 5277 HadError = true; 5278 continue; 5279 } 5280 5281 Info.AllToInit.push_back(CXXBaseInit); 5282 } 5283 } 5284 5285 // Fields. 5286 for (auto *Mem : ClassDecl->decls()) { 5287 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5288 // C++ [class.bit]p2: 5289 // A declaration for a bit-field that omits the identifier declares an 5290 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5291 // initialized. 5292 if (F->isUnnamedBitfield()) 5293 continue; 5294 5295 // If we're not generating the implicit copy/move constructor, then we'll 5296 // handle anonymous struct/union fields based on their individual 5297 // indirect fields. 5298 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5299 continue; 5300 5301 if (CollectFieldInitializer(*this, Info, F)) 5302 HadError = true; 5303 continue; 5304 } 5305 5306 // Beyond this point, we only consider default initialization. 5307 if (Info.isImplicitCopyOrMove()) 5308 continue; 5309 5310 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5311 if (F->getType()->isIncompleteArrayType()) { 5312 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", 5313, __extension__ __PRETTY_FUNCTION__
))
5313 "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", 5313, __extension__ __PRETTY_FUNCTION__
))
; 5314 continue; 5315 } 5316 5317 // Initialize each field of an anonymous struct individually. 5318 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5319 HadError = true; 5320 5321 continue; 5322 } 5323 } 5324 5325 unsigned NumInitializers = Info.AllToInit.size(); 5326 if (NumInitializers > 0) { 5327 Constructor->setNumCtorInitializers(NumInitializers); 5328 CXXCtorInitializer **baseOrMemberInitializers = 5329 new (Context) CXXCtorInitializer*[NumInitializers]; 5330 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5331 NumInitializers * sizeof(CXXCtorInitializer*)); 5332 Constructor->setCtorInitializers(baseOrMemberInitializers); 5333 5334 // Constructors implicitly reference the base and member 5335 // destructors. 5336 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5337 Constructor->getParent()); 5338 } 5339 5340 return HadError; 5341} 5342 5343static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5344 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5345 const RecordDecl *RD = RT->getDecl(); 5346 if (RD->isAnonymousStructOrUnion()) { 5347 for (auto *Field : RD->fields()) 5348 PopulateKeysForFields(Field, IdealInits); 5349 return; 5350 } 5351 } 5352 IdealInits.push_back(Field->getCanonicalDecl()); 5353} 5354 5355static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5356 return Context.getCanonicalType(BaseType).getTypePtr(); 5357} 5358 5359static const void *GetKeyForMember(ASTContext &Context, 5360 CXXCtorInitializer *Member) { 5361 if (!Member->isAnyMemberInitializer()) 5362 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5363 5364 return Member->getAnyMember()->getCanonicalDecl(); 5365} 5366 5367static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, 5368 const CXXCtorInitializer *Previous, 5369 const CXXCtorInitializer *Current) { 5370 if (Previous->isAnyMemberInitializer()) 5371 Diag << 0 << Previous->getAnyMember(); 5372 else 5373 Diag << 1 << Previous->getTypeSourceInfo()->getType(); 5374 5375 if (Current->isAnyMemberInitializer()) 5376 Diag << 0 << Current->getAnyMember(); 5377 else 5378 Diag << 1 << Current->getTypeSourceInfo()->getType(); 5379} 5380 5381static void DiagnoseBaseOrMemInitializerOrder( 5382 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5383 ArrayRef<CXXCtorInitializer *> Inits) { 5384 if (Constructor->getDeclContext()->isDependentContext()) 5385 return; 5386 5387 // Don't check initializers order unless the warning is enabled at the 5388 // location of at least one initializer. 5389 bool ShouldCheckOrder = false; 5390 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5391 CXXCtorInitializer *Init = Inits[InitIndex]; 5392 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5393 Init->getSourceLocation())) { 5394 ShouldCheckOrder = true; 5395 break; 5396 } 5397 } 5398 if (!ShouldCheckOrder) 5399 return; 5400 5401 // Build the list of bases and members in the order that they'll 5402 // actually be initialized. The explicit initializers should be in 5403 // this same order but may be missing things. 5404 SmallVector<const void*, 32> IdealInitKeys; 5405 5406 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5407 5408 // 1. Virtual bases. 5409 for (const auto &VBase : ClassDecl->vbases()) 5410 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5411 5412 // 2. Non-virtual bases. 5413 for (const auto &Base : ClassDecl->bases()) { 5414 if (Base.isVirtual()) 5415 continue; 5416 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5417 } 5418 5419 // 3. Direct fields. 5420 for (auto *Field : ClassDecl->fields()) { 5421 if (Field->isUnnamedBitfield()) 5422 continue; 5423 5424 PopulateKeysForFields(Field, IdealInitKeys); 5425 } 5426 5427 unsigned NumIdealInits = IdealInitKeys.size(); 5428 unsigned IdealIndex = 0; 5429 5430 // Track initializers that are in an incorrect order for either a warning or 5431 // note if multiple ones occur. 5432 SmallVector<unsigned> WarnIndexes; 5433 // Correlates the index of an initializer in the init-list to the index of 5434 // the field/base in the class. 5435 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder; 5436 5437 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5438 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]); 5439 5440 // Scan forward to try to find this initializer in the idealized 5441 // initializers list. 5442 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5443 if (InitKey == IdealInitKeys[IdealIndex]) 5444 break; 5445 5446 // If we didn't find this initializer, it must be because we 5447 // scanned past it on a previous iteration. That can only 5448 // happen if we're out of order; emit a warning. 5449 if (IdealIndex == NumIdealInits && InitIndex) { 5450 WarnIndexes.push_back(InitIndex); 5451 5452 // Move back to the initializer's location in the ideal list. 5453 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5454 if (InitKey == IdealInitKeys[IdealIndex]) 5455 break; 5456 5457 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", 5458, __extension__ __PRETTY_FUNCTION__
))
5458 "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", 5458, __extension__ __PRETTY_FUNCTION__
))
; 5459 } 5460 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex); 5461 } 5462 5463 if (WarnIndexes.empty()) 5464 return; 5465 5466 // Sort based on the ideal order, first in the pair. 5467 llvm::sort(CorrelatedInitOrder, llvm::less_first()); 5468 5469 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to 5470 // emit the diagnostic before we can try adding notes. 5471 { 5472 Sema::SemaDiagnosticBuilder D = SemaRef.Diag( 5473 Inits[WarnIndexes.front() - 1]->getSourceLocation(), 5474 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order 5475 : diag::warn_some_initializers_out_of_order); 5476 5477 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) { 5478 if (CorrelatedInitOrder[I].second == I) 5479 continue; 5480 // Ideally we would be using InsertFromRange here, but clang doesn't 5481 // appear to handle InsertFromRange correctly when the source range is 5482 // modified by another fix-it. 5483 D << FixItHint::CreateReplacement( 5484 Inits[I]->getSourceRange(), 5485 Lexer::getSourceText( 5486 CharSourceRange::getTokenRange( 5487 Inits[CorrelatedInitOrder[I].second]->getSourceRange()), 5488 SemaRef.getSourceManager(), SemaRef.getLangOpts())); 5489 } 5490 5491 // If there is only 1 item out of order, the warning expects the name and 5492 // type of each being added to it. 5493 if (WarnIndexes.size() == 1) { 5494 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1], 5495 Inits[WarnIndexes.front()]); 5496 return; 5497 } 5498 } 5499 // More than 1 item to warn, create notes letting the user know which ones 5500 // are bad. 5501 for (unsigned WarnIndex : WarnIndexes) { 5502 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1]; 5503 auto D = SemaRef.Diag(PrevInit->getSourceLocation(), 5504 diag::note_initializer_out_of_order); 5505 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]); 5506 D << PrevInit->getSourceRange(); 5507 } 5508} 5509 5510namespace { 5511bool CheckRedundantInit(Sema &S, 5512 CXXCtorInitializer *Init, 5513 CXXCtorInitializer *&PrevInit) { 5514 if (!PrevInit) { 5515 PrevInit = Init; 5516 return false; 5517 } 5518 5519 if (FieldDecl *Field = Init->getAnyMember()) 5520 S.Diag(Init->getSourceLocation(), 5521 diag::err_multiple_mem_initialization) 5522 << Field->getDeclName() 5523 << Init->getSourceRange(); 5524 else { 5525 const Type *BaseClass = Init->getBaseClass(); 5526 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", 5526, __extension__ __PRETTY_FUNCTION__
))
; 5527 S.Diag(Init->getSourceLocation(), 5528 diag::err_multiple_base_initialization) 5529 << QualType(BaseClass, 0) 5530 << Init->getSourceRange(); 5531 } 5532 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5533 << 0 << PrevInit->getSourceRange(); 5534 5535 return true; 5536} 5537 5538typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5539typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5540 5541bool CheckRedundantUnionInit(Sema &S, 5542 CXXCtorInitializer *Init, 5543 RedundantUnionMap &Unions) { 5544 FieldDecl *Field = Init->getAnyMember(); 5545 RecordDecl *Parent = Field->getParent(); 5546 NamedDecl *Child = Field; 5547 5548 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5549 if (Parent->isUnion()) { 5550 UnionEntry &En = Unions[Parent]; 5551 if (En.first && En.first != Child) { 5552 S.Diag(Init->getSourceLocation(), 5553 diag::err_multiple_mem_union_initialization) 5554 << Field->getDeclName() 5555 << Init->getSourceRange(); 5556 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5557 << 0 << En.second->getSourceRange(); 5558 return true; 5559 } 5560 if (!En.first) { 5561 En.first = Child; 5562 En.second = Init; 5563 } 5564 if (!Parent->isAnonymousStructOrUnion()) 5565 return false; 5566 } 5567 5568 Child = Parent; 5569 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5570 } 5571 5572 return false; 5573} 5574} // namespace 5575 5576/// ActOnMemInitializers - Handle the member initializers for a constructor. 5577void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5578 SourceLocation ColonLoc, 5579 ArrayRef<CXXCtorInitializer*> MemInits, 5580 bool AnyErrors) { 5581 if (!ConstructorDecl) 5582 return; 5583 5584 AdjustDeclIfTemplate(ConstructorDecl); 5585 5586 CXXConstructorDecl *Constructor 5587 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5588 5589 if (!Constructor) { 5590 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5591 return; 5592 } 5593 5594 // Mapping for the duplicate initializers check. 5595 // For member initializers, this is keyed with a FieldDecl*. 5596 // For base initializers, this is keyed with a Type*. 5597 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5598 5599 // Mapping for the inconsistent anonymous-union initializers check. 5600 RedundantUnionMap MemberUnions; 5601 5602 bool HadError = false; 5603 for (unsigned i = 0; i < MemInits.size(); i++) { 5604 CXXCtorInitializer *Init = MemInits[i]; 5605 5606 // Set the source order index. 5607 Init->setSourceOrder(i); 5608 5609 if (Init->isAnyMemberInitializer()) { 5610 const void *Key = GetKeyForMember(Context, Init); 5611 if (CheckRedundantInit(*this, Init, Members[Key]) || 5612 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5613 HadError = true; 5614 } else if (Init->isBaseInitializer()) { 5615 const void *Key = GetKeyForMember(Context, Init); 5616 if (CheckRedundantInit(*this, Init, Members[Key])) 5617 HadError = true; 5618 } else { 5619 assert(Init->isDelegatingInitializer())(static_cast <bool> (Init->isDelegatingInitializer()
) ? void (0) : __assert_fail ("Init->isDelegatingInitializer()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 5619, __extension__ __PRETTY_FUNCTION__
))
; 5620 // This must be the only initializer 5621 if (MemInits.size() != 1) { 5622 Diag(Init->getSourceLocation(), 5623 diag::err_delegating_initializer_alone) 5624 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5625 // We will treat this as being the only initializer. 5626 } 5627 SetDelegatingInitializer(Constructor, MemInits[i]); 5628 // Return immediately as the initializer is set. 5629 return; 5630 } 5631 } 5632 5633 if (HadError) 5634 return; 5635 5636 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5637 5638 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5639 5640 DiagnoseUninitializedFields(*this, Constructor); 5641} 5642 5643void 5644Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5645 CXXRecordDecl *ClassDecl) { 5646 // Ignore dependent contexts. Also ignore unions, since their members never 5647 // have destructors implicitly called. 5648 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5649 return; 5650 5651 // FIXME: all the access-control diagnostics are positioned on the 5652 // field/base declaration. That's probably good; that said, the 5653 // user might reasonably want to know why the destructor is being 5654 // emitted, and we currently don't say. 5655 5656 // Non-static data members. 5657 for (auto *Field : ClassDecl->fields()) { 5658 if (Field->isInvalidDecl()) 5659 continue; 5660 5661 // Don't destroy incomplete or zero-length arrays. 5662 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5663 continue; 5664 5665 QualType FieldType = Context.getBaseElementType(Field->getType()); 5666 5667 const RecordType* RT = FieldType->getAs<RecordType>(); 5668 if (!RT) 5669 continue; 5670 5671 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5672 if (FieldClassDecl->isInvalidDecl()) 5673 continue; 5674 if (FieldClassDecl->hasIrrelevantDestructor()) 5675 continue; 5676 // The destructor for an implicit anonymous union member is never invoked. 5677 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5678 continue; 5679 5680 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5681 // Dtor might still be missing, e.g because it's invalid. 5682 if (!Dtor) 5683 continue; 5684 CheckDestructorAccess(Field->getLocation(), Dtor, 5685 PDiag(diag::err_access_dtor_field) 5686 << Field->getDeclName() 5687 << FieldType); 5688 5689 MarkFunctionReferenced(Location, Dtor); 5690 DiagnoseUseOfDecl(Dtor, Location); 5691 } 5692 5693 // We only potentially invoke the destructors of potentially constructed 5694 // subobjects. 5695 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5696 5697 // If the destructor exists and has already been marked used in the MS ABI, 5698 // then virtual base destructors have already been checked and marked used. 5699 // Skip checking them again to avoid duplicate diagnostics. 5700 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5701 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5702 if (Dtor && Dtor->isUsed()) 5703 VisitVirtualBases = false; 5704 } 5705 5706 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5707 5708 // Bases. 5709 for (const auto &Base : ClassDecl->bases()) { 5710 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5711 if (!RT) 5712 continue; 5713 5714 // Remember direct virtual bases. 5715 if (Base.isVirtual()) { 5716 if (!VisitVirtualBases) 5717 continue; 5718 DirectVirtualBases.insert(RT); 5719 } 5720 5721 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5722 // If our base class is invalid, we probably can't get its dtor anyway. 5723 if (BaseClassDecl->isInvalidDecl()) 5724 continue; 5725 if (BaseClassDecl->hasIrrelevantDestructor()) 5726 continue; 5727 5728 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5729 // Dtor might still be missing, e.g because it's invalid. 5730 if (!Dtor) 5731 continue; 5732 5733 // FIXME: caret should be on the start of the class name 5734 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5735 PDiag(diag::err_access_dtor_base) 5736 << Base.getType() << Base.getSourceRange(), 5737 Context.getTypeDeclType(ClassDecl)); 5738 5739 MarkFunctionReferenced(Location, Dtor); 5740 DiagnoseUseOfDecl(Dtor, Location); 5741 } 5742 5743 if (VisitVirtualBases) 5744 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5745 &DirectVirtualBases); 5746} 5747 5748void Sema::MarkVirtualBaseDestructorsReferenced( 5749 SourceLocation Location, CXXRecordDecl *ClassDecl, 5750 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5751 // Virtual bases. 5752 for (const auto &VBase : ClassDecl->vbases()) { 5753 // Bases are always records in a well-formed non-dependent class. 5754 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5755 5756 // Ignore already visited direct virtual bases. 5757 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5758 continue; 5759 5760 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5761 // If our base class is invalid, we probably can't get its dtor anyway. 5762 if (BaseClassDecl->isInvalidDecl()) 5763 continue; 5764 if (BaseClassDecl->hasIrrelevantDestructor()) 5765 continue; 5766 5767 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5768 // Dtor might still be missing, e.g because it's invalid. 5769 if (!Dtor) 5770 continue; 5771 if (CheckDestructorAccess( 5772 ClassDecl->getLocation(), Dtor, 5773 PDiag(diag::err_access_dtor_vbase) 5774 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5775 Context.getTypeDeclType(ClassDecl)) == 5776 AR_accessible) { 5777 CheckDerivedToBaseConversion( 5778 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5779 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5780 SourceRange(), DeclarationName(), nullptr); 5781 } 5782 5783 MarkFunctionReferenced(Location, Dtor); 5784 DiagnoseUseOfDecl(Dtor, Location); 5785 } 5786} 5787 5788void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5789 if (!CDtorDecl) 5790 return; 5791 5792 if (CXXConstructorDecl *Constructor 5793 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5794 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5795 DiagnoseUninitializedFields(*this, Constructor); 5796 } 5797} 5798 5799bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5800 if (!getLangOpts().CPlusPlus) 5801 return false; 5802 5803 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5804 if (!RD) 5805 return false; 5806 5807 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5808 // class template specialization here, but doing so breaks a lot of code. 5809 5810 // We can't answer whether something is abstract until it has a 5811 // definition. If it's currently being defined, we'll walk back 5812 // over all the declarations when we have a full definition. 5813 const CXXRecordDecl *Def = RD->getDefinition(); 5814 if (!Def || Def->isBeingDefined()) 5815 return false; 5816 5817 return RD->isAbstract(); 5818} 5819 5820bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5821 TypeDiagnoser &Diagnoser) { 5822 if (!isAbstractType(Loc, T)) 5823 return false; 5824 5825 T = Context.getBaseElementType(T); 5826 Diagnoser.diagnose(*this, Loc, T); 5827 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5828 return true; 5829} 5830 5831void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5832 // Check if we've already emitted the list of pure virtual functions 5833 // for this class. 5834 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5835 return; 5836 5837 // If the diagnostic is suppressed, don't emit the notes. We're only 5838 // going to emit them once, so try to attach them to a diagnostic we're 5839 // actually going to show. 5840 if (Diags.isLastDiagnosticIgnored()) 5841 return; 5842 5843 CXXFinalOverriderMap FinalOverriders; 5844 RD->getFinalOverriders(FinalOverriders); 5845 5846 // Keep a set of seen pure methods so we won't diagnose the same method 5847 // more than once. 5848 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5849 5850 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5851 MEnd = FinalOverriders.end(); 5852 M != MEnd; 5853 ++M) { 5854 for (OverridingMethods::iterator SO = M->second.begin(), 5855 SOEnd = M->second.end(); 5856 SO != SOEnd; ++SO) { 5857 // C++ [class.abstract]p4: 5858 // A class is abstract if it contains or inherits at least one 5859 // pure virtual function for which the final overrider is pure 5860 // virtual. 5861 5862 // 5863 if (SO->second.size() != 1) 5864 continue; 5865 5866 if (!SO->second.front().Method->isPure()) 5867 continue; 5868 5869 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5870 continue; 5871 5872 Diag(SO->second.front().Method->getLocation(), 5873 diag::note_pure_virtual_function) 5874 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5875 } 5876 } 5877 5878 if (!PureVirtualClassDiagSet) 5879 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5880 PureVirtualClassDiagSet->insert(RD); 5881} 5882 5883namespace { 5884struct AbstractUsageInfo { 5885 Sema &S; 5886 CXXRecordDecl *Record; 5887 CanQualType AbstractType; 5888 bool Invalid; 5889 5890 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5891 : S(S), Record(Record), 5892 AbstractType(S.Context.getCanonicalType( 5893 S.Context.getTypeDeclType(Record))), 5894 Invalid(false) {} 5895 5896 void DiagnoseAbstractType() { 5897 if (Invalid) return; 5898 S.DiagnoseAbstractType(Record); 5899 Invalid = true; 5900 } 5901 5902 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5903}; 5904 5905struct CheckAbstractUsage { 5906 AbstractUsageInfo &Info; 5907 const NamedDecl *Ctx; 5908 5909 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5910 : Info(Info), Ctx(Ctx) {} 5911 5912 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5913 switch (TL.getTypeLocClass()) { 5914#define ABSTRACT_TYPELOC(CLASS, PARENT) 5915#define TYPELOC(CLASS, PARENT) \ 5916 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5917#include "clang/AST/TypeLocNodes.def" 5918 } 5919 } 5920 5921 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5922 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5923 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5924 if (!TL.getParam(I)) 5925 continue; 5926 5927 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5928 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5929 } 5930 } 5931 5932 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5933 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5934 } 5935 5936 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5937 // Visit the type parameters from a permissive context. 5938 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5939 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5940 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5941 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5942 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5943 // TODO: other template argument types? 5944 } 5945 } 5946 5947 // Visit pointee types from a permissive context. 5948#define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc
(), Sema::AbstractNone); }
\
5949 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5950 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5951 } 5952 CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5953 CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5954 CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5955 CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5956 CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5957 5958 /// Handle all the types we haven't given a more specific 5959 /// implementation for above. 5960 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5961 // Every other kind of type that we haven't called out already 5962 // that has an inner type is either (1) sugar or (2) contains that 5963 // inner type in some way as a subobject. 5964 if (TypeLoc Next = TL.getNextTypeLoc()) 5965 return Visit(Next, Sel); 5966 5967 // If there's no inner type and we're in a permissive context, 5968 // don't diagnose. 5969 if (Sel == Sema::AbstractNone) return; 5970 5971 // Check whether the type matches the abstract type. 5972 QualType T = TL.getType(); 5973 if (T->isArrayType()) { 5974 Sel = Sema::AbstractArrayType; 5975 T = Info.S.Context.getBaseElementType(T); 5976 } 5977 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5978 if (CT != Info.AbstractType) return; 5979 5980 // It matched; do some magic. 5981 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646. 5982 if (Sel == Sema::AbstractArrayType) { 5983 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5984 << T << TL.getSourceRange(); 5985 } else { 5986 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5987 << Sel << T << TL.getSourceRange(); 5988 } 5989 Info.DiagnoseAbstractType(); 5990 } 5991}; 5992 5993void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5994 Sema::AbstractDiagSelID Sel) { 5995 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5996} 5997 5998} 5999 6000/// Check for invalid uses of an abstract type in a function declaration. 6001static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 6002 FunctionDecl *FD) { 6003 // No need to do the check on definitions, which require that 6004 // the return/param types be complete. 6005 if (FD->doesThisDeclarationHaveABody()) 6006 return; 6007 6008 // For safety's sake, just ignore it if we don't have type source 6009 // information. This should never happen for non-implicit methods, 6010 // but... 6011 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 6012 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone); 6013} 6014 6015/// Check for invalid uses of an abstract type in a variable0 declaration. 6016static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 6017 VarDecl *VD) { 6018 // No need to do the check on definitions, which require that 6019 // the type is complete. 6020 if (VD->isThisDeclarationADefinition()) 6021 return; 6022 6023 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(), 6024 Sema::AbstractVariableType); 6025} 6026 6027/// Check for invalid uses of an abstract type within a class definition. 6028static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 6029 CXXRecordDecl *RD) { 6030 for (auto *D : RD->decls()) { 6031 if (D->isImplicit()) continue; 6032 6033 // Step through friends to the befriended declaration. 6034 if (auto *FD = dyn_cast<FriendDecl>(D)) { 6035 D = FD->getFriendDecl(); 6036 if (!D) continue; 6037 } 6038 6039 // Functions and function templates. 6040 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 6041 CheckAbstractClassUsage(Info, FD); 6042 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) { 6043 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl()); 6044 6045 // Fields and static variables. 6046 } else if (auto *FD = dyn_cast<FieldDecl>(D)) { 6047 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 6048 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 6049 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 6050 CheckAbstractClassUsage(Info, VD); 6051 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) { 6052 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl()); 6053 6054 // Nested classes and class templates. 6055 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 6056 CheckAbstractClassUsage(Info, RD); 6057 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) { 6058 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl()); 6059 } 6060 } 6061} 6062 6063static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 6064 Attr *ClassAttr = getDLLAttr(Class); 6065 if (!ClassAttr) 6066 return; 6067 6068 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", 6068, __extension__ __PRETTY_FUNCTION__
))
; 6069 6070 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6071 6072 if (TSK == TSK_ExplicitInstantiationDeclaration) 6073 // Don't go any further if this is just an explicit instantiation 6074 // declaration. 6075 return; 6076 6077 // Add a context note to explain how we got to any diagnostics produced below. 6078 struct MarkingClassDllexported { 6079 Sema &S; 6080 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 6081 SourceLocation AttrLoc) 6082 : S(S) { 6083 Sema::CodeSynthesisContext Ctx; 6084 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 6085 Ctx.PointOfInstantiation = AttrLoc; 6086 Ctx.Entity = Class; 6087 S.pushCodeSynthesisContext(Ctx); 6088 } 6089 ~MarkingClassDllexported() { 6090 S.popCodeSynthesisContext(); 6091 } 6092 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 6093 6094 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 6095 S.MarkVTableUsed(Class->getLocation(), Class, true); 6096 6097 for (Decl *Member : Class->decls()) { 6098 // Skip members that were not marked exported. 6099 if (!Member->hasAttr<DLLExportAttr>()) 6100 continue; 6101 6102 // Defined static variables that are members of an exported base 6103 // class must be marked export too. 6104 auto *VD = dyn_cast<VarDecl>(Member); 6105 if (VD && VD->getStorageClass() == SC_Static && 6106 TSK == TSK_ImplicitInstantiation) 6107 S.MarkVariableReferenced(VD->getLocation(), VD); 6108 6109 auto *MD = dyn_cast<CXXMethodDecl>(Member); 6110 if (!MD) 6111 continue; 6112 6113 if (MD->isUserProvided()) { 6114 // Instantiate non-default class member functions ... 6115 6116 // .. except for certain kinds of template specializations. 6117 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 6118 continue; 6119 6120 // If this is an MS ABI dllexport default constructor, instantiate any 6121 // default arguments. 6122 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 6123 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6124 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) { 6125 S.InstantiateDefaultCtorDefaultArgs(CD); 6126 } 6127 } 6128 6129 S.MarkFunctionReferenced(Class->getLocation(), MD); 6130 6131 // The function will be passed to the consumer when its definition is 6132 // encountered. 6133 } else if (MD->isExplicitlyDefaulted()) { 6134 // Synthesize and instantiate explicitly defaulted methods. 6135 S.MarkFunctionReferenced(Class->getLocation(), MD); 6136 6137 if (TSK != TSK_ExplicitInstantiationDefinition) { 6138 // Except for explicit instantiation defs, we will not see the 6139 // definition again later, so pass it to the consumer now. 6140 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6141 } 6142 } else if (!MD->isTrivial() || 6143 MD->isCopyAssignmentOperator() || 6144 MD->isMoveAssignmentOperator()) { 6145 // Synthesize and instantiate non-trivial implicit methods, and the copy 6146 // and move assignment operators. The latter are exported even if they 6147 // are trivial, because the address of an operator can be taken and 6148 // should compare equal across libraries. 6149 S.MarkFunctionReferenced(Class->getLocation(), MD); 6150 6151 // There is no later point when we will see the definition of this 6152 // function, so pass it to the consumer now. 6153 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6154 } 6155 } 6156} 6157 6158static void checkForMultipleExportedDefaultConstructors(Sema &S, 6159 CXXRecordDecl *Class) { 6160 // Only the MS ABI has default constructor closures, so we don't need to do 6161 // this semantic checking anywhere else. 6162 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 6163 return; 6164 6165 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 6166 for (Decl *Member : Class->decls()) { 6167 // Look for exported default constructors. 6168 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 6169 if (!CD || !CD->isDefaultConstructor()) 6170 continue; 6171 auto *Attr = CD->getAttr<DLLExportAttr>(); 6172 if (!Attr) 6173 continue; 6174 6175 // If the class is non-dependent, mark the default arguments as ODR-used so 6176 // that we can properly codegen the constructor closure. 6177 if (!Class->isDependentContext()) { 6178 for (ParmVarDecl *PD : CD->parameters()) { 6179 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 6180 S.DiscardCleanupsInEvaluationContext(); 6181 } 6182 } 6183 6184 if (LastExportedDefaultCtor) { 6185 S.Diag(LastExportedDefaultCtor->getLocation(), 6186 diag::err_attribute_dll_ambiguous_default_ctor) 6187 << Class; 6188 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 6189 << CD->getDeclName(); 6190 return; 6191 } 6192 LastExportedDefaultCtor = CD; 6193 } 6194} 6195 6196static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 6197 CXXRecordDecl *Class) { 6198 bool ErrorReported = false; 6199 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6200 ClassTemplateDecl *TD) { 6201 if (ErrorReported) 6202 return; 6203 S.Diag(TD->getLocation(), 6204 diag::err_cuda_device_builtin_surftex_cls_template) 6205 << /*surface*/ 0 << TD; 6206 ErrorReported = true; 6207 }; 6208 6209 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6210 if (!TD) { 6211 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6212 if (!SD) { 6213 S.Diag(Class->getLocation(), 6214 diag::err_cuda_device_builtin_surftex_ref_decl) 6215 << /*surface*/ 0 << Class; 6216 S.Diag(Class->getLocation(), 6217 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6218 << Class; 6219 return; 6220 } 6221 TD = SD->getSpecializedTemplate(); 6222 } 6223 6224 TemplateParameterList *Params = TD->getTemplateParameters(); 6225 unsigned N = Params->size(); 6226 6227 if (N != 2) { 6228 reportIllegalClassTemplate(S, TD); 6229 S.Diag(TD->getLocation(), 6230 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6231 << TD << 2; 6232 } 6233 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6234 reportIllegalClassTemplate(S, TD); 6235 S.Diag(TD->getLocation(), 6236 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6237 << TD << /*1st*/ 0 << /*type*/ 0; 6238 } 6239 if (N > 1) { 6240 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6241 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6242 reportIllegalClassTemplate(S, TD); 6243 S.Diag(TD->getLocation(), 6244 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6245 << TD << /*2nd*/ 1 << /*integer*/ 1; 6246 } 6247 } 6248} 6249 6250static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 6251 CXXRecordDecl *Class) { 6252 bool ErrorReported = false; 6253 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6254 ClassTemplateDecl *TD) { 6255 if (ErrorReported) 6256 return; 6257 S.Diag(TD->getLocation(), 6258 diag::err_cuda_device_builtin_surftex_cls_template) 6259 << /*texture*/ 1 << TD; 6260 ErrorReported = true; 6261 }; 6262 6263 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6264 if (!TD) { 6265 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6266 if (!SD) { 6267 S.Diag(Class->getLocation(), 6268 diag::err_cuda_device_builtin_surftex_ref_decl) 6269 << /*texture*/ 1 << Class; 6270 S.Diag(Class->getLocation(), 6271 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6272 << Class; 6273 return; 6274 } 6275 TD = SD->getSpecializedTemplate(); 6276 } 6277 6278 TemplateParameterList *Params = TD->getTemplateParameters(); 6279 unsigned N = Params->size(); 6280 6281 if (N != 3) { 6282 reportIllegalClassTemplate(S, TD); 6283 S.Diag(TD->getLocation(), 6284 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6285 << TD << 3; 6286 } 6287 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6288 reportIllegalClassTemplate(S, TD); 6289 S.Diag(TD->getLocation(), 6290 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6291 << TD << /*1st*/ 0 << /*type*/ 0; 6292 } 6293 if (N > 1) { 6294 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6295 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6296 reportIllegalClassTemplate(S, TD); 6297 S.Diag(TD->getLocation(), 6298 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6299 << TD << /*2nd*/ 1 << /*integer*/ 1; 6300 } 6301 } 6302 if (N > 2) { 6303 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6304 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6305 reportIllegalClassTemplate(S, TD); 6306 S.Diag(TD->getLocation(), 6307 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6308 << TD << /*3rd*/ 2 << /*integer*/ 1; 6309 } 6310 } 6311} 6312 6313void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6314 // Mark any compiler-generated routines with the implicit code_seg attribute. 6315 for (auto *Method : Class->methods()) { 6316 if (Method->isUserProvided()) 6317 continue; 6318 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6319 Method->addAttr(A); 6320 } 6321} 6322 6323/// Check class-level dllimport/dllexport attribute. 6324void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6325 Attr *ClassAttr = getDLLAttr(Class); 6326 6327 // MSVC inherits DLL attributes to partial class template specializations. 6328 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { 6329 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6330 if (Attr *TemplateAttr = 6331 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6332 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6333 A->setInherited(true); 6334 ClassAttr = A; 6335 } 6336 } 6337 } 6338 6339 if (!ClassAttr) 6340 return; 6341 6342 // MSVC allows imported or exported template classes that have UniqueExternal 6343 // linkage. This occurs when the template class has been instantiated with 6344 // a template parameter which itself has internal linkage. 6345 // We drop the attribute to avoid exporting or importing any members. 6346 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() || 6347 Context.getTargetInfo().getTriple().isPS()) && 6348 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) { 6349 Class->dropAttr<DLLExportAttr>(); 6350 Class->dropAttr<DLLImportAttr>(); 6351 return; 6352 } 6353 6354 if (!Class->isExternallyVisible()) { 6355 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6356 << Class << ClassAttr; 6357 return; 6358 } 6359 6360 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6361 !ClassAttr->isInherited()) { 6362 // Diagnose dll attributes on members of class with dll attribute. 6363 for (Decl *Member : Class->decls()) { 6364 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6365 continue; 6366 InheritableAttr *MemberAttr = getDLLAttr(Member); 6367 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6368 continue; 6369 6370 Diag(MemberAttr->getLocation(), 6371 diag::err_attribute_dll_member_of_dll_class) 6372 << MemberAttr << ClassAttr; 6373 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6374 Member->setInvalidDecl(); 6375 } 6376 } 6377 6378 if (Class->getDescribedClassTemplate()) 6379 // Don't inherit dll attribute until the template is instantiated. 6380 return; 6381 6382 // The class is either imported or exported. 6383 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6384 6385 // Check if this was a dllimport attribute propagated from a derived class to 6386 // a base class template specialization. We don't apply these attributes to 6387 // static data members. 6388 const bool PropagatedImport = 6389 !ClassExported && 6390 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6391 6392 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6393 6394 // Ignore explicit dllexport on explicit class template instantiation 6395 // declarations, except in MinGW mode. 6396 if (ClassExported && !ClassAttr->isInherited() && 6397 TSK == TSK_ExplicitInstantiationDeclaration && 6398 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6399 Class->dropAttr<DLLExportAttr>(); 6400 return; 6401 } 6402 6403 // Force declaration of implicit members so they can inherit the attribute. 6404 ForceDeclarationOfImplicitMembers(Class); 6405 6406 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6407 // seem to be true in practice? 6408 6409 for (Decl *Member : Class->decls()) { 6410 VarDecl *VD = dyn_cast<VarDecl>(Member); 6411 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6412 6413 // Only methods and static fields inherit the attributes. 6414 if (!VD && !MD) 6415 continue; 6416 6417 if (MD) { 6418 // Don't process deleted methods. 6419 if (MD->isDeleted()) 6420 continue; 6421 6422 if (MD->isInlined()) { 6423 // MinGW does not import or export inline methods. But do it for 6424 // template instantiations. 6425 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6426 TSK != TSK_ExplicitInstantiationDeclaration && 6427 TSK != TSK_ExplicitInstantiationDefinition) 6428 continue; 6429 6430 // MSVC versions before 2015 don't export the move assignment operators 6431 // and move constructor, so don't attempt to import/export them if 6432 // we have a definition. 6433 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6434 if ((MD->isMoveAssignmentOperator() || 6435 (Ctor && Ctor->isMoveConstructor())) && 6436 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6437 continue; 6438 6439 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6440 // operator is exported anyway. 6441 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6442 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6443 continue; 6444 } 6445 } 6446 6447 // Don't apply dllimport attributes to static data members of class template 6448 // instantiations when the attribute is propagated from a derived class. 6449 if (VD && PropagatedImport) 6450 continue; 6451 6452 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6453 continue; 6454 6455 if (!getDLLAttr(Member)) { 6456 InheritableAttr *NewAttr = nullptr; 6457 6458 // Do not export/import inline function when -fno-dllexport-inlines is 6459 // passed. But add attribute for later local static var check. 6460 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6461 TSK != TSK_ExplicitInstantiationDeclaration && 6462 TSK != TSK_ExplicitInstantiationDefinition) { 6463 if (ClassExported) { 6464 NewAttr = ::new (getASTContext()) 6465 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6466 } else { 6467 NewAttr = ::new (getASTContext()) 6468 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6469 } 6470 } else { 6471 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6472 } 6473 6474 NewAttr->setInherited(true); 6475 Member->addAttr(NewAttr); 6476 6477 if (MD) { 6478 // Propagate DLLAttr to friend re-declarations of MD that have already 6479 // been constructed. 6480 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6481 FD = FD->getPreviousDecl()) { 6482 if (FD->getFriendObjectKind() == Decl::FOK_None) 6483 continue; 6484 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", 6485, __extension__ __PRETTY_FUNCTION__
))
6485 "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", 6485, __extension__ __PRETTY_FUNCTION__
))
; 6486 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6487 NewAttr->setInherited(true); 6488 FD->addAttr(NewAttr); 6489 } 6490 } 6491 } 6492 } 6493 6494 if (ClassExported) 6495 DelayedDllExportClasses.push_back(Class); 6496} 6497 6498/// Perform propagation of DLL attributes from a derived class to a 6499/// templated base class for MS compatibility. 6500void Sema::propagateDLLAttrToBaseClassTemplate( 6501 CXXRecordDecl *Class, Attr *ClassAttr, 6502 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6503 if (getDLLAttr( 6504 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6505 // If the base class template has a DLL attribute, don't try to change it. 6506 return; 6507 } 6508 6509 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6510 if (!getDLLAttr(BaseTemplateSpec) && 6511 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6512 TSK == TSK_ImplicitInstantiation)) { 6513 // The template hasn't been instantiated yet (or it has, but only as an 6514 // explicit instantiation declaration or implicit instantiation, which means 6515 // we haven't codegenned any members yet), so propagate the attribute. 6516 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6517 NewAttr->setInherited(true); 6518 BaseTemplateSpec->addAttr(NewAttr); 6519 6520 // If this was an import, mark that we propagated it from a derived class to 6521 // a base class template specialization. 6522 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6523 ImportAttr->setPropagatedToBaseTemplate(); 6524 6525 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6526 // needs to be run again to work see the new attribute. Otherwise this will 6527 // get run whenever the template is instantiated. 6528 if (TSK != TSK_Undeclared) 6529 checkClassLevelDLLAttribute(BaseTemplateSpec); 6530 6531 return; 6532 } 6533 6534 if (getDLLAttr(BaseTemplateSpec)) { 6535 // The template has already been specialized or instantiated with an 6536 // attribute, explicitly or through propagation. We should not try to change 6537 // it. 6538 return; 6539 } 6540 6541 // The template was previously instantiated or explicitly specialized without 6542 // a dll attribute, It's too late for us to add an attribute, so warn that 6543 // this is unsupported. 6544 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6545 << BaseTemplateSpec->isExplicitSpecialization(); 6546 Diag(ClassAttr->getLocation(), diag::note_attribute); 6547 if (BaseTemplateSpec->isExplicitSpecialization()) { 6548 Diag(BaseTemplateSpec->getLocation(), 6549 diag::note_template_class_explicit_specialization_was_here) 6550 << BaseTemplateSpec; 6551 } else { 6552 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6553 diag::note_template_class_instantiation_was_here) 6554 << BaseTemplateSpec; 6555 } 6556} 6557 6558/// Determine the kind of defaulting that would be done for a given function. 6559/// 6560/// If the function is both a default constructor and a copy / move constructor 6561/// (due to having a default argument for the first parameter), this picks 6562/// CXXDefaultConstructor. 6563/// 6564/// FIXME: Check that case is properly handled by all callers. 6565Sema::DefaultedFunctionKind 6566Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6567 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6568 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6569 if (Ctor->isDefaultConstructor()) 6570 return Sema::CXXDefaultConstructor; 6571 6572 if (Ctor->isCopyConstructor()) 6573 return Sema::CXXCopyConstructor; 6574 6575 if (Ctor->isMoveConstructor()) 6576 return Sema::CXXMoveConstructor; 6577 } 6578 6579 if (MD->isCopyAssignmentOperator()) 6580 return Sema::CXXCopyAssignment; 6581 6582 if (MD->isMoveAssignmentOperator()) 6583 return Sema::CXXMoveAssignment; 6584 6585 if (isa<CXXDestructorDecl>(FD)) 6586 return Sema::CXXDestructor; 6587 } 6588 6589 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6590 case OO_EqualEqual: 6591 return DefaultedComparisonKind::Equal; 6592 6593 case OO_ExclaimEqual: 6594 return DefaultedComparisonKind::NotEqual; 6595 6596 case OO_Spaceship: 6597 // No point allowing this if <=> doesn't exist in the current language mode. 6598 if (!getLangOpts().CPlusPlus20) 6599 break; 6600 return DefaultedComparisonKind::ThreeWay; 6601 6602 case OO_Less: 6603 case OO_LessEqual: 6604 case OO_Greater: 6605 case OO_GreaterEqual: 6606 // No point allowing this if <=> doesn't exist in the current language mode. 6607 if (!getLangOpts().CPlusPlus20) 6608 break; 6609 return DefaultedComparisonKind::Relational; 6610 6611 default: 6612 break; 6613 } 6614 6615 // Not defaultable. 6616 return DefaultedFunctionKind(); 6617} 6618 6619static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6620 SourceLocation DefaultLoc) { 6621 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6622 if (DFK.isComparison()) 6623 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6624 6625 switch (DFK.asSpecialMember()) { 6626 case Sema::CXXDefaultConstructor: 6627 S.DefineImplicitDefaultConstructor(DefaultLoc, 6628 cast<CXXConstructorDecl>(FD)); 6629 break; 6630 case Sema::CXXCopyConstructor: 6631 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6632 break; 6633 case Sema::CXXCopyAssignment: 6634 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6635 break; 6636 case Sema::CXXDestructor: 6637 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6638 break; 6639 case Sema::CXXMoveConstructor: 6640 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6641 break; 6642 case Sema::CXXMoveAssignment: 6643 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6644 break; 6645 case Sema::CXXInvalid: 6646 llvm_unreachable("Invalid special member.")::llvm::llvm_unreachable_internal("Invalid special member.", "clang/lib/Sema/SemaDeclCXX.cpp"
, 6646)
; 6647 } 6648} 6649 6650/// Determine whether a type is permitted to be passed or returned in 6651/// registers, per C++ [class.temporary]p3. 6652static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6653 TargetInfo::CallingConvKind CCK) { 6654 if (D->isDependentType() || D->isInvalidDecl()) 6655 return false; 6656 6657 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6658 // The PS4 platform ABI follows the behavior of Clang 3.2. 6659 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6660 return !D->hasNonTrivialDestructorForCall() && 6661 !D->hasNonTrivialCopyConstructorForCall(); 6662 6663 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6664 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6665 bool DtorIsTrivialForCall = false; 6666 6667 // If a class has at least one eligible, trivial copy constructor, it 6668 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6669 // 6670 // Note: This permits classes with non-trivial copy or move ctors to be 6671 // passed in registers, so long as they *also* have a trivial copy ctor, 6672 // which is non-conforming. 6673 if (D->needsImplicitCopyConstructor()) { 6674 if (!D->defaultedCopyConstructorIsDeleted()) { 6675 if (D->hasTrivialCopyConstructor()) 6676 CopyCtorIsTrivial = true; 6677 if (D->hasTrivialCopyConstructorForCall()) 6678 CopyCtorIsTrivialForCall = true; 6679 } 6680 } else { 6681 for (const CXXConstructorDecl *CD : D->ctors()) { 6682 if (CD->isCopyConstructor() && !CD->isDeleted() && 6683 !CD->isIneligibleOrNotSelected()) { 6684 if (CD->isTrivial()) 6685 CopyCtorIsTrivial = true; 6686 if (CD->isTrivialForCall()) 6687 CopyCtorIsTrivialForCall = true; 6688 } 6689 } 6690 } 6691 6692 if (D->needsImplicitDestructor()) { 6693 if (!D->defaultedDestructorIsDeleted() && 6694 D->hasTrivialDestructorForCall()) 6695 DtorIsTrivialForCall = true; 6696 } else if (const auto *DD = D->getDestructor()) { 6697 if (!DD->isDeleted() && DD->isTrivialForCall()) 6698 DtorIsTrivialForCall = true; 6699 } 6700 6701 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6702 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6703 return true; 6704 6705 // If a class has a destructor, we'd really like to pass it indirectly 6706 // because it allows us to elide copies. Unfortunately, MSVC makes that 6707 // impossible for small types, which it will pass in a single register or 6708 // stack slot. Most objects with dtors are large-ish, so handle that early. 6709 // We can't call out all large objects as being indirect because there are 6710 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6711 // how we pass large POD types. 6712 6713 // Note: This permits small classes with nontrivial destructors to be 6714 // passed in registers, which is non-conforming. 6715 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6716 uint64_t TypeSize = isAArch64 ? 128 : 64; 6717 6718 if (CopyCtorIsTrivial && 6719 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6720 return true; 6721 return false; 6722 } 6723 6724 // Per C++ [class.temporary]p3, the relevant condition is: 6725 // each copy constructor, move constructor, and destructor of X is 6726 // either trivial or deleted, and X has at least one non-deleted copy 6727 // or move constructor 6728 bool HasNonDeletedCopyOrMove = false; 6729 6730 if (D->needsImplicitCopyConstructor() && 6731 !D->defaultedCopyConstructorIsDeleted()) { 6732 if (!D->hasTrivialCopyConstructorForCall()) 6733 return false; 6734 HasNonDeletedCopyOrMove = true; 6735 } 6736 6737 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6738 !D->defaultedMoveConstructorIsDeleted()) { 6739 if (!D->hasTrivialMoveConstructorForCall()) 6740 return false; 6741 HasNonDeletedCopyOrMove = true; 6742 } 6743 6744 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6745 !D->hasTrivialDestructorForCall()) 6746 return false; 6747 6748 for (const CXXMethodDecl *MD : D->methods()) { 6749 if (MD->isDeleted() || MD->isIneligibleOrNotSelected()) 6750 continue; 6751 6752 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6753 if (CD && CD->isCopyOrMoveConstructor()) 6754 HasNonDeletedCopyOrMove = true; 6755 else if (!isa<CXXDestructorDecl>(MD)) 6756 continue; 6757 6758 if (!MD->isTrivialForCall()) 6759 return false; 6760 } 6761 6762 return HasNonDeletedCopyOrMove; 6763} 6764 6765/// Report an error regarding overriding, along with any relevant 6766/// overridden methods. 6767/// 6768/// \param DiagID the primary error to report. 6769/// \param MD the overriding method. 6770static bool 6771ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6772 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6773 bool IssuedDiagnostic = false; 6774 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6775 if (Report(O)) { 6776 if (!IssuedDiagnostic) { 6777 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6778 IssuedDiagnostic = true; 6779 } 6780 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6781 } 6782 } 6783 return IssuedDiagnostic; 6784} 6785 6786/// Perform semantic checks on a class definition that has been 6787/// completing, introducing implicitly-declared members, checking for 6788/// abstract types, etc. 6789/// 6790/// \param S The scope in which the class was parsed. Null if we didn't just 6791/// parse a class definition. 6792/// \param Record The completed class. 6793void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6794 if (!Record) 6795 return; 6796 6797 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6798 AbstractUsageInfo Info(*this, Record); 6799 CheckAbstractClassUsage(Info, Record); 6800 } 6801 6802 // If this is not an aggregate type and has no user-declared constructor, 6803 // complain about any non-static data members of reference or const scalar 6804 // type, since they will never get initializers. 6805 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6806 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6807 !Record->isLambda()) { 6808 bool Complained = false; 6809 for (const auto *F : Record->fields()) { 6810 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6811 continue; 6812 6813 if (F->getType()->isReferenceType() || 6814 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6815 if (!Complained) { 6816 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6817 << Record->getTagKind() << Record; 6818 Complained = true; 6819 } 6820 6821 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6822 << F->getType()->isReferenceType() 6823 << F->getDeclName(); 6824 } 6825 } 6826 } 6827 6828 if (Record->getIdentifier()) { 6829 // C++ [class.mem]p13: 6830 // If T is the name of a class, then each of the following shall have a 6831 // name different from T: 6832 // - every member of every anonymous union that is a member of class T. 6833 // 6834 // C++ [class.mem]p14: 6835 // In addition, if class T has a user-declared constructor (12.1), every 6836 // non-static data member of class T shall have a name different from T. 6837 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6838 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6839 ++I) { 6840 NamedDecl *D = (*I)->getUnderlyingDecl(); 6841 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6842 Record->hasUserDeclaredConstructor()) || 6843 isa<IndirectFieldDecl>(D)) { 6844 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6845 << D->getDeclName(); 6846 break; 6847 } 6848 } 6849 } 6850 6851 // Warn if the class has virtual methods but non-virtual public destructor. 6852 if (Record->isPolymorphic() && !Record->isDependentType()) { 6853 CXXDestructorDecl *dtor = Record->getDestructor(); 6854 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6855 !Record->hasAttr<FinalAttr>()) 6856 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6857 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6858 } 6859 6860 if (Record->isAbstract()) { 6861 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6862 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6863 << FA->isSpelledAsSealed(); 6864 DiagnoseAbstractType(Record); 6865 } 6866 } 6867 6868 // Warn if the class has a final destructor but is not itself marked final. 6869 if (!Record->hasAttr<FinalAttr>()) { 6870 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6871 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6872 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6873 << FA->isSpelledAsSealed() 6874 << FixItHint::CreateInsertion( 6875 getLocForEndOfToken(Record->getLocation()), 6876 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6877 Diag(Record->getLocation(), 6878 diag::note_final_dtor_non_final_class_silence) 6879 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6880 } 6881 } 6882 } 6883 6884 // See if trivial_abi has to be dropped. 6885 if (Record->hasAttr<TrivialABIAttr>()) 6886 checkIllFormedTrivialABIStruct(*Record); 6887 6888 // Set HasTrivialSpecialMemberForCall if the record has attribute 6889 // "trivial_abi". 6890 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6891 6892 if (HasTrivialABI) 6893 Record->setHasTrivialSpecialMemberForCall(); 6894 6895 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6896 // We check these last because they can depend on the properties of the 6897 // primary comparison functions (==, <=>). 6898 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6899 6900 // Perform checks that can't be done until we know all the properties of a 6901 // member function (whether it's defaulted, deleted, virtual, overriding, 6902 // ...). 6903 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6904 // A static function cannot override anything. 6905 if (MD->getStorageClass() == SC_Static) { 6906 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6907 [](const CXXMethodDecl *) { return true; })) 6908 return; 6909 } 6910 6911 // A deleted function cannot override a non-deleted function and vice 6912 // versa. 6913 if (ReportOverrides(*this, 6914 MD->isDeleted() ? diag::err_deleted_override 6915 : diag::err_non_deleted_override, 6916 MD, [&](const CXXMethodDecl *V) { 6917 return MD->isDeleted() != V->isDeleted(); 6918 })) { 6919 if (MD->isDefaulted() && MD->isDeleted()) 6920 // Explain why this defaulted function was deleted. 6921 DiagnoseDeletedDefaultedFunction(MD); 6922 return; 6923 } 6924 6925 // A consteval function cannot override a non-consteval function and vice 6926 // versa. 6927 if (ReportOverrides(*this, 6928 MD->isConsteval() ? diag::err_consteval_override 6929 : diag::err_non_consteval_override, 6930 MD, [&](const CXXMethodDecl *V) { 6931 return MD->isConsteval() != V->isConsteval(); 6932 })) { 6933 if (MD->isDefaulted() && MD->isDeleted()) 6934 // Explain why this defaulted function was deleted. 6935 DiagnoseDeletedDefaultedFunction(MD); 6936 return; 6937 } 6938 }; 6939 6940 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6941 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6942 return false; 6943 6944 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6945 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6946 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6947 DefaultedSecondaryComparisons.push_back(FD); 6948 return true; 6949 } 6950 6951 CheckExplicitlyDefaultedFunction(S, FD); 6952 return false; 6953 }; 6954 6955 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6956 // Check whether the explicitly-defaulted members are valid. 6957 bool Incomplete = CheckForDefaultedFunction(M); 6958 6959 // Skip the rest of the checks for a member of a dependent class. 6960 if (Record->isDependentType()) 6961 return; 6962 6963 // For an explicitly defaulted or deleted special member, we defer 6964 // determining triviality until the class is complete. That time is now! 6965 CXXSpecialMember CSM = getSpecialMember(M); 6966 if (!M->isImplicit() && !M->isUserProvided()) { 6967 if (CSM != CXXInvalid) { 6968 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6969 // Inform the class that we've finished declaring this member. 6970 Record->finishedDefaultedOrDeletedMember(M); 6971 M->setTrivialForCall( 6972 HasTrivialABI || 6973 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6974 Record->setTrivialForCallFlags(M); 6975 } 6976 } 6977 6978 // Set triviality for the purpose of calls if this is a user-provided 6979 // copy/move constructor or destructor. 6980 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6981 CSM == CXXDestructor) && M->isUserProvided()) { 6982 M->setTrivialForCall(HasTrivialABI); 6983 Record->setTrivialForCallFlags(M); 6984 } 6985 6986 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6987 M->hasAttr<DLLExportAttr>()) { 6988 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6989 M->isTrivial() && 6990 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6991 CSM == CXXDestructor)) 6992 M->dropAttr<DLLExportAttr>(); 6993 6994 if (M->hasAttr<DLLExportAttr>()) { 6995 // Define after any fields with in-class initializers have been parsed. 6996 DelayedDllExportMemberFunctions.push_back(M); 6997 } 6998 } 6999 7000 // Define defaulted constexpr virtual functions that override a base class 7001 // function right away. 7002 // FIXME: We can defer doing this until the vtable is marked as used. 7003 if (CSM != CXXInvalid && !M->isDeleted() && M->isDefaulted() && 7004 M->isConstexpr() && M->size_overridden_methods()) 7005 DefineDefaultedFunction(*this, M, M->getLocation()); 7006 7007 if (!Incomplete) 7008 CheckCompletedMemberFunction(M); 7009 }; 7010 7011 // Check the destructor before any other member function. We need to 7012 // determine whether it's trivial in order to determine whether the claas 7013 // type is a literal type, which is a prerequisite for determining whether 7014 // other special member functions are valid and whether they're implicitly 7015 // 'constexpr'. 7016 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 7017 CompleteMemberFunction(Dtor); 7018 7019 bool HasMethodWithOverrideControl = false, 7020 HasOverridingMethodWithoutOverrideControl = false; 7021 for (auto *D : Record->decls()) { 7022 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 7023 // FIXME: We could do this check for dependent types with non-dependent 7024 // bases. 7025 if (!Record->isDependentType()) { 7026 // See if a method overloads virtual methods in a base 7027 // class without overriding any. 7028 if (!M->isStatic()) 7029 DiagnoseHiddenVirtualMethods(M); 7030 if (M->hasAttr<OverrideAttr>()) 7031 HasMethodWithOverrideControl = true; 7032 else if (M->size_overridden_methods() > 0) 7033 HasOverridingMethodWithoutOverrideControl = true; 7034 } 7035 7036 if (!isa<CXXDestructorDecl>(M)) 7037 CompleteMemberFunction(M); 7038 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 7039 CheckForDefaultedFunction( 7040 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 7041 } 7042 } 7043 7044 if (HasOverridingMethodWithoutOverrideControl) { 7045 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 7046 for (auto *M : Record->methods()) 7047 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 7048 } 7049 7050 // Check the defaulted secondary comparisons after any other member functions. 7051 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 7052 CheckExplicitlyDefaultedFunction(S, FD); 7053 7054 // If this is a member function, we deferred checking it until now. 7055 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 7056 CheckCompletedMemberFunction(MD); 7057 } 7058 7059 // ms_struct is a request to use the same ABI rules as MSVC. Check 7060 // whether this class uses any C++ features that are implemented 7061 // completely differently in MSVC, and if so, emit a diagnostic. 7062 // That diagnostic defaults to an error, but we allow projects to 7063 // map it down to a warning (or ignore it). It's a fairly common 7064 // practice among users of the ms_struct pragma to mass-annotate 7065 // headers, sweeping up a bunch of types that the project doesn't 7066 // really rely on MSVC-compatible layout for. We must therefore 7067 // support "ms_struct except for C++ stuff" as a secondary ABI. 7068 // Don't emit this diagnostic if the feature was enabled as a 7069 // language option (as opposed to via a pragma or attribute), as 7070 // the option -mms-bitfields otherwise essentially makes it impossible 7071 // to build C++ code, unless this diagnostic is turned off. 7072 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 7073 (Record->isPolymorphic() || Record->getNumBases())) { 7074 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 7075 } 7076 7077 checkClassLevelDLLAttribute(Record); 7078 checkClassLevelCodeSegAttribute(Record); 7079 7080 bool ClangABICompat4 = 7081 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 7082 TargetInfo::CallingConvKind CCK = 7083 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 7084 bool CanPass = canPassInRegisters(*this, Record, CCK); 7085 7086 // Do not change ArgPassingRestrictions if it has already been set to 7087 // APK_CanNeverPassInRegs. 7088 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 7089 Record->setArgPassingRestrictions(CanPass 7090 ? RecordDecl::APK_CanPassInRegs 7091 : RecordDecl::APK_CannotPassInRegs); 7092 7093 // If canPassInRegisters returns true despite the record having a non-trivial 7094 // destructor, the record is destructed in the callee. This happens only when 7095 // the record or one of its subobjects has a field annotated with trivial_abi 7096 // or a field qualified with ObjC __strong/__weak. 7097 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 7098 Record->setParamDestroyedInCallee(true); 7099 else if (Record->hasNonTrivialDestructor()) 7100 Record->setParamDestroyedInCallee(CanPass); 7101 7102 if (getLangOpts().ForceEmitVTables) { 7103 // If we want to emit all the vtables, we need to mark it as used. This 7104 // is especially required for cases like vtable assumption loads. 7105 MarkVTableUsed(Record->getInnerLocStart(), Record); 7106 } 7107 7108 if (getLangOpts().CUDA) { 7109 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 7110 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 7111 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 7112 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 7113 } 7114} 7115 7116/// Look up the special member function that would be called by a special 7117/// member function for a subobject of class type. 7118/// 7119/// \param Class The class type of the subobject. 7120/// \param CSM The kind of special member function. 7121/// \param FieldQuals If the subobject is a field, its cv-qualifiers. 7122/// \param ConstRHS True if this is a copy operation with a const object 7123/// on its RHS, that is, if the argument to the outer special member 7124/// function is 'const' and this is not a field marked 'mutable'. 7125static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 7126 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 7127 unsigned FieldQuals, bool ConstRHS) { 7128 unsigned LHSQuals = 0; 7129 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 7130 LHSQuals = FieldQuals; 7131 7132 unsigned RHSQuals = FieldQuals; 7133 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 7134 RHSQuals = 0; 7135 else if (ConstRHS) 7136 RHSQuals |= Qualifiers::Const; 7137 7138 return S.LookupSpecialMember(Class, CSM, 7139 RHSQuals & Qualifiers::Const, 7140 RHSQuals & Qualifiers::Volatile, 7141 false, 7142 LHSQuals & Qualifiers::Const, 7143 LHSQuals & Qualifiers::Volatile); 7144} 7145 7146class Sema::InheritedConstructorInfo { 7147 Sema &S; 7148 SourceLocation UseLoc; 7149 7150 /// A mapping from the base classes through which the constructor was 7151 /// inherited to the using shadow declaration in that base class (or a null 7152 /// pointer if the constructor was declared in that base class). 7153 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 7154 InheritedFromBases; 7155 7156public: 7157 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 7158 ConstructorUsingShadowDecl *Shadow) 7159 : S(S), UseLoc(UseLoc) { 7160 bool DiagnosedMultipleConstructedBases = false; 7161 CXXRecordDecl *ConstructedBase = nullptr; 7162 BaseUsingDecl *ConstructedBaseIntroducer = nullptr; 7163 7164 // Find the set of such base class subobjects and check that there's a 7165 // unique constructed subobject. 7166 for (auto *D : Shadow->redecls()) { 7167 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 7168 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 7169 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 7170 7171 InheritedFromBases.insert( 7172 std::make_pair(DNominatedBase->getCanonicalDecl(), 7173 DShadow->getNominatedBaseClassShadowDecl())); 7174 if (DShadow->constructsVirtualBase()) 7175 InheritedFromBases.insert( 7176 std::make_pair(DConstructedBase->getCanonicalDecl(), 7177 DShadow->getConstructedBaseClassShadowDecl())); 7178 else 7179 assert(DNominatedBase == DConstructedBase)(static_cast <bool> (DNominatedBase == DConstructedBase
) ? void (0) : __assert_fail ("DNominatedBase == DConstructedBase"
, "clang/lib/Sema/SemaDeclCXX.cpp", 7179, __extension__ __PRETTY_FUNCTION__
))
; 7180 7181 // [class.inhctor.init]p2: 7182 // If the constructor was inherited from multiple base class subobjects 7183 // of type B, the program is ill-formed. 7184 if (!ConstructedBase) { 7185 ConstructedBase = DConstructedBase; 7186 ConstructedBaseIntroducer = D->getIntroducer(); 7187 } else if (ConstructedBase != DConstructedBase && 7188 !Shadow->isInvalidDecl()) { 7189 if (!DiagnosedMultipleConstructedBases) { 7190 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 7191 << Shadow->getTargetDecl(); 7192 S.Diag(ConstructedBaseIntroducer->getLocation(), 7193 diag::note_ambiguous_inherited_constructor_using) 7194 << ConstructedBase; 7195 DiagnosedMultipleConstructedBases = true; 7196 } 7197 S.Diag(D->getIntroducer()->getLocation(), 7198 diag::note_ambiguous_inherited_constructor_using) 7199 << DConstructedBase; 7200 } 7201 } 7202 7203 if (DiagnosedMultipleConstructedBases) 7204 Shadow->setInvalidDecl(); 7205 } 7206 7207 /// Find the constructor to use for inherited construction of a base class, 7208 /// and whether that base class constructor inherits the constructor from a 7209 /// virtual base class (in which case it won't actually invoke it). 7210 std::pair<CXXConstructorDecl *, bool> 7211 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 7212 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 7213 if (It == InheritedFromBases.end()) 7214 return std::make_pair(nullptr, false); 7215 7216 // This is an intermediary class. 7217 if (It->second) 7218 return std::make_pair( 7219 S.findInheritingConstructor(UseLoc, Ctor, It->second), 7220 It->second->constructsVirtualBase()); 7221 7222 // This is the base class from which the constructor was inherited. 7223 return std::make_pair(Ctor, false); 7224 } 7225}; 7226 7227/// Is the special member function which would be selected to perform the 7228/// specified operation on the specified class type a constexpr constructor? 7229static bool 7230specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 7231 Sema::CXXSpecialMember CSM, unsigned Quals, 7232 bool ConstRHS, 7233 CXXConstructorDecl *InheritedCtor = nullptr, 7234 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7235 // Suppress duplicate constraint checking here, in case a constraint check 7236 // caused us to decide to do this. Any truely recursive checks will get 7237 // caught during these checks anyway. 7238 Sema::SatisfactionStackResetRAII SSRAII{S}; 7239 7240 // If we're inheriting a constructor, see if we need to call it for this base 7241 // class. 7242 if (InheritedCtor) { 7243 assert(CSM == Sema::CXXDefaultConstructor)(static_cast <bool> (CSM == Sema::CXXDefaultConstructor
) ? void (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor"
, "clang/lib/Sema/SemaDeclCXX.cpp", 7243, __extension__ __PRETTY_FUNCTION__
))
; 7244 auto BaseCtor = 7245 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 7246 if (BaseCtor) 7247 return BaseCtor->isConstexpr(); 7248 } 7249 7250 if (CSM == Sema::CXXDefaultConstructor) 7251 return ClassDecl->hasConstexprDefaultConstructor(); 7252 if (CSM == Sema::CXXDestructor) 7253 return ClassDecl->hasConstexprDestructor(); 7254 7255 Sema::SpecialMemberOverloadResult SMOR = 7256 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 7257 if (!SMOR.getMethod()) 7258 // A constructor we wouldn't select can't be "involved in initializing" 7259 // anything. 7260 return true; 7261 return SMOR.getMethod()->isConstexpr(); 7262} 7263 7264/// Determine whether the specified special member function would be constexpr 7265/// if it were implicitly defined. 7266static bool defaultedSpecialMemberIsConstexpr( 7267 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 7268 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 7269 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7270 if (!S.getLangOpts().CPlusPlus11) 7271 return false; 7272 7273 // C++11 [dcl.constexpr]p4: 7274 // In the definition of a constexpr constructor [...] 7275 bool Ctor = true; 7276 switch (CSM) { 7277 case Sema::CXXDefaultConstructor: 7278 if (Inherited) 7279 break; 7280 // Since default constructor lookup is essentially trivial (and cannot 7281 // involve, for instance, template instantiation), we compute whether a 7282 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7283 // 7284 // This is important for performance; we need to know whether the default 7285 // constructor is constexpr to determine whether the type is a literal type. 7286 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7287 7288 case Sema::CXXCopyConstructor: 7289 case Sema::CXXMoveConstructor: 7290 // For copy or move constructors, we need to perform overload resolution. 7291 break; 7292 7293 case Sema::CXXCopyAssignment: 7294 case Sema::CXXMoveAssignment: 7295 if (!S.getLangOpts().CPlusPlus14) 7296 return false; 7297 // In C++1y, we need to perform overload resolution. 7298 Ctor = false; 7299 break; 7300 7301 case Sema::CXXDestructor: 7302 return ClassDecl->defaultedDestructorIsConstexpr(); 7303 7304 case Sema::CXXInvalid: 7305 return false; 7306 } 7307 7308 // -- if the class is a non-empty union, or for each non-empty anonymous 7309 // union member of a non-union class, exactly one non-static data member 7310 // shall be initialized; [DR1359] 7311 // 7312 // If we squint, this is guaranteed, since exactly one non-static data member 7313 // will be initialized (if the constructor isn't deleted), we just don't know 7314 // which one. 7315 if (Ctor && ClassDecl->isUnion()) 7316 return CSM == Sema::CXXDefaultConstructor 7317 ? ClassDecl->hasInClassInitializer() || 7318 !ClassDecl->hasVariantMembers() 7319 : true; 7320 7321 // -- the class shall not have any virtual base classes; 7322 if (Ctor && ClassDecl->getNumVBases()) 7323 return false; 7324 7325 // C++1y [class.copy]p26: 7326 // -- [the class] is a literal type, and 7327 if (!Ctor && !ClassDecl->isLiteral()) 7328 return false; 7329 7330 // -- every constructor involved in initializing [...] base class 7331 // sub-objects shall be a constexpr constructor; 7332 // -- the assignment operator selected to copy/move each direct base 7333 // class is a constexpr function, and 7334 for (const auto &B : ClassDecl->bases()) { 7335 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7336 if (!BaseType) 7337 continue; 7338 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7339 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7340 InheritedCtor, Inherited)) 7341 return false; 7342 } 7343 7344 // -- every constructor involved in initializing non-static data members 7345 // [...] shall be a constexpr constructor; 7346 // -- every non-static data member and base class sub-object shall be 7347 // initialized 7348 // -- for each non-static data member of X that is of class type (or array 7349 // thereof), the assignment operator selected to copy/move that member is 7350 // a constexpr function 7351 for (const auto *F : ClassDecl->fields()) { 7352 if (F->isInvalidDecl()) 7353 continue; 7354 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7355 continue; 7356 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7357 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7358 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7359 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7360 BaseType.getCVRQualifiers(), 7361 ConstArg && !F->isMutable())) 7362 return false; 7363 } else if (CSM == Sema::CXXDefaultConstructor) { 7364 return false; 7365 } 7366 } 7367 7368 // All OK, it's constexpr! 7369 return true; 7370} 7371 7372namespace { 7373/// RAII object to register a defaulted function as having its exception 7374/// specification computed. 7375struct ComputingExceptionSpec { 7376 Sema &S; 7377 7378 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7379 : S(S) { 7380 Sema::CodeSynthesisContext Ctx; 7381 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7382 Ctx.PointOfInstantiation = Loc; 7383 Ctx.Entity = FD; 7384 S.pushCodeSynthesisContext(Ctx); 7385 } 7386 ~ComputingExceptionSpec() { 7387 S.popCodeSynthesisContext(); 7388 } 7389}; 7390} 7391 7392static Sema::ImplicitExceptionSpecification 7393ComputeDefaultedSpecialMemberExceptionSpec( 7394 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7395 Sema::InheritedConstructorInfo *ICI); 7396 7397static Sema::ImplicitExceptionSpecification 7398ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7399 FunctionDecl *FD, 7400 Sema::DefaultedComparisonKind DCK); 7401 7402static Sema::ImplicitExceptionSpecification 7403computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7404 auto DFK = S.getDefaultedFunctionKind(FD); 7405 if (DFK.isSpecialMember()) 7406 return ComputeDefaultedSpecialMemberExceptionSpec( 7407 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7408 if (DFK.isComparison()) 7409 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7410 DFK.asComparison()); 7411 7412 auto *CD = cast<CXXConstructorDecl>(FD); 7413 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", 7415, __extension__ __PRETTY_FUNCTION__
))
7414 "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", 7415, __extension__ __PRETTY_FUNCTION__
))
7415 "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", 7415, __extension__ __PRETTY_FUNCTION__
))
; 7416 Sema::InheritedConstructorInfo ICI( 7417 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7418 return ComputeDefaultedSpecialMemberExceptionSpec( 7419 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7420} 7421 7422static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7423 CXXMethodDecl *MD) { 7424 FunctionProtoType::ExtProtoInfo EPI; 7425 7426 // Build an exception specification pointing back at this member. 7427 EPI.ExceptionSpec.Type = EST_Unevaluated; 7428 EPI.ExceptionSpec.SourceDecl = MD; 7429 7430 // Set the calling convention to the default for C++ instance methods. 7431 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7432 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7433 /*IsCXXMethod=*/true)); 7434 return EPI; 7435} 7436 7437void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7438 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7439 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7440 return; 7441 7442 // Evaluate the exception specification. 7443 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7444 auto ESI = IES.getExceptionSpec(); 7445 7446 // Update the type of the special member to use it. 7447 UpdateExceptionSpec(FD, ESI); 7448} 7449 7450void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7451 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", 7451, __extension__ __PRETTY_FUNCTION__
))
; 7452 7453 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7454 if (!DefKind) { 7455 assert(FD->getDeclContext()->isDependentContext())(static_cast <bool> (FD->getDeclContext()->isDependentContext
()) ? void (0) : __assert_fail ("FD->getDeclContext()->isDependentContext()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 7455, __extension__ __PRETTY_FUNCTION__
))
; 7456 return; 7457 } 7458 7459 if (DefKind.isComparison()) 7460 UnusedPrivateFields.clear(); 7461 7462 if (DefKind.isSpecialMember() 7463 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7464 DefKind.asSpecialMember(), 7465 FD->getDefaultLoc()) 7466 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7467 FD->setInvalidDecl(); 7468} 7469 7470bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7471 CXXSpecialMember CSM, 7472 SourceLocation DefaultLoc) { 7473 CXXRecordDecl *RD = MD->getParent(); 7474 7475 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", 7476, __extension__ __PRETTY_FUNCTION__
))
7476 "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", 7476, __extension__ __PRETTY_FUNCTION__
))
; 7477 7478 // Defer all checking for special members of a dependent type. 7479 if (RD->isDependentType()) 7480 return false; 7481 7482 // Whether this was the first-declared instance of the constructor. 7483 // This affects whether we implicitly add an exception spec and constexpr. 7484 bool First = MD == MD->getCanonicalDecl(); 7485 7486 bool HadError = false; 7487 7488 // C++11 [dcl.fct.def.default]p1: 7489 // A function that is explicitly defaulted shall 7490 // -- be a special member function [...] (checked elsewhere), 7491 // -- have the same type (except for ref-qualifiers, and except that a 7492 // copy operation can take a non-const reference) as an implicit 7493 // declaration, and 7494 // -- not have default arguments. 7495 // C++2a changes the second bullet to instead delete the function if it's 7496 // defaulted on its first declaration, unless it's "an assignment operator, 7497 // and its return type differs or its parameter type is not a reference". 7498 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7499 bool ShouldDeleteForTypeMismatch = false; 7500 unsigned ExpectedParams = 1; 7501 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7502 ExpectedParams = 0; 7503 if (MD->getNumParams() != ExpectedParams) { 7504 // This checks for default arguments: a copy or move constructor with a 7505 // default argument is classified as a default constructor, and assignment 7506 // operations and destructors can't have default arguments. 7507 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7508 << CSM << MD->getSourceRange(); 7509 HadError = true; 7510 } else if (MD->isVariadic()) { 7511 if (DeleteOnTypeMismatch) 7512 ShouldDeleteForTypeMismatch = true; 7513 else { 7514 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7515 << CSM << MD->getSourceRange(); 7516 HadError = true; 7517 } 7518 } 7519 7520 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7521 7522 bool CanHaveConstParam = false; 7523 if (CSM == CXXCopyConstructor) 7524 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7525 else if (CSM == CXXCopyAssignment) 7526 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7527 7528 QualType ReturnType = Context.VoidTy; 7529 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7530 // Check for return type matching. 7531 ReturnType = Type->getReturnType(); 7532 7533 QualType DeclType = Context.getTypeDeclType(RD); 7534 DeclType = Context.getElaboratedType(ETK_None, nullptr, DeclType, nullptr); 7535 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7536 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7537 7538 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7539 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7540 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7541 HadError = true; 7542 } 7543 7544 // A defaulted special member cannot have cv-qualifiers. 7545 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7546 if (DeleteOnTypeMismatch) 7547 ShouldDeleteForTypeMismatch = true; 7548 else { 7549 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7550 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7551 HadError = true; 7552 } 7553 } 7554 } 7555 7556 // Check for parameter type matching. 7557 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7558 bool HasConstParam = false; 7559 if (ExpectedParams && ArgType->isReferenceType()) { 7560 // Argument must be reference to possibly-const T. 7561 QualType ReferentType = ArgType->getPointeeType(); 7562 HasConstParam = ReferentType.isConstQualified(); 7563 7564 if (ReferentType.isVolatileQualified()) { 7565 if (DeleteOnTypeMismatch) 7566 ShouldDeleteForTypeMismatch = true; 7567 else { 7568 Diag(MD->getLocation(), 7569 diag::err_defaulted_special_member_volatile_param) << CSM; 7570 HadError = true; 7571 } 7572 } 7573 7574 if (HasConstParam && !CanHaveConstParam) { 7575 if (DeleteOnTypeMismatch) 7576 ShouldDeleteForTypeMismatch = true; 7577 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7578 Diag(MD->getLocation(), 7579 diag::err_defaulted_special_member_copy_const_param) 7580 << (CSM == CXXCopyAssignment); 7581 // FIXME: Explain why this special member can't be const. 7582 HadError = true; 7583 } else { 7584 Diag(MD->getLocation(), 7585 diag::err_defaulted_special_member_move_const_param) 7586 << (CSM == CXXMoveAssignment); 7587 HadError = true; 7588 } 7589 } 7590 } else if (ExpectedParams) { 7591 // A copy assignment operator can take its argument by value, but a 7592 // defaulted one cannot. 7593 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", 7593, __extension__ __PRETTY_FUNCTION__
))
; 7594 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7595 HadError = true; 7596 } 7597 7598 // C++11 [dcl.fct.def.default]p2: 7599 // An explicitly-defaulted function may be declared constexpr only if it 7600 // would have been implicitly declared as constexpr, 7601 // Do not apply this rule to members of class templates, since core issue 1358 7602 // makes such functions always instantiate to constexpr functions. For 7603 // functions which cannot be constexpr (for non-constructors in C++11 and for 7604 // destructors in C++14 and C++17), this is checked elsewhere. 7605 // 7606 // FIXME: This should not apply if the member is deleted. 7607 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7608 HasConstParam); 7609 7610 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358): 7611 // If the instantiated template specialization of a constexpr function 7612 // template or member function of a class template would fail to satisfy 7613 // the requirements for a constexpr function or constexpr constructor, that 7614 // specialization is still a constexpr function or constexpr constructor, 7615 // even though a call to such a function cannot appear in a constant 7616 // expression. 7617 if (MD->isTemplateInstantiation() && MD->isConstexpr()) 7618 Constexpr = true; 7619 7620 if ((getLangOpts().CPlusPlus20 || 7621 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7622 : isa<CXXConstructorDecl>(MD))) && 7623 MD->isConstexpr() && !Constexpr && 7624 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7625 Diag(MD->getBeginLoc(), MD->isConsteval() 7626 ? diag::err_incorrect_defaulted_consteval 7627 : diag::err_incorrect_defaulted_constexpr) 7628 << CSM; 7629 // FIXME: Explain why the special member can't be constexpr. 7630 HadError = true; 7631 } 7632 7633 if (First) { 7634 // C++2a [dcl.fct.def.default]p3: 7635 // If a function is explicitly defaulted on its first declaration, it is 7636 // implicitly considered to be constexpr if the implicit declaration 7637 // would be. 7638 MD->setConstexprKind(Constexpr ? (MD->isConsteval() 7639 ? ConstexprSpecKind::Consteval 7640 : ConstexprSpecKind::Constexpr) 7641 : ConstexprSpecKind::Unspecified); 7642 7643 if (!Type->hasExceptionSpec()) { 7644 // C++2a [except.spec]p3: 7645 // If a declaration of a function does not have a noexcept-specifier 7646 // [and] is defaulted on its first declaration, [...] the exception 7647 // specification is as specified below 7648 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7649 EPI.ExceptionSpec.Type = EST_Unevaluated; 7650 EPI.ExceptionSpec.SourceDecl = MD; 7651 MD->setType(Context.getFunctionType( 7652 ReturnType, llvm::ArrayRef(&ArgType, ExpectedParams), EPI)); 7653 } 7654 } 7655 7656 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7657 if (First) { 7658 SetDeclDeleted(MD, MD->getLocation()); 7659 if (!inTemplateInstantiation() && !HadError) { 7660 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7661 if (ShouldDeleteForTypeMismatch) { 7662 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7663 } else if (ShouldDeleteSpecialMember(MD, CSM, nullptr, 7664 /*Diagnose*/ true) && 7665 DefaultLoc.isValid()) { 7666 Diag(DefaultLoc, diag::note_replace_equals_default_to_delete) 7667 << FixItHint::CreateReplacement(DefaultLoc, "delete"); 7668 } 7669 } 7670 if (ShouldDeleteForTypeMismatch && !HadError) { 7671 Diag(MD->getLocation(), 7672 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7673 } 7674 } else { 7675 // C++11 [dcl.fct.def.default]p4: 7676 // [For a] user-provided explicitly-defaulted function [...] if such a 7677 // function is implicitly defined as deleted, the program is ill-formed. 7678 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7679 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", 7679, __extension__ __PRETTY_FUNCTION__
))
; 7680 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7681 HadError = true; 7682 } 7683 } 7684 7685 return HadError; 7686} 7687 7688namespace { 7689/// Helper class for building and checking a defaulted comparison. 7690/// 7691/// Defaulted functions are built in two phases: 7692/// 7693/// * First, the set of operations that the function will perform are 7694/// identified, and some of them are checked. If any of the checked 7695/// operations is invalid in certain ways, the comparison function is 7696/// defined as deleted and no body is built. 7697/// * Then, if the function is not defined as deleted, the body is built. 7698/// 7699/// This is accomplished by performing two visitation steps over the eventual 7700/// body of the function. 7701template<typename Derived, typename ResultList, typename Result, 7702 typename Subobject> 7703class DefaultedComparisonVisitor { 7704public: 7705 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7706 7707 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7708 DefaultedComparisonKind DCK) 7709 : S(S), RD(RD), FD(FD), DCK(DCK) { 7710 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7711 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7712 // UnresolvedSet to avoid this copy. 7713 Fns.assign(Info->getUnqualifiedLookups().begin(), 7714 Info->getUnqualifiedLookups().end()); 7715 } 7716 } 7717 7718 ResultList visit() { 7719 // The type of an lvalue naming a parameter of this function. 7720 QualType ParamLvalType = 7721 FD->getParamDecl(0)->getType().getNonReferenceType(); 7722 7723 ResultList Results; 7724 7725 switch (DCK) { 7726 case DefaultedComparisonKind::None: 7727 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "clang/lib/Sema/SemaDeclCXX.cpp", 7727)
; 7728 7729 case DefaultedComparisonKind::Equal: 7730 case DefaultedComparisonKind::ThreeWay: 7731 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7732 return Results; 7733 7734 case DefaultedComparisonKind::NotEqual: 7735 case DefaultedComparisonKind::Relational: 7736 Results.add(getDerived().visitExpandedSubobject( 7737 ParamLvalType, getDerived().getCompleteObject())); 7738 return Results; 7739 } 7740 llvm_unreachable("")::llvm::llvm_unreachable_internal("", "clang/lib/Sema/SemaDeclCXX.cpp"
, 7740)
; 7741 } 7742 7743protected: 7744 Derived &getDerived() { return static_cast<Derived&>(*this); } 7745 7746 /// Visit the expanded list of subobjects of the given type, as specified in 7747 /// C++2a [class.compare.default]. 7748 /// 7749 /// \return \c true if the ResultList object said we're done, \c false if not. 7750 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7751 Qualifiers Quals) { 7752 // C++2a [class.compare.default]p4: 7753 // The direct base class subobjects of C 7754 for (CXXBaseSpecifier &Base : Record->bases()) 7755 if (Results.add(getDerived().visitSubobject( 7756 S.Context.getQualifiedType(Base.getType(), Quals), 7757 getDerived().getBase(&Base)))) 7758 return true; 7759 7760 // followed by the non-static data members of C 7761 for (FieldDecl *Field : Record->fields()) { 7762 // C++23 [class.bit]p2: 7763 // Unnamed bit-fields are not members ... 7764 if (Field->isUnnamedBitfield()) 7765 continue; 7766 // Recursively expand anonymous structs. 7767 if (Field->isAnonymousStructOrUnion()) { 7768 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7769 Quals)) 7770 return true; 7771 continue; 7772 } 7773 7774 // Figure out the type of an lvalue denoting this field. 7775 Qualifiers FieldQuals = Quals; 7776 if (Field->isMutable()) 7777 FieldQuals.removeConst(); 7778 QualType FieldType = 7779 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7780 7781 if (Results.add(getDerived().visitSubobject( 7782 FieldType, getDerived().getField(Field)))) 7783 return true; 7784 } 7785 7786 // form a list of subobjects. 7787 return false; 7788 } 7789 7790 Result visitSubobject(QualType Type, Subobject Subobj) { 7791 // In that list, any subobject of array type is recursively expanded 7792 const ArrayType *AT = S.Context.getAsArrayType(Type); 7793 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7794 return getDerived().visitSubobjectArray(CAT->getElementType(), 7795 CAT->getSize(), Subobj); 7796 return getDerived().visitExpandedSubobject(Type, Subobj); 7797 } 7798 7799 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7800 Subobject Subobj) { 7801 return getDerived().visitSubobject(Type, Subobj); 7802 } 7803 7804protected: 7805 Sema &S; 7806 CXXRecordDecl *RD; 7807 FunctionDecl *FD; 7808 DefaultedComparisonKind DCK; 7809 UnresolvedSet<16> Fns; 7810}; 7811 7812/// Information about a defaulted comparison, as determined by 7813/// DefaultedComparisonAnalyzer. 7814struct DefaultedComparisonInfo { 7815 bool Deleted = false; 7816 bool Constexpr = true; 7817 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7818 7819 static DefaultedComparisonInfo deleted() { 7820 DefaultedComparisonInfo Deleted; 7821 Deleted.Deleted = true; 7822 return Deleted; 7823 } 7824 7825 bool add(const DefaultedComparisonInfo &R) { 7826 Deleted |= R.Deleted; 7827 Constexpr &= R.Constexpr; 7828 Category = commonComparisonType(Category, R.Category); 7829 return Deleted; 7830 } 7831}; 7832 7833/// An element in the expanded list of subobjects of a defaulted comparison, as 7834/// specified in C++2a [class.compare.default]p4. 7835struct DefaultedComparisonSubobject { 7836 enum { CompleteObject, Member, Base } Kind; 7837 NamedDecl *Decl; 7838 SourceLocation Loc; 7839}; 7840 7841/// A visitor over the notional body of a defaulted comparison that determines 7842/// whether that body would be deleted or constexpr. 7843class DefaultedComparisonAnalyzer 7844 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7845 DefaultedComparisonInfo, 7846 DefaultedComparisonInfo, 7847 DefaultedComparisonSubobject> { 7848public: 7849 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7850 7851private: 7852 DiagnosticKind Diagnose; 7853 7854public: 7855 using Base = DefaultedComparisonVisitor; 7856 using Result = DefaultedComparisonInfo; 7857 using Subobject = DefaultedComparisonSubobject; 7858 7859 friend Base; 7860 7861 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7862 DefaultedComparisonKind DCK, 7863 DiagnosticKind Diagnose = NoDiagnostics) 7864 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7865 7866 Result visit() { 7867 if ((DCK == DefaultedComparisonKind::Equal || 7868 DCK == DefaultedComparisonKind::ThreeWay) && 7869 RD->hasVariantMembers()) { 7870 // C++2a [class.compare.default]p2 [P2002R0]: 7871 // A defaulted comparison operator function for class C is defined as 7872 // deleted if [...] C has variant members. 7873 if (Diagnose == ExplainDeleted) { 7874 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7875 << FD << RD->isUnion() << RD; 7876 } 7877 return Result::deleted(); 7878 } 7879 7880 return Base::visit(); 7881 } 7882 7883private: 7884 Subobject getCompleteObject() { 7885 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()}; 7886 } 7887 7888 Subobject getBase(CXXBaseSpecifier *Base) { 7889 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7890 Base->getBaseTypeLoc()}; 7891 } 7892 7893 Subobject getField(FieldDecl *Field) { 7894 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7895 } 7896 7897 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7898 // C++2a [class.compare.default]p2 [P2002R0]: 7899 // A defaulted <=> or == operator function for class C is defined as 7900 // deleted if any non-static data member of C is of reference type 7901 if (Type->isReferenceType()) { 7902 if (Diagnose == ExplainDeleted) { 7903 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7904 << FD << RD; 7905 } 7906 return Result::deleted(); 7907 } 7908 7909 // [...] Let xi be an lvalue denoting the ith element [...] 7910 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7911 Expr *Args[] = {&Xi, &Xi}; 7912 7913 // All operators start by trying to apply that same operator recursively. 7914 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7915 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", 7915, __extension__ __PRETTY_FUNCTION__
))
; 7916 return visitBinaryOperator(OO, Args, Subobj); 7917 } 7918 7919 Result 7920 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7921 Subobject Subobj, 7922 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7923 // Note that there is no need to consider rewritten candidates here if 7924 // we've already found there is no viable 'operator<=>' candidate (and are 7925 // considering synthesizing a '<=>' from '==' and '<'). 7926 OverloadCandidateSet CandidateSet( 7927 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7928 OverloadCandidateSet::OperatorRewriteInfo( 7929 OO, FD->getLocation(), 7930 /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7931 7932 /// C++2a [class.compare.default]p1 [P2002R0]: 7933 /// [...] the defaulted function itself is never a candidate for overload 7934 /// resolution [...] 7935 CandidateSet.exclude(FD); 7936 7937 if (Args[0]->getType()->isOverloadableType()) 7938 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7939 else 7940 // FIXME: We determine whether this is a valid expression by checking to 7941 // see if there's a viable builtin operator candidate for it. That isn't 7942 // really what the rules ask us to do, but should give the right results. 7943 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7944 7945 Result R; 7946 7947 OverloadCandidateSet::iterator Best; 7948 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7949 case OR_Success: { 7950 // C++2a [class.compare.secondary]p2 [P2002R0]: 7951 // The operator function [...] is defined as deleted if [...] the 7952 // candidate selected by overload resolution is not a rewritten 7953 // candidate. 7954 if ((DCK == DefaultedComparisonKind::NotEqual || 7955 DCK == DefaultedComparisonKind::Relational) && 7956 !Best->RewriteKind) { 7957 if (Diagnose == ExplainDeleted) { 7958 if (Best->Function) { 7959 S.Diag(Best->Function->getLocation(), 7960 diag::note_defaulted_comparison_not_rewritten_callee) 7961 << FD; 7962 } else { 7963 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", 7966, __extension__ __PRETTY_FUNCTION__
))
7964 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", 7966, __extension__ __PRETTY_FUNCTION__
))
7965 "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", 7966, __extension__ __PRETTY_FUNCTION__
))
7966 "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", 7966, __extension__ __PRETTY_FUNCTION__
))
; 7967 S.Diag(Best->Conversions[0] 7968 .UserDefined.FoundConversionFunction.getDecl() 7969 ->getLocation(), 7970 diag::note_defaulted_comparison_not_rewritten_conversion) 7971 << FD; 7972 } 7973 } 7974 return Result::deleted(); 7975 } 7976 7977 // Throughout C++2a [class.compare]: if overload resolution does not 7978 // result in a usable function, the candidate function is defined as 7979 // deleted. This requires that we selected an accessible function. 7980 // 7981 // Note that this only considers the access of the function when named 7982 // within the type of the subobject, and not the access path for any 7983 // derived-to-base conversion. 7984 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7985 if (ArgClass && Best->FoundDecl.getDecl() && 7986 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7987 QualType ObjectType = Subobj.Kind == Subobject::Member 7988 ? Args[0]->getType() 7989 : S.Context.getRecordType(RD); 7990 if (!S.isMemberAccessibleForDeletion( 7991 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7992 Diagnose == ExplainDeleted 7993 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7994 << FD << Subobj.Kind << Subobj.Decl 7995 : S.PDiag())) 7996 return Result::deleted(); 7997 } 7998 7999 bool NeedsDeducing = 8000 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType(); 8001 8002 if (FunctionDecl *BestFD = Best->Function) { 8003 // C++2a [class.compare.default]p3 [P2002R0]: 8004 // A defaulted comparison function is constexpr-compatible if 8005 // [...] no overlod resolution performed [...] results in a 8006 // non-constexpr function. 8007 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", 8007, __extension__ __PRETTY_FUNCTION__
))
; 8008 // If it's not constexpr, explain why not. 8009 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 8010 if (Subobj.Kind != Subobject::CompleteObject) 8011 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 8012 << Subobj.Kind << Subobj.Decl; 8013 S.Diag(BestFD->getLocation(), 8014 diag::note_defaulted_comparison_not_constexpr_here); 8015 // Bail out after explaining; we don't want any more notes. 8016 return Result::deleted(); 8017 } 8018 R.Constexpr &= BestFD->isConstexpr(); 8019 8020 if (NeedsDeducing) { 8021 // If any callee has an undeduced return type, deduce it now. 8022 // FIXME: It's not clear how a failure here should be handled. For 8023 // now, we produce an eager diagnostic, because that is forward 8024 // compatible with most (all?) other reasonable options. 8025 if (BestFD->getReturnType()->isUndeducedType() && 8026 S.DeduceReturnType(BestFD, FD->getLocation(), 8027 /*Diagnose=*/false)) { 8028 // Don't produce a duplicate error when asked to explain why the 8029 // comparison is deleted: we diagnosed that when initially checking 8030 // the defaulted operator. 8031 if (Diagnose == NoDiagnostics) { 8032 S.Diag( 8033 FD->getLocation(), 8034 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 8035 << Subobj.Kind << Subobj.Decl; 8036 S.Diag( 8037 Subobj.Loc, 8038 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 8039 << Subobj.Kind << Subobj.Decl; 8040 S.Diag(BestFD->getLocation(), 8041 diag::note_defaulted_comparison_cannot_deduce_callee) 8042 << Subobj.Kind << Subobj.Decl; 8043 } 8044 return Result::deleted(); 8045 } 8046 auto *Info = S.Context.CompCategories.lookupInfoForType( 8047 BestFD->getCallResultType()); 8048 if (!Info) { 8049 if (Diagnose == ExplainDeleted) { 8050 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 8051 << Subobj.Kind << Subobj.Decl 8052 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 8053 S.Diag(BestFD->getLocation(), 8054 diag::note_defaulted_comparison_cannot_deduce_callee) 8055 << Subobj.Kind << Subobj.Decl; 8056 } 8057 return Result::deleted(); 8058 } 8059 R.Category = Info->Kind; 8060 } 8061 } else { 8062 QualType T = Best->BuiltinParamTypes[0]; 8063 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", 8064, __extension__ __PRETTY_FUNCTION__
))
8064 "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", 8064, __extension__ __PRETTY_FUNCTION__
))
; 8065 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", 8066, __extension__ __PRETTY_FUNCTION__
))
8066 "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", 8066, __extension__ __PRETTY_FUNCTION__
))
; 8067 8068 if (NeedsDeducing) { 8069 std::optional<ComparisonCategoryType> Cat = 8070 getComparisonCategoryForBuiltinCmp(T); 8071 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", 8071, __extension__ __PRETTY_FUNCTION__
))
; 8072 R.Category = *Cat; 8073 } 8074 } 8075 8076 // Note that we might be rewriting to a different operator. That call is 8077 // not considered until we come to actually build the comparison function. 8078 break; 8079 } 8080 8081 case OR_Ambiguous: 8082 if (Diagnose == ExplainDeleted) { 8083 unsigned Kind = 0; 8084 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 8085 Kind = OO == OO_EqualEqual ? 1 : 2; 8086 CandidateSet.NoteCandidates( 8087 PartialDiagnosticAt( 8088 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 8089 << FD << Kind << Subobj.Kind << Subobj.Decl), 8090 S, OCD_AmbiguousCandidates, Args); 8091 } 8092 R = Result::deleted(); 8093 break; 8094 8095 case OR_Deleted: 8096 if (Diagnose == ExplainDeleted) { 8097 if ((DCK == DefaultedComparisonKind::NotEqual || 8098 DCK == DefaultedComparisonKind::Relational) && 8099 !Best->RewriteKind) { 8100 S.Diag(Best->Function->getLocation(), 8101 diag::note_defaulted_comparison_not_rewritten_callee) 8102 << FD; 8103 } else { 8104 S.Diag(Subobj.Loc, 8105 diag::note_defaulted_comparison_calls_deleted) 8106 << FD << Subobj.Kind << Subobj.Decl; 8107 S.NoteDeletedFunction(Best->Function); 8108 } 8109 } 8110 R = Result::deleted(); 8111 break; 8112 8113 case OR_No_Viable_Function: 8114 // If there's no usable candidate, we're done unless we can rewrite a 8115 // '<=>' in terms of '==' and '<'. 8116 if (OO == OO_Spaceship && 8117 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 8118 // For any kind of comparison category return type, we need a usable 8119 // '==' and a usable '<'. 8120 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 8121 &CandidateSet))) 8122 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 8123 break; 8124 } 8125 8126 if (Diagnose == ExplainDeleted) { 8127 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 8128 << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl; 8129 8130 // For a three-way comparison, list both the candidates for the 8131 // original operator and the candidates for the synthesized operator. 8132 if (SpaceshipCandidates) { 8133 SpaceshipCandidates->NoteCandidates( 8134 S, Args, 8135 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 8136 Args, FD->getLocation())); 8137 S.Diag(Subobj.Loc, 8138 diag::note_defaulted_comparison_no_viable_function_synthesized) 8139 << (OO == OO_EqualEqual ? 0 : 1); 8140 } 8141 8142 CandidateSet.NoteCandidates( 8143 S, Args, 8144 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 8145 FD->getLocation())); 8146 } 8147 R = Result::deleted(); 8148 break; 8149 } 8150 8151 return R; 8152 } 8153}; 8154 8155/// A list of statements. 8156struct StmtListResult { 8157 bool IsInvalid = false; 8158 llvm::SmallVector<Stmt*, 16> Stmts; 8159 8160 bool add(const StmtResult &S) { 8161 IsInvalid |= S.isInvalid(); 8162 if (IsInvalid) 8163 return true; 8164 Stmts.push_back(S.get()); 8165 return false; 8166 } 8167}; 8168 8169/// A visitor over the notional body of a defaulted comparison that synthesizes 8170/// the actual body. 8171class DefaultedComparisonSynthesizer 8172 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 8173 StmtListResult, StmtResult, 8174 std::pair<ExprResult, ExprResult>> { 8175 SourceLocation Loc; 8176 unsigned ArrayDepth = 0; 8177 8178public: 8179 using Base = DefaultedComparisonVisitor; 8180 using ExprPair = std::pair<ExprResult, ExprResult>; 8181 8182 friend Base; 8183 8184 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 8185 DefaultedComparisonKind DCK, 8186 SourceLocation BodyLoc) 8187 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 8188 8189 /// Build a suitable function body for this defaulted comparison operator. 8190 StmtResult build() { 8191 Sema::CompoundScopeRAII CompoundScope(S); 8192 8193 StmtListResult Stmts = visit(); 8194 if (Stmts.IsInvalid) 8195 return StmtError(); 8196 8197 ExprResult RetVal; 8198 switch (DCK) { 8199 case DefaultedComparisonKind::None: 8200 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8200)
; 8201 8202 case DefaultedComparisonKind::Equal: { 8203 // C++2a [class.eq]p3: 8204 // [...] compar[e] the corresponding elements [...] until the first 8205 // index i where xi == yi yields [...] false. If no such index exists, 8206 // V is true. Otherwise, V is false. 8207 // 8208 // Join the comparisons with '&&'s and return the result. Use a right 8209 // fold (traversing the conditions right-to-left), because that 8210 // short-circuits more naturally. 8211 auto OldStmts = std::move(Stmts.Stmts); 8212 Stmts.Stmts.clear(); 8213 ExprResult CmpSoFar; 8214 // Finish a particular comparison chain. 8215 auto FinishCmp = [&] { 8216 if (Expr *Prior = CmpSoFar.get()) { 8217 // Convert the last expression to 'return ...;' 8218 if (RetVal.isUnset() && Stmts.Stmts.empty()) 8219 RetVal = CmpSoFar; 8220 // Convert any prior comparison to 'if (!(...)) return false;' 8221 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 8222 return true; 8223 CmpSoFar = ExprResult(); 8224 } 8225 return false; 8226 }; 8227 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 8228 Expr *E = dyn_cast<Expr>(EAsStmt); 8229 if (!E) { 8230 // Found an array comparison. 8231 if (FinishCmp() || Stmts.add(EAsStmt)) 8232 return StmtError(); 8233 continue; 8234 } 8235 8236 if (CmpSoFar.isUnset()) { 8237 CmpSoFar = E; 8238 continue; 8239 } 8240 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 8241 if (CmpSoFar.isInvalid()) 8242 return StmtError(); 8243 } 8244 if (FinishCmp()) 8245 return StmtError(); 8246 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 8247 // If no such index exists, V is true. 8248 if (RetVal.isUnset()) 8249 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 8250 break; 8251 } 8252 8253 case DefaultedComparisonKind::ThreeWay: { 8254 // Per C++2a [class.spaceship]p3, as a fallback add: 8255 // return static_cast<R>(std::strong_ordering::equal); 8256 QualType StrongOrdering = S.CheckComparisonCategoryType( 8257 ComparisonCategoryType::StrongOrdering, Loc, 8258 Sema::ComparisonCategoryUsage::DefaultedOperator); 8259 if (StrongOrdering.isNull()) 8260 return StmtError(); 8261 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 8262 .getValueInfo(ComparisonCategoryResult::Equal) 8263 ->VD; 8264 RetVal = getDecl(EqualVD); 8265 if (RetVal.isInvalid()) 8266 return StmtError(); 8267 RetVal = buildStaticCastToR(RetVal.get()); 8268 break; 8269 } 8270 8271 case DefaultedComparisonKind::NotEqual: 8272 case DefaultedComparisonKind::Relational: 8273 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 8274 break; 8275 } 8276 8277 // Build the final return statement. 8278 if (RetVal.isInvalid()) 8279 return StmtError(); 8280 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 8281 if (ReturnStmt.isInvalid()) 8282 return StmtError(); 8283 Stmts.Stmts.push_back(ReturnStmt.get()); 8284 8285 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 8286 } 8287 8288private: 8289 ExprResult getDecl(ValueDecl *VD) { 8290 return S.BuildDeclarationNameExpr( 8291 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8292 } 8293 8294 ExprResult getParam(unsigned I) { 8295 ParmVarDecl *PD = FD->getParamDecl(I); 8296 return getDecl(PD); 8297 } 8298 8299 ExprPair getCompleteObject() { 8300 unsigned Param = 0; 8301 ExprResult LHS; 8302 if (isa<CXXMethodDecl>(FD)) { 8303 // LHS is '*this'. 8304 LHS = S.ActOnCXXThis(Loc); 8305 if (!LHS.isInvalid()) 8306 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 8307 } else { 8308 LHS = getParam(Param++); 8309 } 8310 ExprResult RHS = getParam(Param++); 8311 assert(Param == FD->getNumParams())(static_cast <bool> (Param == FD->getNumParams()) ? void
(0) : __assert_fail ("Param == FD->getNumParams()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 8311, __extension__ __PRETTY_FUNCTION__))
; 8312 return {LHS, RHS}; 8313 } 8314 8315 ExprPair getBase(CXXBaseSpecifier *Base) { 8316 ExprPair Obj = getCompleteObject(); 8317 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8318 return {ExprError(), ExprError()}; 8319 CXXCastPath Path = {Base}; 8320 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 8321 CK_DerivedToBase, VK_LValue, &Path), 8322 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 8323 CK_DerivedToBase, VK_LValue, &Path)}; 8324 } 8325 8326 ExprPair getField(FieldDecl *Field) { 8327 ExprPair Obj = getCompleteObject(); 8328 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8329 return {ExprError(), ExprError()}; 8330 8331 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8332 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8333 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8334 CXXScopeSpec(), Field, Found, NameInfo), 8335 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8336 CXXScopeSpec(), Field, Found, NameInfo)}; 8337 } 8338 8339 // FIXME: When expanding a subobject, register a note in the code synthesis 8340 // stack to say which subobject we're comparing. 8341 8342 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8343 if (Cond.isInvalid()) 8344 return StmtError(); 8345 8346 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8347 if (NotCond.isInvalid()) 8348 return StmtError(); 8349 8350 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8351 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", 8351, __extension__ __PRETTY_FUNCTION__
))
; 8352 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8353 if (ReturnFalse.isInvalid()) 8354 return StmtError(); 8355 8356 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr, 8357 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8358 Sema::ConditionKind::Boolean), 8359 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8360 } 8361 8362 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8363 ExprPair Subobj) { 8364 QualType SizeType = S.Context.getSizeType(); 8365 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8366 8367 // Build 'size_t i$n = 0'. 8368 IdentifierInfo *IterationVarName = nullptr; 8369 { 8370 SmallString<8> Str; 8371 llvm::raw_svector_ostream OS(Str); 8372 OS << "i" << ArrayDepth; 8373 IterationVarName = &S.Context.Idents.get(OS.str()); 8374 } 8375 VarDecl *IterationVar = VarDecl::Create( 8376 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8377 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8378 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8379 IterationVar->setInit( 8380 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8381 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8382 8383 auto IterRef = [&] { 8384 ExprResult Ref = S.BuildDeclarationNameExpr( 8385 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8386 IterationVar); 8387 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", 8387, __extension__ __PRETTY_FUNCTION__
))
; 8388 return Ref.get(); 8389 }; 8390 8391 // Build 'i$n != Size'. 8392 ExprResult Cond = S.CreateBuiltinBinOp( 8393 Loc, BO_NE, IterRef(), 8394 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8395 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", 8395, __extension__ __PRETTY_FUNCTION__
))
; 8396 8397 // Build '++i$n'. 8398 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8399 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", 8399, __extension__ __PRETTY_FUNCTION__
))
; 8400 8401 // Build 'a[i$n]' and 'b[i$n]'. 8402 auto Index = [&](ExprResult E) { 8403 if (E.isInvalid()) 8404 return ExprError(); 8405 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8406 }; 8407 Subobj.first = Index(Subobj.first); 8408 Subobj.second = Index(Subobj.second); 8409 8410 // Compare the array elements. 8411 ++ArrayDepth; 8412 StmtResult Substmt = visitSubobject(Type, Subobj); 8413 --ArrayDepth; 8414 8415 if (Substmt.isInvalid()) 8416 return StmtError(); 8417 8418 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8419 // For outer levels or for an 'operator<=>' we already have a suitable 8420 // statement that returns as necessary. 8421 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8422 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", 8423, __extension__ __PRETTY_FUNCTION__
))
8423 "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", 8423, __extension__ __PRETTY_FUNCTION__
))
; 8424 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8425 if (Substmt.isInvalid()) 8426 return StmtError(); 8427 } 8428 8429 // Build 'for (...) ...' 8430 return S.ActOnForStmt(Loc, Loc, Init, 8431 S.ActOnCondition(nullptr, Loc, Cond.get(), 8432 Sema::ConditionKind::Boolean), 8433 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8434 Substmt.get()); 8435 } 8436 8437 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8438 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8439 return StmtError(); 8440 8441 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8442 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8443 ExprResult Op; 8444 if (Type->isOverloadableType()) 8445 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8446 Obj.second.get(), /*PerformADL=*/true, 8447 /*AllowRewrittenCandidates=*/true, FD); 8448 else 8449 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8450 if (Op.isInvalid()) 8451 return StmtError(); 8452 8453 switch (DCK) { 8454 case DefaultedComparisonKind::None: 8455 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8455)
; 8456 8457 case DefaultedComparisonKind::Equal: 8458 // Per C++2a [class.eq]p2, each comparison is individually contextually 8459 // converted to bool. 8460 Op = S.PerformContextuallyConvertToBool(Op.get()); 8461 if (Op.isInvalid()) 8462 return StmtError(); 8463 return Op.get(); 8464 8465 case DefaultedComparisonKind::ThreeWay: { 8466 // Per C++2a [class.spaceship]p3, form: 8467 // if (R cmp = static_cast<R>(op); cmp != 0) 8468 // return cmp; 8469 QualType R = FD->getReturnType(); 8470 Op = buildStaticCastToR(Op.get()); 8471 if (Op.isInvalid()) 8472 return StmtError(); 8473 8474 // R cmp = ...; 8475 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8476 VarDecl *VD = 8477 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8478 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8479 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8480 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8481 8482 // cmp != 0 8483 ExprResult VDRef = getDecl(VD); 8484 if (VDRef.isInvalid()) 8485 return StmtError(); 8486 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8487 Expr *Zero = 8488 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8489 ExprResult Comp; 8490 if (VDRef.get()->getType()->isOverloadableType()) 8491 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8492 true, FD); 8493 else 8494 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8495 if (Comp.isInvalid()) 8496 return StmtError(); 8497 Sema::ConditionResult Cond = S.ActOnCondition( 8498 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8499 if (Cond.isInvalid()) 8500 return StmtError(); 8501 8502 // return cmp; 8503 VDRef = getDecl(VD); 8504 if (VDRef.isInvalid()) 8505 return StmtError(); 8506 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8507 if (ReturnStmt.isInvalid()) 8508 return StmtError(); 8509 8510 // if (...) 8511 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond, 8512 Loc, ReturnStmt.get(), 8513 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8514 } 8515 8516 case DefaultedComparisonKind::NotEqual: 8517 case DefaultedComparisonKind::Relational: 8518 // C++2a [class.compare.secondary]p2: 8519 // Otherwise, the operator function yields x @ y. 8520 return Op.get(); 8521 } 8522 llvm_unreachable("")::llvm::llvm_unreachable_internal("", "clang/lib/Sema/SemaDeclCXX.cpp"
, 8522)
; 8523 } 8524 8525 /// Build "static_cast<R>(E)". 8526 ExprResult buildStaticCastToR(Expr *E) { 8527 QualType R = FD->getReturnType(); 8528 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", 8528, __extension__ __PRETTY_FUNCTION__
))
; 8529 8530 // Don't bother forming a no-op cast in the common case. 8531 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R)) 8532 return E; 8533 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8534 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8535 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8536 } 8537}; 8538} 8539 8540/// Perform the unqualified lookups that might be needed to form a defaulted 8541/// comparison function for the given operator. 8542static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8543 UnresolvedSetImpl &Operators, 8544 OverloadedOperatorKind Op) { 8545 auto Lookup = [&](OverloadedOperatorKind OO) { 8546 Self.LookupOverloadedOperatorName(OO, S, Operators); 8547 }; 8548 8549 // Every defaulted operator looks up itself. 8550 Lookup(Op); 8551 // ... and the rewritten form of itself, if any. 8552 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8553 Lookup(ExtraOp); 8554 8555 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8556 // synthesize a three-way comparison from '<' and '=='. In a dependent 8557 // context, we also need to look up '==' in case we implicitly declare a 8558 // defaulted 'operator=='. 8559 if (Op == OO_Spaceship) { 8560 Lookup(OO_ExclaimEqual); 8561 Lookup(OO_Less); 8562 Lookup(OO_EqualEqual); 8563 } 8564} 8565 8566bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8567 DefaultedComparisonKind DCK) { 8568 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", 8568, __extension__ __PRETTY_FUNCTION__
))
; 8569 8570 // Perform any unqualified lookups we're going to need to default this 8571 // function. 8572 if (S) { 8573 UnresolvedSet<32> Operators; 8574 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8575 FD->getOverloadedOperator()); 8576 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8577 Context, Operators.pairs())); 8578 } 8579 8580 // C++2a [class.compare.default]p1: 8581 // A defaulted comparison operator function for some class C shall be a 8582 // non-template function declared in the member-specification of C that is 8583 // -- a non-static const member of C having one parameter of type 8584 // const C&, or 8585 // -- a friend of C having two parameters of type const C& or two 8586 // parameters of type C. 8587 8588 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8589 bool IsMethod = isa<CXXMethodDecl>(FD); 8590 if (IsMethod) { 8591 auto *MD = cast<CXXMethodDecl>(FD); 8592 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", 8592, __extension__ __PRETTY_FUNCTION__
))
; 8593 8594 // If we're out-of-class, this is the class we're comparing. 8595 if (!RD) 8596 RD = MD->getParent(); 8597 8598 if (!MD->isConst()) { 8599 SourceLocation InsertLoc; 8600 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8601 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8602 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8603 // corresponding defaulted 'operator<=>' already. 8604 if (!MD->isImplicit()) { 8605 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8606 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8607 } 8608 8609 // Add the 'const' to the type to recover. 8610 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8611 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8612 EPI.TypeQuals.addConst(); 8613 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8614 FPT->getParamTypes(), EPI)); 8615 } 8616 } 8617 8618 if (FD->getNumParams() != (IsMethod ? 1 : 2)) { 8619 // Let's not worry about using a variadic template pack here -- who would do 8620 // such a thing? 8621 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args) 8622 << int(IsMethod) << int(DCK); 8623 return true; 8624 } 8625 8626 const ParmVarDecl *KnownParm = nullptr; 8627 for (const ParmVarDecl *Param : FD->parameters()) { 8628 QualType ParmTy = Param->getType(); 8629 if (ParmTy->isDependentType()) 8630 continue; 8631 if (!KnownParm) { 8632 auto CTy = ParmTy; 8633 // Is it `T const &`? 8634 bool Ok = !IsMethod; 8635 QualType ExpectedTy; 8636 if (RD) 8637 ExpectedTy = Context.getRecordType(RD); 8638 if (auto *Ref = CTy->getAs<ReferenceType>()) { 8639 CTy = Ref->getPointeeType(); 8640 if (RD) 8641 ExpectedTy.addConst(); 8642 Ok = true; 8643 } 8644 8645 // Is T a class? 8646 if (!Ok) { 8647 } else if (RD) { 8648 if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy)) 8649 Ok = false; 8650 } else if (auto *CRD = CTy->getAsRecordDecl()) { 8651 RD = cast<CXXRecordDecl>(CRD); 8652 } else { 8653 Ok = false; 8654 } 8655 8656 if (Ok) { 8657 KnownParm = Param; 8658 } else { 8659 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8660 // corresponding defaulted 'operator<=>' already. 8661 if (!FD->isImplicit()) { 8662 if (RD) { 8663 QualType PlainTy = Context.getRecordType(RD); 8664 QualType RefTy = 8665 Context.getLValueReferenceType(PlainTy.withConst()); 8666 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8667 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy 8668 << Param->getSourceRange(); 8669 } else { 8670 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", 8670, __extension__ __PRETTY_FUNCTION__
))
; 8671 Diag(FD->getLocation(), 8672 diag::err_defaulted_comparison_param_unknown) 8673 << int(DCK) << ParmTy << Param->getSourceRange(); 8674 } 8675 } 8676 return true; 8677 } 8678 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) { 8679 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8680 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange() 8681 << ParmTy << Param->getSourceRange(); 8682 return true; 8683 } 8684 } 8685 8686 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", 8686, __extension__ __PRETTY_FUNCTION__
))
; 8687 if (IsMethod) { 8688 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 8689 // In-class, must be a friend decl. 8690 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", 8690, __extension__ __PRETTY_FUNCTION__
))
; 8691 } else { 8692 // Out of class, require the defaulted comparison to be a friend (of a 8693 // complete type). 8694 if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD), 8695 diag::err_defaulted_comparison_not_friend, int(DCK), 8696 int(1))) 8697 return true; 8698 8699 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) { 8700 return FD->getCanonicalDecl() == 8701 F->getFriendDecl()->getCanonicalDecl(); 8702 })) { 8703 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend) 8704 << int(DCK) << int(0) << RD; 8705 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at); 8706 return true; 8707 } 8708 } 8709 8710 // C++2a [class.eq]p1, [class.rel]p1: 8711 // A [defaulted comparison other than <=>] shall have a declared return 8712 // type bool. 8713 if (DCK != DefaultedComparisonKind::ThreeWay && 8714 !FD->getDeclaredReturnType()->isDependentType() && 8715 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8716 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8717 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8718 << FD->getReturnTypeSourceRange(); 8719 return true; 8720 } 8721 // C++2a [class.spaceship]p2 [P2002R0]: 8722 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8723 // R shall not contain a placeholder type. 8724 if (QualType RT = FD->getDeclaredReturnType(); 8725 DCK == DefaultedComparisonKind::ThreeWay && 8726 RT->getContainedDeducedType() && 8727 (!Context.hasSameType(RT, Context.getAutoDeductType()) || 8728 RT->getContainedAutoType()->isConstrained())) { 8729 Diag(FD->getLocation(), 8730 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8731 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8732 << FD->getReturnTypeSourceRange(); 8733 return true; 8734 } 8735 8736 // For a defaulted function in a dependent class, defer all remaining checks 8737 // until instantiation. 8738 if (RD->isDependentType()) 8739 return false; 8740 8741 // Determine whether the function should be defined as deleted. 8742 DefaultedComparisonInfo Info = 8743 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8744 8745 bool First = FD == FD->getCanonicalDecl(); 8746 8747 if (!First) { 8748 if (Info.Deleted) { 8749 // C++11 [dcl.fct.def.default]p4: 8750 // [For a] user-provided explicitly-defaulted function [...] if such a 8751 // function is implicitly defined as deleted, the program is ill-formed. 8752 // 8753 // This is really just a consequence of the general rule that you can 8754 // only delete a function on its first declaration. 8755 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8756 << FD->isImplicit() << (int)DCK; 8757 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8758 DefaultedComparisonAnalyzer::ExplainDeleted) 8759 .visit(); 8760 return true; 8761 } 8762 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 8763 // C++20 [class.compare.default]p1: 8764 // [...] A definition of a comparison operator as defaulted that appears 8765 // in a class shall be the first declaration of that function. 8766 Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class) 8767 << (int)DCK; 8768 Diag(FD->getCanonicalDecl()->getLocation(), 8769 diag::note_previous_declaration); 8770 return true; 8771 } 8772 } 8773 8774 // If we want to delete the function, then do so; there's nothing else to 8775 // check in that case. 8776 if (Info.Deleted) { 8777 SetDeclDeleted(FD, FD->getLocation()); 8778 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8779 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8780 << (int)DCK; 8781 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8782 DefaultedComparisonAnalyzer::ExplainDeleted) 8783 .visit(); 8784 if (FD->getDefaultLoc().isValid()) 8785 Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete) 8786 << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete"); 8787 } 8788 return false; 8789 } 8790 8791 // C++2a [class.spaceship]p2: 8792 // The return type is deduced as the common comparison type of R0, R1, ... 8793 if (DCK == DefaultedComparisonKind::ThreeWay && 8794 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8795 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8796 if (RetLoc.isInvalid()) 8797 RetLoc = FD->getBeginLoc(); 8798 // FIXME: Should we really care whether we have the complete type and the 8799 // 'enumerator' constants here? A forward declaration seems sufficient. 8800 QualType Cat = CheckComparisonCategoryType( 8801 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8802 if (Cat.isNull()) 8803 return true; 8804 Context.adjustDeducedFunctionResultType( 8805 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8806 } 8807 8808 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8809 // An explicitly-defaulted function that is not defined as deleted may be 8810 // declared constexpr or consteval only if it is constexpr-compatible. 8811 // C++2a [class.compare.default]p3 [P2002R0]: 8812 // A defaulted comparison function is constexpr-compatible if it satisfies 8813 // the requirements for a constexpr function [...] 8814 // The only relevant requirements are that the parameter and return types are 8815 // literal types. The remaining conditions are checked by the analyzer. 8816 // 8817 // We support P2448R2 in language modes earlier than C++23 as an extension. 8818 // The concept of constexpr-compatible was removed. 8819 // C++23 [dcl.fct.def.default]p3 [P2448R2] 8820 // A function explicitly defaulted on its first declaration is implicitly 8821 // inline, and is implicitly constexpr if it is constexpr-suitable. 8822 // C++23 [dcl.constexpr]p3 8823 // A function is constexpr-suitable if 8824 // - it is not a coroutine, and 8825 // - if the function is a constructor or destructor, its class does not 8826 // have any virtual base classes. 8827 if (FD->isConstexpr()) { 8828 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8829 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8830 !Info.Constexpr) { 8831 Diag(FD->getBeginLoc(), 8832 getLangOpts().CPlusPlus23 8833 ? diag::warn_cxx23_compat_defaulted_comparison_constexpr_mismatch 8834 : diag::ext_defaulted_comparison_constexpr_mismatch) 8835 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8836 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8837 DefaultedComparisonAnalyzer::ExplainConstexpr) 8838 .visit(); 8839 } 8840 } 8841 8842 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8843 // If a constexpr-compatible function is explicitly defaulted on its first 8844 // declaration, it is implicitly considered to be constexpr. 8845 // FIXME: Only applying this to the first declaration seems problematic, as 8846 // simple reorderings can affect the meaning of the program. 8847 if (First && !FD->isConstexpr() && Info.Constexpr) 8848 FD->setConstexprKind(ConstexprSpecKind::Constexpr); 8849 8850 // C++2a [except.spec]p3: 8851 // If a declaration of a function does not have a noexcept-specifier 8852 // [and] is defaulted on its first declaration, [...] the exception 8853 // specification is as specified below 8854 if (FD->getExceptionSpecType() == EST_None) { 8855 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8856 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8857 EPI.ExceptionSpec.Type = EST_Unevaluated; 8858 EPI.ExceptionSpec.SourceDecl = FD; 8859 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8860 FPT->getParamTypes(), EPI)); 8861 } 8862 8863 return false; 8864} 8865 8866void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8867 FunctionDecl *Spaceship) { 8868 Sema::CodeSynthesisContext Ctx; 8869 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8870 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8871 Ctx.Entity = Spaceship; 8872 pushCodeSynthesisContext(Ctx); 8873 8874 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8875 EqualEqual->setImplicit(); 8876 8877 popCodeSynthesisContext(); 8878} 8879 8880void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8881 DefaultedComparisonKind DCK) { 8882 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", 8883, __extension__ __PRETTY_FUNCTION__
))
8883 !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", 8883, __extension__ __PRETTY_FUNCTION__
))
; 8884 if (FD->willHaveBody() || FD->isInvalidDecl()) 8885 return; 8886 8887 SynthesizedFunctionScope Scope(*this, FD); 8888 8889 // Add a context note for diagnostics produced after this point. 8890 Scope.addContextNote(UseLoc); 8891 8892 { 8893 // Build and set up the function body. 8894 // The first parameter has type maybe-ref-to maybe-const T, use that to get 8895 // the type of the class being compared. 8896 auto PT = FD->getParamDecl(0)->getType(); 8897 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl(); 8898 SourceLocation BodyLoc = 8899 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8900 StmtResult Body = 8901 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8902 if (Body.isInvalid()) { 8903 FD->setInvalidDecl(); 8904 return; 8905 } 8906 FD->setBody(Body.get()); 8907 FD->markUsed(Context); 8908 } 8909 8910 // The exception specification is needed because we are defining the 8911 // function. Note that this will reuse the body we just built. 8912 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8913 8914 if (ASTMutationListener *L = getASTMutationListener()) 8915 L->CompletedImplicitDefinition(FD); 8916} 8917 8918static Sema::ImplicitExceptionSpecification 8919ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8920 FunctionDecl *FD, 8921 Sema::DefaultedComparisonKind DCK) { 8922 ComputingExceptionSpec CES(S, FD, Loc); 8923 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8924 8925 if (FD->isInvalidDecl()) 8926 return ExceptSpec; 8927 8928 // The common case is that we just defined the comparison function. In that 8929 // case, just look at whether the body can throw. 8930 if (FD->hasBody()) { 8931 ExceptSpec.CalledStmt(FD->getBody()); 8932 } else { 8933 // Otherwise, build a body so we can check it. This should ideally only 8934 // happen when we're not actually marking the function referenced. (This is 8935 // only really important for efficiency: we don't want to build and throw 8936 // away bodies for comparison functions more than we strictly need to.) 8937 8938 // Pretend to synthesize the function body in an unevaluated context. 8939 // Note that we can't actually just go ahead and define the function here: 8940 // we are not permitted to mark its callees as referenced. 8941 Sema::SynthesizedFunctionScope Scope(S, FD); 8942 EnterExpressionEvaluationContext Context( 8943 S, Sema::ExpressionEvaluationContext::Unevaluated); 8944 8945 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8946 SourceLocation BodyLoc = 8947 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8948 StmtResult Body = 8949 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8950 if (!Body.isInvalid()) 8951 ExceptSpec.CalledStmt(Body.get()); 8952 8953 // FIXME: Can we hold onto this body and just transform it to potentially 8954 // evaluated when we're asked to define the function rather than rebuilding 8955 // it? Either that, or we should only build the bits of the body that we 8956 // need (the expressions, not the statements). 8957 } 8958 8959 return ExceptSpec; 8960} 8961 8962void Sema::CheckDelayedMemberExceptionSpecs() { 8963 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8964 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8965 8966 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8967 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8968 8969 // Perform any deferred checking of exception specifications for virtual 8970 // destructors. 8971 for (auto &Check : Overriding) 8972 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8973 8974 // Perform any deferred checking of exception specifications for befriended 8975 // special members. 8976 for (auto &Check : Equivalent) 8977 CheckEquivalentExceptionSpec(Check.second, Check.first); 8978} 8979 8980namespace { 8981/// CRTP base class for visiting operations performed by a special member 8982/// function (or inherited constructor). 8983template<typename Derived> 8984struct SpecialMemberVisitor { 8985 Sema &S; 8986 CXXMethodDecl *MD; 8987 Sema::CXXSpecialMember CSM; 8988 Sema::InheritedConstructorInfo *ICI; 8989 8990 // Properties of the special member, computed for convenience. 8991 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8992 8993 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8994 Sema::InheritedConstructorInfo *ICI) 8995 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8996 switch (CSM) { 8997 case Sema::CXXDefaultConstructor: 8998 case Sema::CXXCopyConstructor: 8999 case Sema::CXXMoveConstructor: 9000 IsConstructor = true; 9001 break; 9002 case Sema::CXXCopyAssignment: 9003 case Sema::CXXMoveAssignment: 9004 IsAssignment = true; 9005 break; 9006 case Sema::CXXDestructor: 9007 break; 9008 case Sema::CXXInvalid: 9009 llvm_unreachable("invalid special member kind")::llvm::llvm_unreachable_internal("invalid special member kind"
, "clang/lib/Sema/SemaDeclCXX.cpp", 9009)
; 9010 } 9011 9012 if (MD->getNumParams()) { 9013 if (const ReferenceType *RT = 9014 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 9015 ConstArg = RT->getPointeeType().isConstQualified(); 9016 } 9017 } 9018 9019 Derived &getDerived() { return static_cast<Derived&>(*this); } 9020 9021 /// Is this a "move" special member? 9022 bool isMove() const { 9023 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 9024 } 9025 9026 /// Look up the corresponding special member in the given class. 9027 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 9028 unsigned Quals, bool IsMutable) { 9029 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 9030 ConstArg && !IsMutable); 9031 } 9032 9033 /// Look up the constructor for the specified base class to see if it's 9034 /// overridden due to this being an inherited constructor. 9035 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 9036 if (!ICI) 9037 return {}; 9038 assert(CSM == Sema::CXXDefaultConstructor)(static_cast <bool> (CSM == Sema::CXXDefaultConstructor
) ? void (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor"
, "clang/lib/Sema/SemaDeclCXX.cpp", 9038, __extension__ __PRETTY_FUNCTION__
))
; 9039 auto *BaseCtor = 9040 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 9041 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 9042 return MD; 9043 return {}; 9044 } 9045 9046 /// A base or member subobject. 9047 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 9048 9049 /// Get the location to use for a subobject in diagnostics. 9050 static SourceLocation getSubobjectLoc(Subobject Subobj) { 9051 // FIXME: For an indirect virtual base, the direct base leading to 9052 // the indirect virtual base would be a more useful choice. 9053 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 9054 return B->getBaseTypeLoc(); 9055 else 9056 return Subobj.get<FieldDecl*>()->getLocation(); 9057 } 9058 9059 enum BasesToVisit { 9060 /// Visit all non-virtual (direct) bases. 9061 VisitNonVirtualBases, 9062 /// Visit all direct bases, virtual or not. 9063 VisitDirectBases, 9064 /// Visit all non-virtual bases, and all virtual bases if the class 9065 /// is not abstract. 9066 VisitPotentiallyConstructedBases, 9067 /// Visit all direct or virtual bases. 9068 VisitAllBases 9069 }; 9070 9071 // Visit the bases and members of the class. 9072 bool visit(BasesToVisit Bases) { 9073 CXXRecordDecl *RD = MD->getParent(); 9074 9075 if (Bases == VisitPotentiallyConstructedBases) 9076 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 9077 9078 for (auto &B : RD->bases()) 9079 if ((Bases == VisitDirectBases || !B.isVirtual()) && 9080 getDerived().visitBase(&B)) 9081 return true; 9082 9083 if (Bases == VisitAllBases) 9084 for (auto &B : RD->vbases()) 9085 if (getDerived().visitBase(&B)) 9086 return true; 9087 9088 for (auto *F : RD->fields()) 9089 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 9090 getDerived().visitField(F)) 9091 return true; 9092 9093 return false; 9094 } 9095}; 9096} 9097 9098namespace { 9099struct SpecialMemberDeletionInfo 9100 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 9101 bool Diagnose; 9102 9103 SourceLocation Loc; 9104 9105 bool AllFieldsAreConst; 9106 9107 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 9108 Sema::CXXSpecialMember CSM, 9109 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 9110 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 9111 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 9112 9113 bool inUnion() const { return MD->getParent()->isUnion(); } 9114 9115 Sema::CXXSpecialMember getEffectiveCSM() { 9116 return ICI ? Sema::CXXInvalid : CSM; 9117 } 9118 9119 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 9120 9121 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 9122 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 9123 9124 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 9125 bool shouldDeleteForField(FieldDecl *FD); 9126 bool shouldDeleteForAllConstMembers(); 9127 9128 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 9129 unsigned Quals); 9130 bool shouldDeleteForSubobjectCall(Subobject Subobj, 9131 Sema::SpecialMemberOverloadResult SMOR, 9132 bool IsDtorCallInCtor); 9133 9134 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 9135}; 9136} 9137 9138/// Is the given special member inaccessible when used on the given 9139/// sub-object. 9140bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 9141 CXXMethodDecl *target) { 9142 /// If we're operating on a base class, the object type is the 9143 /// type of this special member. 9144 QualType objectTy; 9145 AccessSpecifier access = target->getAccess(); 9146 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 9147 objectTy = S.Context.getTypeDeclType(MD->getParent()); 9148 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 9149 9150 // If we're operating on a field, the object type is the type of the field. 9151 } else { 9152 objectTy = S.Context.getTypeDeclType(target->getParent()); 9153 } 9154 9155 return S.isMemberAccessibleForDeletion( 9156 target->getParent(), DeclAccessPair::make(target, access), objectTy); 9157} 9158 9159/// Check whether we should delete a special member due to the implicit 9160/// definition containing a call to a special member of a subobject. 9161bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 9162 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 9163 bool IsDtorCallInCtor) { 9164 CXXMethodDecl *Decl = SMOR.getMethod(); 9165 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 9166 9167 int DiagKind = -1; 9168 9169 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 9170 DiagKind = !Decl ? 0 : 1; 9171 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9172 DiagKind = 2; 9173 else if (!isAccessible(Subobj, Decl)) 9174 DiagKind = 3; 9175 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 9176 !Decl->isTrivial()) { 9177 // A member of a union must have a trivial corresponding special member. 9178 // As a weird special case, a destructor call from a union's constructor 9179 // must be accessible and non-deleted, but need not be trivial. Such a 9180 // destructor is never actually called, but is semantically checked as 9181 // if it were. 9182 if (CSM == Sema::CXXDefaultConstructor) { 9183 // [class.default.ctor]p2: 9184 // A defaulted default constructor for class X is defined as deleted if 9185 // - X is a union that has a variant member with a non-trivial default 9186 // constructor and no variant member of X has a default member 9187 // initializer 9188 const auto *RD = cast<CXXRecordDecl>(Field->getParent()); 9189 if (!RD->hasInClassInitializer()) 9190 DiagKind = 4; 9191 } else { 9192 DiagKind = 4; 9193 } 9194 } 9195 9196 if (DiagKind == -1) 9197 return false; 9198 9199 if (Diagnose) { 9200 if (Field) { 9201 S.Diag(Field->getLocation(), 9202 diag::note_deleted_special_member_class_subobject) 9203 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 9204 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 9205 } else { 9206 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 9207 S.Diag(Base->getBeginLoc(), 9208 diag::note_deleted_special_member_class_subobject) 9209 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 9210 << Base->getType() << DiagKind << IsDtorCallInCtor 9211 << /*IsObjCPtr*/false; 9212 } 9213 9214 if (DiagKind == 1) 9215 S.NoteDeletedFunction(Decl); 9216 // FIXME: Explain inaccessibility if DiagKind == 3. 9217 } 9218 9219 return true; 9220} 9221 9222/// Check whether we should delete a special member function due to having a 9223/// direct or virtual base class or non-static data member of class type M. 9224bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 9225 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 9226 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 9227 bool IsMutable = Field && Field->isMutable(); 9228 9229 // C++11 [class.ctor]p5: 9230 // -- any direct or virtual base class, or non-static data member with no 9231 // brace-or-equal-initializer, has class type M (or array thereof) and 9232 // either M has no default constructor or overload resolution as applied 9233 // to M's default constructor results in an ambiguity or in a function 9234 // that is deleted or inaccessible 9235 // C++11 [class.copy]p11, C++11 [class.copy]p23: 9236 // -- a direct or virtual base class B that cannot be copied/moved because 9237 // overload resolution, as applied to B's corresponding special member, 9238 // results in an ambiguity or a function that is deleted or inaccessible 9239 // from the defaulted special member 9240 // C++11 [class.dtor]p5: 9241 // -- any direct or virtual base class [...] has a type with a destructor 9242 // that is deleted or inaccessible 9243 if (!(CSM == Sema::CXXDefaultConstructor && 9244 Field && Field->hasInClassInitializer()) && 9245 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 9246 false)) 9247 return true; 9248 9249 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 9250 // -- any direct or virtual base class or non-static data member has a 9251 // type with a destructor that is deleted or inaccessible 9252 if (IsConstructor) { 9253 Sema::SpecialMemberOverloadResult SMOR = 9254 S.LookupSpecialMember(Class, Sema::CXXDestructor, 9255 false, false, false, false, false); 9256 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 9257 return true; 9258 } 9259 9260 return false; 9261} 9262 9263bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 9264 FieldDecl *FD, QualType FieldType) { 9265 // The defaulted special functions are defined as deleted if this is a variant 9266 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 9267 // type under ARC. 9268 if (!FieldType.hasNonTrivialObjCLifetime()) 9269 return false; 9270 9271 // Don't make the defaulted default constructor defined as deleted if the 9272 // member has an in-class initializer. 9273 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 9274 return false; 9275 9276 if (Diagnose) { 9277 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 9278 S.Diag(FD->getLocation(), 9279 diag::note_deleted_special_member_class_subobject) 9280 << getEffectiveCSM() << ParentClass << /*IsField*/true 9281 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 9282 } 9283 9284 return true; 9285} 9286 9287/// Check whether we should delete a special member function due to the class 9288/// having a particular direct or virtual base class. 9289bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 9290 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 9291 // If program is correct, BaseClass cannot be null, but if it is, the error 9292 // must be reported elsewhere. 9293 if (!BaseClass) 9294 return false; 9295 // If we have an inheriting constructor, check whether we're calling an 9296 // inherited constructor instead of a default constructor. 9297 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 9298 if (auto *BaseCtor = SMOR.getMethod()) { 9299 // Note that we do not check access along this path; other than that, 9300 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 9301 // FIXME: Check that the base has a usable destructor! Sink this into 9302 // shouldDeleteForClassSubobject. 9303 if (BaseCtor->isDeleted() && Diagnose) { 9304 S.Diag(Base->getBeginLoc(), 9305 diag::note_deleted_special_member_class_subobject) 9306 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 9307 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 9308 << /*IsObjCPtr*/false; 9309 S.NoteDeletedFunction(BaseCtor); 9310 } 9311 return BaseCtor->isDeleted(); 9312 } 9313 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 9314} 9315 9316/// Check whether we should delete a special member function due to the class 9317/// having a particular non-static data member. 9318bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 9319 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 9320 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 9321 9322 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 9323 return true; 9324 9325 if (CSM == Sema::CXXDefaultConstructor) { 9326 // For a default constructor, all references must be initialized in-class 9327 // and, if a union, it must have a non-const member. 9328 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 9329 if (Diagnose) 9330 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9331 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 9332 return true; 9333 } 9334 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static 9335 // data member of const-qualified type (or array thereof) with no 9336 // brace-or-equal-initializer is not const-default-constructible. 9337 if (!inUnion() && FieldType.isConstQualified() && 9338 !FD->hasInClassInitializer() && 9339 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) { 9340 if (Diagnose) 9341 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9342 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 9343 return true; 9344 } 9345 9346 if (inUnion() && !FieldType.isConstQualified()) 9347 AllFieldsAreConst = false; 9348 } else if (CSM == Sema::CXXCopyConstructor) { 9349 // For a copy constructor, data members must not be of rvalue reference 9350 // type. 9351 if (FieldType->isRValueReferenceType()) { 9352 if (Diagnose) 9353 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 9354 << MD->getParent() << FD << FieldType; 9355 return true; 9356 } 9357 } else if (IsAssignment) { 9358 // For an assignment operator, data members must not be of reference type. 9359 if (FieldType->isReferenceType()) { 9360 if (Diagnose) 9361 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9362 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 9363 return true; 9364 } 9365 if (!FieldRecord && FieldType.isConstQualified()) { 9366 // C++11 [class.copy]p23: 9367 // -- a non-static data member of const non-class type (or array thereof) 9368 if (Diagnose) 9369 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9370 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 9371 return true; 9372 } 9373 } 9374 9375 if (FieldRecord) { 9376 // Some additional restrictions exist on the variant members. 9377 if (!inUnion() && FieldRecord->isUnion() && 9378 FieldRecord->isAnonymousStructOrUnion()) { 9379 bool AllVariantFieldsAreConst = true; 9380 9381 // FIXME: Handle anonymous unions declared within anonymous unions. 9382 for (auto *UI : FieldRecord->fields()) { 9383 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 9384 9385 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 9386 return true; 9387 9388 if (!UnionFieldType.isConstQualified()) 9389 AllVariantFieldsAreConst = false; 9390 9391 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 9392 if (UnionFieldRecord && 9393 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 9394 UnionFieldType.getCVRQualifiers())) 9395 return true; 9396 } 9397 9398 // At least one member in each anonymous union must be non-const 9399 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 9400 !FieldRecord->field_empty()) { 9401 if (Diagnose) 9402 S.Diag(FieldRecord->getLocation(), 9403 diag::note_deleted_default_ctor_all_const) 9404 << !!ICI << MD->getParent() << /*anonymous union*/1; 9405 return true; 9406 } 9407 9408 // Don't check the implicit member of the anonymous union type. 9409 // This is technically non-conformant but supported, and we have a 9410 // diagnostic for this elsewhere. 9411 return false; 9412 } 9413 9414 if (shouldDeleteForClassSubobject(FieldRecord, FD, 9415 FieldType.getCVRQualifiers())) 9416 return true; 9417 } 9418 9419 return false; 9420} 9421 9422/// C++11 [class.ctor] p5: 9423/// A defaulted default constructor for a class X is defined as deleted if 9424/// X is a union and all of its variant members are of const-qualified type. 9425bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 9426 // This is a silly definition, because it gives an empty union a deleted 9427 // default constructor. Don't do that. 9428 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9429 bool AnyFields = false; 9430 for (auto *F : MD->getParent()->fields()) 9431 if ((AnyFields = !F->isUnnamedBitfield())) 9432 break; 9433 if (!AnyFields) 9434 return false; 9435 if (Diagnose) 9436 S.Diag(MD->getParent()->getLocation(), 9437 diag::note_deleted_default_ctor_all_const) 9438 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9439 return true; 9440 } 9441 return false; 9442} 9443 9444/// Determine whether a defaulted special member function should be defined as 9445/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9446/// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9447bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9448 InheritedConstructorInfo *ICI, 9449 bool Diagnose) { 9450 if (MD->isInvalidDecl()) 9451 return false; 9452 CXXRecordDecl *RD = MD->getParent(); 9453 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", 9453, __extension__ __PRETTY_FUNCTION__
))
; 9454 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9455 return false; 9456 9457 // C++11 [expr.lambda.prim]p19: 9458 // The closure type associated with a lambda-expression has a 9459 // deleted (8.4.3) default constructor and a deleted copy 9460 // assignment operator. 9461 // C++2a adds back these operators if the lambda has no lambda-capture. 9462 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9463 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9464 if (Diagnose) 9465 Diag(RD->getLocation(), diag::note_lambda_decl); 9466 return true; 9467 } 9468 9469 // For an anonymous struct or union, the copy and assignment special members 9470 // will never be used, so skip the check. For an anonymous union declared at 9471 // namespace scope, the constructor and destructor are used. 9472 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9473 RD->isAnonymousStructOrUnion()) 9474 return false; 9475 9476 // C++11 [class.copy]p7, p18: 9477 // If the class definition declares a move constructor or move assignment 9478 // operator, an implicitly declared copy constructor or copy assignment 9479 // operator is defined as deleted. 9480 if (MD->isImplicit() && 9481 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9482 CXXMethodDecl *UserDeclaredMove = nullptr; 9483 9484 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9485 // deletion of the corresponding copy operation, not both copy operations. 9486 // MSVC 2015 has adopted the standards conforming behavior. 9487 bool DeletesOnlyMatchingCopy = 9488 getLangOpts().MSVCCompat && 9489 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9490 9491 if (RD->hasUserDeclaredMoveConstructor() && 9492 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9493 if (!Diagnose) return true; 9494 9495 // Find any user-declared move constructor. 9496 for (auto *I : RD->ctors()) { 9497 if (I->isMoveConstructor()) { 9498 UserDeclaredMove = I; 9499 break; 9500 } 9501 } 9502 assert(UserDeclaredMove)(static_cast <bool> (UserDeclaredMove) ? void (0) : __assert_fail
("UserDeclaredMove", "clang/lib/Sema/SemaDeclCXX.cpp", 9502,
__extension__ __PRETTY_FUNCTION__))
; 9503 } else if (RD->hasUserDeclaredMoveAssignment() && 9504 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9505 if (!Diagnose) return true; 9506 9507 // Find any user-declared move assignment operator. 9508 for (auto *I : RD->methods()) { 9509 if (I->isMoveAssignmentOperator()) { 9510 UserDeclaredMove = I; 9511 break; 9512 } 9513 } 9514 assert(UserDeclaredMove)(static_cast <bool> (UserDeclaredMove) ? void (0) : __assert_fail
("UserDeclaredMove", "clang/lib/Sema/SemaDeclCXX.cpp", 9514,
__extension__ __PRETTY_FUNCTION__))
; 9515 } 9516 9517 if (UserDeclaredMove) { 9518 Diag(UserDeclaredMove->getLocation(), 9519 diag::note_deleted_copy_user_declared_move) 9520 << (CSM == CXXCopyAssignment) << RD 9521 << UserDeclaredMove->isMoveAssignmentOperator(); 9522 return true; 9523 } 9524 } 9525 9526 // Do access control from the special member function 9527 ContextRAII MethodContext(*this, MD); 9528 9529 // C++11 [class.dtor]p5: 9530 // -- for a virtual destructor, lookup of the non-array deallocation function 9531 // results in an ambiguity or in a function that is deleted or inaccessible 9532 if (CSM == CXXDestructor && MD->isVirtual()) { 9533 FunctionDecl *OperatorDelete = nullptr; 9534 DeclarationName Name = 9535 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9536 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9537 OperatorDelete, /*Diagnose*/false)) { 9538 if (Diagnose) 9539 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9540 return true; 9541 } 9542 } 9543 9544 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9545 9546 // Per DR1611, do not consider virtual bases of constructors of abstract 9547 // classes, since we are not going to construct them. 9548 // Per DR1658, do not consider virtual bases of destructors of abstract 9549 // classes either. 9550 // Per DR2180, for assignment operators we only assign (and thus only 9551 // consider) direct bases. 9552 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9553 : SMI.VisitPotentiallyConstructedBases)) 9554 return true; 9555 9556 if (SMI.shouldDeleteForAllConstMembers()) 9557 return true; 9558 9559 if (getLangOpts().CUDA) { 9560 // We should delete the special member in CUDA mode if target inference 9561 // failed. 9562 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9563 // is treated as certain special member, which may not reflect what special 9564 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9565 // expects CSM to match MD, therefore recalculate CSM. 9566 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", 9566, __extension__ __PRETTY_FUNCTION__
))
; 9567 auto RealCSM = CSM; 9568 if (ICI) 9569 RealCSM = getSpecialMember(MD); 9570 9571 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9572 SMI.ConstArg, Diagnose); 9573 } 9574 9575 return false; 9576} 9577 9578void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9579 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9580 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", 9580, __extension__ __PRETTY_FUNCTION__
))
; 9581 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", 9581, __extension__ __PRETTY_FUNCTION__
))
; 9582 9583 if (DFK.isSpecialMember()) { 9584 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9585 nullptr, /*Diagnose=*/true); 9586 } else { 9587 DefaultedComparisonAnalyzer( 9588 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9589 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9590 .visit(); 9591 } 9592} 9593 9594/// Perform lookup for a special member of the specified kind, and determine 9595/// whether it is trivial. If the triviality can be determined without the 9596/// lookup, skip it. This is intended for use when determining whether a 9597/// special member of a containing object is trivial, and thus does not ever 9598/// perform overload resolution for default constructors. 9599/// 9600/// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9601/// member that was most likely to be intended to be trivial, if any. 9602/// 9603/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9604/// determine whether the special member is trivial. 9605static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9606 Sema::CXXSpecialMember CSM, unsigned Quals, 9607 bool ConstRHS, 9608 Sema::TrivialABIHandling TAH, 9609 CXXMethodDecl **Selected) { 9610 if (Selected) 9611 *Selected = nullptr; 9612 9613 switch (CSM) { 9614 case Sema::CXXInvalid: 9615 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "clang/lib/Sema/SemaDeclCXX.cpp"
, 9615)
; 9616 9617 case Sema::CXXDefaultConstructor: 9618 // C++11 [class.ctor]p5: 9619 // A default constructor is trivial if: 9620 // - all the [direct subobjects] have trivial default constructors 9621 // 9622 // Note, no overload resolution is performed in this case. 9623 if (RD->hasTrivialDefaultConstructor()) 9624 return true; 9625 9626 if (Selected) { 9627 // If there's a default constructor which could have been trivial, dig it 9628 // out. Otherwise, if there's any user-provided default constructor, point 9629 // to that as an example of why there's not a trivial one. 9630 CXXConstructorDecl *DefCtor = nullptr; 9631 if (RD->needsImplicitDefaultConstructor()) 9632 S.DeclareImplicitDefaultConstructor(RD); 9633 for (auto *CI : RD->ctors()) { 9634 if (!CI->isDefaultConstructor()) 9635 continue; 9636 DefCtor = CI; 9637 if (!DefCtor->isUserProvided()) 9638 break; 9639 } 9640 9641 *Selected = DefCtor; 9642 } 9643 9644 return false; 9645 9646 case Sema::CXXDestructor: 9647 // C++11 [class.dtor]p5: 9648 // A destructor is trivial if: 9649 // - all the direct [subobjects] have trivial destructors 9650 if (RD->hasTrivialDestructor() || 9651 (TAH == Sema::TAH_ConsiderTrivialABI && 9652 RD->hasTrivialDestructorForCall())) 9653 return true; 9654 9655 if (Selected) { 9656 if (RD->needsImplicitDestructor()) 9657 S.DeclareImplicitDestructor(RD); 9658 *Selected = RD->getDestructor(); 9659 } 9660 9661 return false; 9662 9663 case Sema::CXXCopyConstructor: 9664 // C++11 [class.copy]p12: 9665 // A copy constructor is trivial if: 9666 // - the constructor selected to copy each direct [subobject] is trivial 9667 if (RD->hasTrivialCopyConstructor() || 9668 (TAH == Sema::TAH_ConsiderTrivialABI && 9669 RD->hasTrivialCopyConstructorForCall())) { 9670 if (Quals == Qualifiers::Const) 9671 // We must either select the trivial copy constructor or reach an 9672 // ambiguity; no need to actually perform overload resolution. 9673 return true; 9674 } else if (!Selected) { 9675 return false; 9676 } 9677 // In C++98, we are not supposed to perform overload resolution here, but we 9678 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9679 // cases like B as having a non-trivial copy constructor: 9680 // struct A { template<typename T> A(T&); }; 9681 // struct B { mutable A a; }; 9682 goto NeedOverloadResolution; 9683 9684 case Sema::CXXCopyAssignment: 9685 // C++11 [class.copy]p25: 9686 // A copy assignment operator is trivial if: 9687 // - the assignment operator selected to copy each direct [subobject] is 9688 // trivial 9689 if (RD->hasTrivialCopyAssignment()) { 9690 if (Quals == Qualifiers::Const) 9691 return true; 9692 } else if (!Selected) { 9693 return false; 9694 } 9695 // In C++98, we are not supposed to perform overload resolution here, but we 9696 // treat that as a language defect. 9697 goto NeedOverloadResolution; 9698 9699 case Sema::CXXMoveConstructor: 9700 case Sema::CXXMoveAssignment: 9701 NeedOverloadResolution: 9702 Sema::SpecialMemberOverloadResult SMOR = 9703 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9704 9705 // The standard doesn't describe how to behave if the lookup is ambiguous. 9706 // We treat it as not making the member non-trivial, just like the standard 9707 // mandates for the default constructor. This should rarely matter, because 9708 // the member will also be deleted. 9709 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9710 return true; 9711 9712 if (!SMOR.getMethod()) { 9713 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", 9714, __extension__ __PRETTY_FUNCTION__
))
9714 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", 9714, __extension__ __PRETTY_FUNCTION__
))
; 9715 return false; 9716 } 9717 9718 // We deliberately don't check if we found a deleted special member. We're 9719 // not supposed to! 9720 if (Selected) 9721 *Selected = SMOR.getMethod(); 9722 9723 if (TAH == Sema::TAH_ConsiderTrivialABI && 9724 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9725 return SMOR.getMethod()->isTrivialForCall(); 9726 return SMOR.getMethod()->isTrivial(); 9727 } 9728 9729 llvm_unreachable("unknown special method kind")::llvm::llvm_unreachable_internal("unknown special method kind"
, "clang/lib/Sema/SemaDeclCXX.cpp", 9729)
; 9730} 9731 9732static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9733 for (auto *CI : RD->ctors()) 9734 if (!CI->isImplicit()) 9735 return CI; 9736 9737 // Look for constructor templates. 9738 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9739 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9740 if (CXXConstructorDecl *CD = 9741 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9742 return CD; 9743 } 9744 9745 return nullptr; 9746} 9747 9748/// The kind of subobject we are checking for triviality. The values of this 9749/// enumeration are used in diagnostics. 9750enum TrivialSubobjectKind { 9751 /// The subobject is a base class. 9752 TSK_BaseClass, 9753 /// The subobject is a non-static data member. 9754 TSK_Field, 9755 /// The object is actually the complete object. 9756 TSK_CompleteObject 9757}; 9758 9759/// Check whether the special member selected for a given type would be trivial. 9760static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9761 QualType SubType, bool ConstRHS, 9762 Sema::CXXSpecialMember CSM, 9763 TrivialSubobjectKind Kind, 9764 Sema::TrivialABIHandling TAH, bool Diagnose) { 9765 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9766 if (!SubRD) 9767 return true; 9768 9769 CXXMethodDecl *Selected; 9770 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9771 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9772 return true; 9773 9774 if (Diagnose) { 9775 if (ConstRHS) 9776 SubType.addConst(); 9777 9778 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9779 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9780 << Kind << SubType.getUnqualifiedType(); 9781 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9782 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9783 } else if (!Selected) 9784 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9785 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9786 else if (Selected->isUserProvided()) { 9787 if (Kind == TSK_CompleteObject) 9788 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9789 << Kind << SubType.getUnqualifiedType() << CSM; 9790 else { 9791 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9792 << Kind << SubType.getUnqualifiedType() << CSM; 9793 S.Diag(Selected->getLocation(), diag::note_declared_at); 9794 } 9795 } else { 9796 if (Kind != TSK_CompleteObject) 9797 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9798 << Kind << SubType.getUnqualifiedType() << CSM; 9799 9800 // Explain why the defaulted or deleted special member isn't trivial. 9801 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9802 Diagnose); 9803 } 9804 } 9805 9806 return false; 9807} 9808 9809/// Check whether the members of a class type allow a special member to be 9810/// trivial. 9811static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9812 Sema::CXXSpecialMember CSM, 9813 bool ConstArg, 9814 Sema::TrivialABIHandling TAH, 9815 bool Diagnose) { 9816 for (const auto *FI : RD->fields()) { 9817 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9818 continue; 9819 9820 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9821 9822 // Pretend anonymous struct or union members are members of this class. 9823 if (FI->isAnonymousStructOrUnion()) { 9824 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9825 CSM, ConstArg, TAH, Diagnose)) 9826 return false; 9827 continue; 9828 } 9829 9830 // C++11 [class.ctor]p5: 9831 // A default constructor is trivial if [...] 9832 // -- no non-static data member of its class has a 9833 // brace-or-equal-initializer 9834 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9835 if (Diagnose) 9836 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9837 << FI; 9838 return false; 9839 } 9840 9841 // Objective C ARC 4.3.5: 9842 // [...] nontrivally ownership-qualified types are [...] not trivially 9843 // default constructible, copy constructible, move constructible, copy 9844 // assignable, move assignable, or destructible [...] 9845 if (FieldType.hasNonTrivialObjCLifetime()) { 9846 if (Diagnose) 9847 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9848 << RD << FieldType.getObjCLifetime(); 9849 return false; 9850 } 9851 9852 bool ConstRHS = ConstArg && !FI->isMutable(); 9853 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9854 CSM, TSK_Field, TAH, Diagnose)) 9855 return false; 9856 } 9857 9858 return true; 9859} 9860 9861/// Diagnose why the specified class does not have a trivial special member of 9862/// the given kind. 9863void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9864 QualType Ty = Context.getRecordType(RD); 9865 9866 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9867 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9868 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9869 /*Diagnose*/true); 9870} 9871 9872/// Determine whether a defaulted or deleted special member function is trivial, 9873/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9874/// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9875bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9876 TrivialABIHandling TAH, bool Diagnose) { 9877 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", 9877, __extension__ __PRETTY_FUNCTION__
))
; 9878 9879 CXXRecordDecl *RD = MD->getParent(); 9880 9881 bool ConstArg = false; 9882 9883 // C++11 [class.copy]p12, p25: [DR1593] 9884 // A [special member] is trivial if [...] its parameter-type-list is 9885 // equivalent to the parameter-type-list of an implicit declaration [...] 9886 switch (CSM) { 9887 case CXXDefaultConstructor: 9888 case CXXDestructor: 9889 // Trivial default constructors and destructors cannot have parameters. 9890 break; 9891 9892 case CXXCopyConstructor: 9893 case CXXCopyAssignment: { 9894 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9895 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9896 9897 // When ClangABICompat14 is true, CXX copy constructors will only be trivial 9898 // if they are not user-provided and their parameter-type-list is equivalent 9899 // to the parameter-type-list of an implicit declaration. This maintains the 9900 // behavior before dr2171 was implemented. 9901 // 9902 // Otherwise, if ClangABICompat14 is false, All copy constructors can be 9903 // trivial, if they are not user-provided, regardless of the qualifiers on 9904 // the reference type. 9905 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <= 9906 LangOptions::ClangABI::Ver14; 9907 if (!RT || 9908 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) && 9909 ClangABICompat14)) { 9910 if (Diagnose) 9911 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9912 << Param0->getSourceRange() << Param0->getType() 9913 << Context.getLValueReferenceType( 9914 Context.getRecordType(RD).withConst()); 9915 return false; 9916 } 9917 9918 ConstArg = RT->getPointeeType().isConstQualified(); 9919 break; 9920 } 9921 9922 case CXXMoveConstructor: 9923 case CXXMoveAssignment: { 9924 // Trivial move operations always have non-cv-qualified parameters. 9925 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9926 const RValueReferenceType *RT = 9927 Param0->getType()->getAs<RValueReferenceType>(); 9928 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9929 if (Diagnose) 9930 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9931 << Param0->getSourceRange() << Param0->getType() 9932 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9933 return false; 9934 } 9935 break; 9936 } 9937 9938 case CXXInvalid: 9939 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "clang/lib/Sema/SemaDeclCXX.cpp"
, 9939)
; 9940 } 9941 9942 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9943 if (Diagnose) 9944 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9945 diag::note_nontrivial_default_arg) 9946 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9947 return false; 9948 } 9949 if (MD->isVariadic()) { 9950 if (Diagnose) 9951 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9952 return false; 9953 } 9954 9955 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9956 // A copy/move [constructor or assignment operator] is trivial if 9957 // -- the [member] selected to copy/move each direct base class subobject 9958 // is trivial 9959 // 9960 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9961 // A [default constructor or destructor] is trivial if 9962 // -- all the direct base classes have trivial [default constructors or 9963 // destructors] 9964 for (const auto &BI : RD->bases()) 9965 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9966 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9967 return false; 9968 9969 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9970 // A copy/move [constructor or assignment operator] for a class X is 9971 // trivial if 9972 // -- for each non-static data member of X that is of class type (or array 9973 // thereof), the constructor selected to copy/move that member is 9974 // trivial 9975 // 9976 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9977 // A [default constructor or destructor] is trivial if 9978 // -- for all of the non-static data members of its class that are of class 9979 // type (or array thereof), each such class has a trivial [default 9980 // constructor or destructor] 9981 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9982 return false; 9983 9984 // C++11 [class.dtor]p5: 9985 // A destructor is trivial if [...] 9986 // -- the destructor is not virtual 9987 if (CSM == CXXDestructor && MD->isVirtual()) { 9988 if (Diagnose) 9989 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9990 return false; 9991 } 9992 9993 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9994 // A [special member] for class X is trivial if [...] 9995 // -- class X has no virtual functions and no virtual base classes 9996 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9997 if (!Diagnose) 9998 return false; 9999 10000 if (RD->getNumVBases()) { 10001 // Check for virtual bases. We already know that the corresponding 10002 // member in all bases is trivial, so vbases must all be direct. 10003 CXXBaseSpecifier &BS = *RD->vbases_begin(); 10004 assert(BS.isVirtual())(static_cast <bool> (BS.isVirtual()) ? void (0) : __assert_fail
("BS.isVirtual()", "clang/lib/Sema/SemaDeclCXX.cpp", 10004, __extension__
__PRETTY_FUNCTION__))
; 10005 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 10006 return false; 10007 } 10008 10009 // Must have a virtual method. 10010 for (const auto *MI : RD->methods()) { 10011 if (MI->isVirtual()) { 10012 SourceLocation MLoc = MI->getBeginLoc(); 10013 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 10014 return false; 10015 } 10016 } 10017 10018 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", 10018)
; 10019 } 10020 10021 // Looks like it's trivial! 10022 return true; 10023} 10024 10025namespace { 10026struct FindHiddenVirtualMethod { 10027 Sema *S; 10028 CXXMethodDecl *Method; 10029 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 10030 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 10031 10032private: 10033 /// Check whether any most overridden method from MD in Methods 10034 static bool CheckMostOverridenMethods( 10035 const CXXMethodDecl *MD, 10036 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 10037 if (MD->size_overridden_methods() == 0) 10038 return Methods.count(MD->getCanonicalDecl()); 10039 for (const CXXMethodDecl *O : MD->overridden_methods()) 10040 if (CheckMostOverridenMethods(O, Methods)) 10041 return true; 10042 return false; 10043 } 10044 10045public: 10046 /// Member lookup function that determines whether a given C++ 10047 /// method overloads virtual methods in a base class without overriding any, 10048 /// to be used with CXXRecordDecl::lookupInBases(). 10049 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 10050 RecordDecl *BaseRecord = 10051 Specifier->getType()->castAs<RecordType>()->getDecl(); 10052 10053 DeclarationName Name = Method->getDeclName(); 10054 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", 10054, __extension__ __PRETTY_FUNCTION__
))
; 10055 10056 bool foundSameNameMethod = false; 10057 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 10058 for (Path.Decls = BaseRecord->lookup(Name).begin(); 10059 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) { 10060 NamedDecl *D = *Path.Decls; 10061 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 10062 MD = MD->getCanonicalDecl(); 10063 foundSameNameMethod = true; 10064 // Interested only in hidden virtual methods. 10065 if (!MD->isVirtual()) 10066 continue; 10067 // If the method we are checking overrides a method from its base 10068 // don't warn about the other overloaded methods. Clang deviates from 10069 // GCC by only diagnosing overloads of inherited virtual functions that 10070 // do not override any other virtual functions in the base. GCC's 10071 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 10072 // function from a base class. These cases may be better served by a 10073 // warning (not specific to virtual functions) on call sites when the 10074 // call would select a different function from the base class, were it 10075 // visible. 10076 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 10077 if (!S->IsOverload(Method, MD, false)) 10078 return true; 10079 // Collect the overload only if its hidden. 10080 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 10081 overloadedMethods.push_back(MD); 10082 } 10083 } 10084 10085 if (foundSameNameMethod) 10086 OverloadedMethods.append(overloadedMethods.begin(), 10087 overloadedMethods.end()); 10088 return foundSameNameMethod; 10089 } 10090}; 10091} // end anonymous namespace 10092 10093/// Add the most overridden methods from MD to Methods 10094static void AddMostOverridenMethods(const CXXMethodDecl *MD, 10095 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 10096 if (MD->size_overridden_methods() == 0) 10097 Methods.insert(MD->getCanonicalDecl()); 10098 else 10099 for (const CXXMethodDecl *O : MD->overridden_methods()) 10100 AddMostOverridenMethods(O, Methods); 10101} 10102 10103/// Check if a method overloads virtual methods in a base class without 10104/// overriding any. 10105void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 10106 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 10107 if (!MD->getDeclName().isIdentifier()) 10108 return; 10109 10110 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 10111 /*bool RecordPaths=*/false, 10112 /*bool DetectVirtual=*/false); 10113 FindHiddenVirtualMethod FHVM; 10114 FHVM.Method = MD; 10115 FHVM.S = this; 10116 10117 // Keep the base methods that were overridden or introduced in the subclass 10118 // by 'using' in a set. A base method not in this set is hidden. 10119 CXXRecordDecl *DC = MD->getParent(); 10120 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 10121 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 10122 NamedDecl *ND = *I; 10123 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 10124 ND = shad->getTargetDecl(); 10125 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 10126 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 10127 } 10128 10129 if (DC->lookupInBases(FHVM, Paths)) 10130 OverloadedMethods = FHVM.OverloadedMethods; 10131} 10132 10133void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 10134 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 10135 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 10136 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 10137 PartialDiagnostic PD = PDiag( 10138 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 10139 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 10140 Diag(overloadedMD->getLocation(), PD); 10141 } 10142} 10143 10144/// Diagnose methods which overload virtual methods in a base class 10145/// without overriding any. 10146void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 10147 if (MD->isInvalidDecl()) 10148 return; 10149 10150 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 10151 return; 10152 10153 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 10154 FindHiddenVirtualMethods(MD, OverloadedMethods); 10155 if (!OverloadedMethods.empty()) { 10156 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 10157 << MD << (OverloadedMethods.size() > 1); 10158 10159 NoteHiddenVirtualMethods(MD, OverloadedMethods); 10160 } 10161} 10162 10163void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 10164 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 10165 // No diagnostics if this is a template instantiation. 10166 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 10167 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 10168 diag::ext_cannot_use_trivial_abi) << &RD; 10169 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 10170 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 10171 } 10172 RD.dropAttr<TrivialABIAttr>(); 10173 }; 10174 10175 // Ill-formed if the copy and move constructors are deleted. 10176 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 10177 // If the type is dependent, then assume it might have 10178 // implicit copy or move ctor because we won't know yet at this point. 10179 if (RD.isDependentType()) 10180 return true; 10181 if (RD.needsImplicitCopyConstructor() && 10182 !RD.defaultedCopyConstructorIsDeleted()) 10183 return true; 10184 if (RD.needsImplicitMoveConstructor() && 10185 !RD.defaultedMoveConstructorIsDeleted()) 10186 return true; 10187 for (const CXXConstructorDecl *CD : RD.ctors()) 10188 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 10189 return true; 10190 return false; 10191 }; 10192 10193 if (!HasNonDeletedCopyOrMoveConstructor()) { 10194 PrintDiagAndRemoveAttr(0); 10195 return; 10196 } 10197 10198 // Ill-formed if the struct has virtual functions. 10199 if (RD.isPolymorphic()) { 10200 PrintDiagAndRemoveAttr(1); 10201 return; 10202 } 10203 10204 for (const auto &B : RD.bases()) { 10205 // Ill-formed if the base class is non-trivial for the purpose of calls or a 10206 // virtual base. 10207 if (!B.getType()->isDependentType() && 10208 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 10209 PrintDiagAndRemoveAttr(2); 10210 return; 10211 } 10212 10213 if (B.isVirtual()) { 10214 PrintDiagAndRemoveAttr(3); 10215 return; 10216 } 10217 } 10218 10219 for (const auto *FD : RD.fields()) { 10220 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 10221 // non-trivial for the purpose of calls. 10222 QualType FT = FD->getType(); 10223 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 10224 PrintDiagAndRemoveAttr(4); 10225 return; 10226 } 10227 10228 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 10229 if (!RT->isDependentType() && 10230 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 10231 PrintDiagAndRemoveAttr(5); 10232 return; 10233 } 10234 } 10235} 10236 10237void Sema::ActOnFinishCXXMemberSpecification( 10238 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 10239 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 10240 if (!TagDecl) 10241 return; 10242 10243 AdjustDeclIfTemplate(TagDecl); 10244 10245 for (const ParsedAttr &AL : AttrList) { 10246 if (AL.getKind() != ParsedAttr::AT_Visibility) 10247 continue; 10248 AL.setInvalid(); 10249 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 10250 } 10251 10252 ActOnFields(S, RLoc, TagDecl, 10253 llvm::ArrayRef( 10254 // strict aliasing violation! 10255 reinterpret_cast<Decl **>(FieldCollector->getCurFields()), 10256 FieldCollector->getCurNumFields()), 10257 LBrac, RBrac, AttrList); 10258 10259 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 10260} 10261 10262/// Find the equality comparison functions that should be implicitly declared 10263/// in a given class definition, per C++2a [class.compare.default]p3. 10264static void findImplicitlyDeclaredEqualityComparisons( 10265 ASTContext &Ctx, CXXRecordDecl *RD, 10266 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 10267 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 10268 if (!RD->lookup(EqEq).empty()) 10269 // Member operator== explicitly declared: no implicit operator==s. 10270 return; 10271 10272 // Traverse friends looking for an '==' or a '<=>'. 10273 for (FriendDecl *Friend : RD->friends()) { 10274 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 10275 if (!FD) continue; 10276 10277 if (FD->getOverloadedOperator() == OO_EqualEqual) { 10278 // Friend operator== explicitly declared: no implicit operator==s. 10279 Spaceships.clear(); 10280 return; 10281 } 10282 10283 if (FD->getOverloadedOperator() == OO_Spaceship && 10284 FD->isExplicitlyDefaulted()) 10285 Spaceships.push_back(FD); 10286 } 10287 10288 // Look for members named 'operator<=>'. 10289 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 10290 for (NamedDecl *ND : RD->lookup(Cmp)) { 10291 // Note that we could find a non-function here (either a function template 10292 // or a using-declaration). Neither case results in an implicit 10293 // 'operator=='. 10294 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 10295 if (FD->isExplicitlyDefaulted()) 10296 Spaceships.push_back(FD); 10297 } 10298} 10299 10300/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 10301/// special functions, such as the default constructor, copy 10302/// constructor, or destructor, to the given C++ class (C++ 10303/// [special]p1). This routine can only be executed just before the 10304/// definition of the class is complete. 10305void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 10306 // Don't add implicit special members to templated classes. 10307 // FIXME: This means unqualified lookups for 'operator=' within a class 10308 // template don't work properly. 10309 if (!ClassDecl->isDependentType()) { 10310 if (ClassDecl->needsImplicitDefaultConstructor()) { 10311 ++getASTContext().NumImplicitDefaultConstructors; 10312 10313 if (ClassDecl->hasInheritedConstructor()) 10314 DeclareImplicitDefaultConstructor(ClassDecl); 10315 } 10316 10317 if (ClassDecl->needsImplicitCopyConstructor()) { 10318 ++getASTContext().NumImplicitCopyConstructors; 10319 10320 // If the properties or semantics of the copy constructor couldn't be 10321 // determined while the class was being declared, force a declaration 10322 // of it now. 10323 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 10324 ClassDecl->hasInheritedConstructor()) 10325 DeclareImplicitCopyConstructor(ClassDecl); 10326 // For the MS ABI we need to know whether the copy ctor is deleted. A 10327 // prerequisite for deleting the implicit copy ctor is that the class has 10328 // a move ctor or move assignment that is either user-declared or whose 10329 // semantics are inherited from a subobject. FIXME: We should provide a 10330 // more direct way for CodeGen to ask whether the constructor was deleted. 10331 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 10332 (ClassDecl->hasUserDeclaredMoveConstructor() || 10333 ClassDecl->needsOverloadResolutionForMoveConstructor() || 10334 ClassDecl->hasUserDeclaredMoveAssignment() || 10335 ClassDecl->needsOverloadResolutionForMoveAssignment())) 10336 DeclareImplicitCopyConstructor(ClassDecl); 10337 } 10338 10339 if (getLangOpts().CPlusPlus11 && 10340 ClassDecl->needsImplicitMoveConstructor()) { 10341 ++getASTContext().NumImplicitMoveConstructors; 10342 10343 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 10344 ClassDecl->hasInheritedConstructor()) 10345 DeclareImplicitMoveConstructor(ClassDecl); 10346 } 10347 10348 if (ClassDecl->needsImplicitCopyAssignment()) { 10349 ++getASTContext().NumImplicitCopyAssignmentOperators; 10350 10351 // If we have a dynamic class, then the copy assignment operator may be 10352 // virtual, so we have to declare it immediately. This ensures that, e.g., 10353 // it shows up in the right place in the vtable and that we diagnose 10354 // problems with the implicit exception specification. 10355 if (ClassDecl->isDynamicClass() || 10356 ClassDecl->needsOverloadResolutionForCopyAssignment() || 10357 ClassDecl->hasInheritedAssignment()) 10358 DeclareImplicitCopyAssignment(ClassDecl); 10359 } 10360 10361 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 10362 ++getASTContext().NumImplicitMoveAssignmentOperators; 10363 10364 // Likewise for the move assignment operator. 10365 if (ClassDecl->isDynamicClass() || 10366 ClassDecl->needsOverloadResolutionForMoveAssignment() || 10367 ClassDecl->hasInheritedAssignment()) 10368 DeclareImplicitMoveAssignment(ClassDecl); 10369 } 10370 10371 if (ClassDecl->needsImplicitDestructor()) { 10372 ++getASTContext().NumImplicitDestructors; 10373 10374 // If we have a dynamic class, then the destructor may be virtual, so we 10375 // have to declare the destructor immediately. This ensures that, e.g., it 10376 // shows up in the right place in the vtable and that we diagnose problems 10377 // with the implicit exception specification. 10378 if (ClassDecl->isDynamicClass() || 10379 ClassDecl->needsOverloadResolutionForDestructor()) 10380 DeclareImplicitDestructor(ClassDecl); 10381 } 10382 } 10383 10384 // C++2a [class.compare.default]p3: 10385 // If the member-specification does not explicitly declare any member or 10386 // friend named operator==, an == operator function is declared implicitly 10387 // for each defaulted three-way comparison operator function defined in 10388 // the member-specification 10389 // FIXME: Consider doing this lazily. 10390 // We do this during the initial parse for a class template, not during 10391 // instantiation, so that we can handle unqualified lookups for 'operator==' 10392 // when parsing the template. 10393 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 10394 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 10395 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 10396 DefaultedSpaceships); 10397 for (auto *FD : DefaultedSpaceships) 10398 DeclareImplicitEqualityComparison(ClassDecl, FD); 10399 } 10400} 10401 10402unsigned 10403Sema::ActOnReenterTemplateScope(Decl *D, 10404 llvm::function_ref<Scope *()> EnterScope) { 10405 if (!D) 10406 return 0; 10407 AdjustDeclIfTemplate(D); 10408 10409 // In order to get name lookup right, reenter template scopes in order from 10410 // outermost to innermost. 10411 SmallVector<TemplateParameterList *, 4> ParameterLists; 10412 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 10413 10414 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 10415 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 10416 ParameterLists.push_back(DD->getTemplateParameterList(i)); 10417 10418 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10419 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 10420 ParameterLists.push_back(FTD->getTemplateParameters()); 10421 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10422 LookupDC = VD->getDeclContext(); 10423 10424 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 10425 ParameterLists.push_back(VTD->getTemplateParameters()); 10426 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 10427 ParameterLists.push_back(PSD->getTemplateParameters()); 10428 } 10429 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10430 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 10431 ParameterLists.push_back(TD->getTemplateParameterList(i)); 10432 10433 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 10434 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 10435 ParameterLists.push_back(CTD->getTemplateParameters()); 10436 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 10437 ParameterLists.push_back(PSD->getTemplateParameters()); 10438 } 10439 } 10440 // FIXME: Alias declarations and concepts. 10441 10442 unsigned Count = 0; 10443 Scope *InnermostTemplateScope = nullptr; 10444 for (TemplateParameterList *Params : ParameterLists) { 10445 // Ignore explicit specializations; they don't contribute to the template 10446 // depth. 10447 if (Params->size() == 0) 10448 continue; 10449 10450 InnermostTemplateScope = EnterScope(); 10451 for (NamedDecl *Param : *Params) { 10452 if (Param->getDeclName()) { 10453 InnermostTemplateScope->AddDecl(Param); 10454 IdResolver.AddDecl(Param); 10455 } 10456 } 10457 ++Count; 10458 } 10459 10460 // Associate the new template scopes with the corresponding entities. 10461 if (InnermostTemplateScope) { 10462 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", 10462, __extension__ __PRETTY_FUNCTION__
))
; 10463 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10464 } 10465 10466 return Count; 10467} 10468 10469void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10470 if (!RecordD) return; 10471 AdjustDeclIfTemplate(RecordD); 10472 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10473 PushDeclContext(S, Record); 10474} 10475 10476void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10477 if (!RecordD) return; 10478 PopDeclContext(); 10479} 10480 10481/// This is used to implement the constant expression evaluation part of the 10482/// attribute enable_if extension. There is nothing in standard C++ which would 10483/// require reentering parameters. 10484void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10485 if (!Param) 10486 return; 10487 10488 S->AddDecl(Param); 10489 if (Param->getDeclName()) 10490 IdResolver.AddDecl(Param); 10491} 10492 10493/// ActOnStartDelayedCXXMethodDeclaration - We have completed 10494/// parsing a top-level (non-nested) C++ class, and we are now 10495/// parsing those parts of the given Method declaration that could 10496/// not be parsed earlier (C++ [class.mem]p2), such as default 10497/// arguments. This action should enter the scope of the given 10498/// Method declaration as if we had just parsed the qualified method 10499/// name. However, it should not bring the parameters into scope; 10500/// that will be performed by ActOnDelayedCXXMethodParameter. 10501void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10502} 10503 10504/// ActOnDelayedCXXMethodParameter - We've already started a delayed 10505/// C++ method declaration. We're (re-)introducing the given 10506/// function parameter into scope for use in parsing later parts of 10507/// the method declaration. For example, we could see an 10508/// ActOnParamDefaultArgument event for this parameter. 10509void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10510 if (!ParamD) 10511 return; 10512 10513 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10514 10515 S->AddDecl(Param); 10516 if (Param->getDeclName()) 10517 IdResolver.AddDecl(Param); 10518} 10519 10520/// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10521/// processing the delayed method declaration for Method. The method 10522/// declaration is now considered finished. There may be a separate 10523/// ActOnStartOfFunctionDef action later (not necessarily 10524/// immediately!) for this method, if it was also defined inside the 10525/// class body. 10526void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10527 if (!MethodD) 10528 return; 10529 10530 AdjustDeclIfTemplate(MethodD); 10531 10532 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10533 10534 // Now that we have our default arguments, check the constructor 10535 // again. It could produce additional diagnostics or affect whether 10536 // the class has implicitly-declared destructors, among other 10537 // things. 10538 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10539 CheckConstructor(Constructor); 10540 10541 // Check the default arguments, which we may have added. 10542 if (!Method->isInvalidDecl()) 10543 CheckCXXDefaultArguments(Method); 10544} 10545 10546// Emit the given diagnostic for each non-address-space qualifier. 10547// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10548static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10549 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10550 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10551 bool DiagOccured = false; 10552 FTI.MethodQualifiers->forEachQualifier( 10553 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10554 SourceLocation SL) { 10555 // This diagnostic should be emitted on any qualifier except an addr 10556 // space qualifier. However, forEachQualifier currently doesn't visit 10557 // addr space qualifiers, so there's no way to write this condition 10558 // right now; we just diagnose on everything. 10559 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10560 DiagOccured = true; 10561 }); 10562 if (DiagOccured) 10563 D.setInvalidType(); 10564 } 10565} 10566 10567/// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10568/// the well-formedness of the constructor declarator @p D with type @p 10569/// R. If there are any errors in the declarator, this routine will 10570/// emit diagnostics and set the invalid bit to true. In any case, the type 10571/// will be updated to reflect a well-formed type for the constructor and 10572/// returned. 10573QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10574 StorageClass &SC) { 10575 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10576 10577 // C++ [class.ctor]p3: 10578 // A constructor shall not be virtual (10.3) or static (9.4). A 10579 // constructor can be invoked for a const, volatile or const 10580 // volatile object. A constructor shall not be declared const, 10581 // volatile, or const volatile (9.3.2). 10582 if (isVirtual) { 10583 if (!D.isInvalidType()) 10584 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10585 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10586 << SourceRange(D.getIdentifierLoc()); 10587 D.setInvalidType(); 10588 } 10589 if (SC == SC_Static) { 10590 if (!D.isInvalidType()) 10591 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10592 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10593 << SourceRange(D.getIdentifierLoc()); 10594 D.setInvalidType(); 10595 SC = SC_None; 10596 } 10597 10598 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10599 diagnoseIgnoredQualifiers( 10600 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10601 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10602 D.getDeclSpec().getRestrictSpecLoc(), 10603 D.getDeclSpec().getAtomicSpecLoc()); 10604 D.setInvalidType(); 10605 } 10606 10607 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10608 10609 // C++0x [class.ctor]p4: 10610 // A constructor shall not be declared with a ref-qualifier. 10611 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10612 if (FTI.hasRefQualifier()) { 10613 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10614 << FTI.RefQualifierIsLValueRef 10615 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10616 D.setInvalidType(); 10617 } 10618 10619 // Rebuild the function type "R" without any type qualifiers (in 10620 // case any of the errors above fired) and with "void" as the 10621 // return type, since constructors don't have return types. 10622 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10623 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10624 return R; 10625 10626 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10627 EPI.TypeQuals = Qualifiers(); 10628 EPI.RefQualifier = RQ_None; 10629 10630 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10631} 10632 10633/// CheckConstructor - Checks a fully-formed constructor for 10634/// well-formedness, issuing any diagnostics required. Returns true if 10635/// the constructor declarator is invalid. 10636void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10637 CXXRecordDecl *ClassDecl 10638 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10639 if (!ClassDecl) 10640 return Constructor->setInvalidDecl(); 10641 10642 // C++ [class.copy]p3: 10643 // A declaration of a constructor for a class X is ill-formed if 10644 // its first parameter is of type (optionally cv-qualified) X and 10645 // either there are no other parameters or else all other 10646 // parameters have default arguments. 10647 if (!Constructor->isInvalidDecl() && 10648 Constructor->hasOneParamOrDefaultArgs() && 10649 Constructor->getTemplateSpecializationKind() != 10650 TSK_ImplicitInstantiation) { 10651 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10652 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10653 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10654 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10655 const char *ConstRef 10656 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10657 : " const &"; 10658 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10659 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10660 10661 // FIXME: Rather that making the constructor invalid, we should endeavor 10662 // to fix the type. 10663 Constructor->setInvalidDecl(); 10664 } 10665 } 10666} 10667 10668/// CheckDestructor - Checks a fully-formed destructor definition for 10669/// well-formedness, issuing any diagnostics required. Returns true 10670/// on error. 10671bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10672 CXXRecordDecl *RD = Destructor->getParent(); 10673 10674 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10675 SourceLocation Loc; 10676 10677 if (!Destructor->isImplicit()) 10678 Loc = Destructor->getLocation(); 10679 else 10680 Loc = RD->getLocation(); 10681 10682 // If we have a virtual destructor, look up the deallocation function 10683 if (FunctionDecl *OperatorDelete = 10684 FindDeallocationFunctionForDestructor(Loc, RD)) { 10685 Expr *ThisArg = nullptr; 10686 10687 // If the notional 'delete this' expression requires a non-trivial 10688 // conversion from 'this' to the type of a destroying operator delete's 10689 // first parameter, perform that conversion now. 10690 if (OperatorDelete->isDestroyingOperatorDelete()) { 10691 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10692 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10693 // C++ [class.dtor]p13: 10694 // ... as if for the expression 'delete this' appearing in a 10695 // non-virtual destructor of the destructor's class. 10696 ContextRAII SwitchContext(*this, Destructor); 10697 ExprResult This = 10698 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10699 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", 10699, __extension__ __PRETTY_FUNCTION__
))
; 10700 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10701 if (This.isInvalid()) { 10702 // FIXME: Register this as a context note so that it comes out 10703 // in the right order. 10704 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10705 return true; 10706 } 10707 ThisArg = This.get(); 10708 } 10709 } 10710 10711 DiagnoseUseOfDecl(OperatorDelete, Loc); 10712 MarkFunctionReferenced(Loc, OperatorDelete); 10713 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10714 } 10715 } 10716 10717 return false; 10718} 10719 10720/// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10721/// the well-formednes of the destructor declarator @p D with type @p 10722/// R. If there are any errors in the declarator, this routine will 10723/// emit diagnostics and set the declarator to invalid. Even if this happens, 10724/// will be updated to reflect a well-formed type for the destructor and 10725/// returned. 10726QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10727 StorageClass& SC) { 10728 // C++ [class.dtor]p1: 10729 // [...] A typedef-name that names a class is a class-name 10730 // (7.1.3); however, a typedef-name that names a class shall not 10731 // be used as the identifier in the declarator for a destructor 10732 // declaration. 10733 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10734 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10735 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10736 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10737 else if (const TemplateSpecializationType *TST = 10738 DeclaratorType->getAs<TemplateSpecializationType>()) 10739 if (TST->isTypeAlias()) 10740 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10741 << DeclaratorType << 1; 10742 10743 // C++ [class.dtor]p2: 10744 // A destructor is used to destroy objects of its class type. A 10745 // destructor takes no parameters, and no return type can be 10746 // specified for it (not even void). The address of a destructor 10747 // shall not be taken. A destructor shall not be static. A 10748 // destructor can be invoked for a const, volatile or const 10749 // volatile object. A destructor shall not be declared const, 10750 // volatile or const volatile (9.3.2). 10751 if (SC == SC_Static) { 10752 if (!D.isInvalidType()) 10753 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10754 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10755 << SourceRange(D.getIdentifierLoc()) 10756 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10757 10758 SC = SC_None; 10759 } 10760 if (!D.isInvalidType()) { 10761 // Destructors don't have return types, but the parser will 10762 // happily parse something like: 10763 // 10764 // class X { 10765 // float ~X(); 10766 // }; 10767 // 10768 // The return type will be eliminated later. 10769 if (D.getDeclSpec().hasTypeSpecifier()) 10770 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10771 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10772 << SourceRange(D.getIdentifierLoc()); 10773 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10774 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10775 SourceLocation(), 10776 D.getDeclSpec().getConstSpecLoc(), 10777 D.getDeclSpec().getVolatileSpecLoc(), 10778 D.getDeclSpec().getRestrictSpecLoc(), 10779 D.getDeclSpec().getAtomicSpecLoc()); 10780 D.setInvalidType(); 10781 } 10782 } 10783 10784 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10785 10786 // C++0x [class.dtor]p2: 10787 // A destructor shall not be declared with a ref-qualifier. 10788 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10789 if (FTI.hasRefQualifier()) { 10790 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10791 << FTI.RefQualifierIsLValueRef 10792 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10793 D.setInvalidType(); 10794 } 10795 10796 // Make sure we don't have any parameters. 10797 if (FTIHasNonVoidParameters(FTI)) { 10798 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10799 10800 // Delete the parameters. 10801 FTI.freeParams(); 10802 D.setInvalidType(); 10803 } 10804 10805 // Make sure the destructor isn't variadic. 10806 if (FTI.isVariadic) { 10807 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10808 D.setInvalidType(); 10809 } 10810 10811 // Rebuild the function type "R" without any type qualifiers or 10812 // parameters (in case any of the errors above fired) and with 10813 // "void" as the return type, since destructors don't have return 10814 // types. 10815 if (!D.isInvalidType()) 10816 return R; 10817 10818 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10819 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10820 EPI.Variadic = false; 10821 EPI.TypeQuals = Qualifiers(); 10822 EPI.RefQualifier = RQ_None; 10823 return Context.getFunctionType(Context.VoidTy, std::nullopt, EPI); 10824} 10825 10826static void extendLeft(SourceRange &R, SourceRange Before) { 10827 if (Before.isInvalid()) 10828 return; 10829 R.setBegin(Before.getBegin()); 10830 if (R.getEnd().isInvalid()) 10831 R.setEnd(Before.getEnd()); 10832} 10833 10834static void extendRight(SourceRange &R, SourceRange After) { 10835 if (After.isInvalid()) 10836 return; 10837 if (R.getBegin().isInvalid()) 10838 R.setBegin(After.getBegin()); 10839 R.setEnd(After.getEnd()); 10840} 10841 10842/// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10843/// well-formednes of the conversion function declarator @p D with 10844/// type @p R. If there are any errors in the declarator, this routine 10845/// will emit diagnostics and return true. Otherwise, it will return 10846/// false. Either way, the type @p R will be updated to reflect a 10847/// well-formed type for the conversion operator. 10848void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10849 StorageClass& SC) { 10850 // C++ [class.conv.fct]p1: 10851 // Neither parameter types nor return type can be specified. The 10852 // type of a conversion function (8.3.5) is "function taking no 10853 // parameter returning conversion-type-id." 10854 if (SC == SC_Static) { 10855 if (!D.isInvalidType()) 10856 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10857 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10858 << D.getName().getSourceRange(); 10859 D.setInvalidType(); 10860 SC = SC_None; 10861 } 10862 10863 TypeSourceInfo *ConvTSI = nullptr; 10864 QualType ConvType = 10865 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10866 10867 const DeclSpec &DS = D.getDeclSpec(); 10868 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10869 // Conversion functions don't have return types, but the parser will 10870 // happily parse something like: 10871 // 10872 // class X { 10873 // float operator bool(); 10874 // }; 10875 // 10876 // The return type will be changed later anyway. 10877 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10878 << SourceRange(DS.getTypeSpecTypeLoc()) 10879 << SourceRange(D.getIdentifierLoc()); 10880 D.setInvalidType(); 10881 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10882 // It's also plausible that the user writes type qualifiers in the wrong 10883 // place, such as: 10884 // struct S { const operator int(); }; 10885 // FIXME: we could provide a fixit to move the qualifiers onto the 10886 // conversion type. 10887 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10888 << SourceRange(D.getIdentifierLoc()) << 0; 10889 D.setInvalidType(); 10890 } 10891 10892 const auto *Proto = R->castAs<FunctionProtoType>(); 10893 10894 // Make sure we don't have any parameters. 10895 if (Proto->getNumParams() > 0) { 10896 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10897 10898 // Delete the parameters. 10899 D.getFunctionTypeInfo().freeParams(); 10900 D.setInvalidType(); 10901 } else if (Proto->isVariadic()) { 10902 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10903 D.setInvalidType(); 10904 } 10905 10906 // Diagnose "&operator bool()" and other such nonsense. This 10907 // is actually a gcc extension which we don't support. 10908 if (Proto->getReturnType() != ConvType) { 10909 bool NeedsTypedef = false; 10910 SourceRange Before, After; 10911 10912 // Walk the chunks and extract information on them for our diagnostic. 10913 bool PastFunctionChunk = false; 10914 for (auto &Chunk : D.type_objects()) { 10915 switch (Chunk.Kind) { 10916 case DeclaratorChunk::Function: 10917 if (!PastFunctionChunk) { 10918 if (Chunk.Fun.HasTrailingReturnType) { 10919 TypeSourceInfo *TRT = nullptr; 10920 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10921 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10922 } 10923 PastFunctionChunk = true; 10924 break; 10925 } 10926 [[fallthrough]]; 10927 case DeclaratorChunk::Array: 10928 NeedsTypedef = true; 10929 extendRight(After, Chunk.getSourceRange()); 10930 break; 10931 10932 case DeclaratorChunk::Pointer: 10933 case DeclaratorChunk::BlockPointer: 10934 case DeclaratorChunk::Reference: 10935 case DeclaratorChunk::MemberPointer: 10936 case DeclaratorChunk::Pipe: 10937 extendLeft(Before, Chunk.getSourceRange()); 10938 break; 10939 10940 case DeclaratorChunk::Paren: 10941 extendLeft(Before, Chunk.Loc); 10942 extendRight(After, Chunk.EndLoc); 10943 break; 10944 } 10945 } 10946 10947 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10948 After.isValid() ? After.getBegin() : 10949 D.getIdentifierLoc(); 10950 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10951 DB << Before << After; 10952 10953 if (!NeedsTypedef) { 10954 DB << /*don't need a typedef*/0; 10955 10956 // If we can provide a correct fix-it hint, do so. 10957 if (After.isInvalid() && ConvTSI) { 10958 SourceLocation InsertLoc = 10959 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10960 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10961 << FixItHint::CreateInsertionFromRange( 10962 InsertLoc, CharSourceRange::getTokenRange(Before)) 10963 << FixItHint::CreateRemoval(Before); 10964 } 10965 } else if (!Proto->getReturnType()->isDependentType()) { 10966 DB << /*typedef*/1 << Proto->getReturnType(); 10967 } else if (getLangOpts().CPlusPlus11) { 10968 DB << /*alias template*/2 << Proto->getReturnType(); 10969 } else { 10970 DB << /*might not be fixable*/3; 10971 } 10972 10973 // Recover by incorporating the other type chunks into the result type. 10974 // Note, this does *not* change the name of the function. This is compatible 10975 // with the GCC extension: 10976 // struct S { &operator int(); } s; 10977 // int &r = s.operator int(); // ok in GCC 10978 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10979 ConvType = Proto->getReturnType(); 10980 } 10981 10982 // C++ [class.conv.fct]p4: 10983 // The conversion-type-id shall not represent a function type nor 10984 // an array type. 10985 if (ConvType->isArrayType()) { 10986 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10987 ConvType = Context.getPointerType(ConvType); 10988 D.setInvalidType(); 10989 } else if (ConvType->isFunctionType()) { 10990 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10991 ConvType = Context.getPointerType(ConvType); 10992 D.setInvalidType(); 10993 } 10994 10995 // Rebuild the function type "R" without any parameters (in case any 10996 // of the errors above fired) and with the conversion type as the 10997 // return type. 10998 if (D.isInvalidType()) 10999 R = Context.getFunctionType(ConvType, std::nullopt, 11000 Proto->getExtProtoInfo()); 11001 11002 // C++0x explicit conversion operators. 11003 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 11004 Diag(DS.getExplicitSpecLoc(), 11005 getLangOpts().CPlusPlus11 11006 ? diag::warn_cxx98_compat_explicit_conversion_functions 11007 : diag::ext_explicit_conversion_functions) 11008 << SourceRange(DS.getExplicitSpecRange()); 11009} 11010 11011/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 11012/// the declaration of the given C++ conversion function. This routine 11013/// is responsible for recording the conversion function in the C++ 11014/// class, if possible. 11015Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 11016 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", 11016, __extension__ __PRETTY_FUNCTION__
))
; 11017 11018 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 11019 11020 // Make sure we aren't redeclaring the conversion function. 11021 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 11022 // C++ [class.conv.fct]p1: 11023 // [...] A conversion function is never used to convert a 11024 // (possibly cv-qualified) object to the (possibly cv-qualified) 11025 // same object type (or a reference to it), to a (possibly 11026 // cv-qualified) base class of that type (or a reference to it), 11027 // or to (possibly cv-qualified) void. 11028 QualType ClassType 11029 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11030 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 11031 ConvType = ConvTypeRef->getPointeeType(); 11032 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 11033 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 11034 /* Suppress diagnostics for instantiations. */; 11035 else if (Conversion->size_overridden_methods() != 0) 11036 /* Suppress diagnostics for overriding virtual function in a base class. */; 11037 else if (ConvType->isRecordType()) { 11038 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 11039 if (ConvType == ClassType) 11040 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 11041 << ClassType; 11042 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 11043 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 11044 << ClassType << ConvType; 11045 } else if (ConvType->isVoidType()) { 11046 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 11047 << ClassType << ConvType; 11048 } 11049 11050 if (FunctionTemplateDecl *ConversionTemplate 11051 = Conversion->getDescribedFunctionTemplate()) 11052 return ConversionTemplate; 11053 11054 return Conversion; 11055} 11056 11057namespace { 11058/// Utility class to accumulate and print a diagnostic listing the invalid 11059/// specifier(s) on a declaration. 11060struct BadSpecifierDiagnoser { 11061 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 11062 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 11063 ~BadSpecifierDiagnoser() { 11064 Diagnostic << Specifiers; 11065 } 11066 11067 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 11068 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 11069 } 11070 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 11071 return check(SpecLoc, 11072 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 11073 } 11074 void check(SourceLocation SpecLoc, const char *Spec) { 11075 if (SpecLoc.isInvalid()) return; 11076 Diagnostic << SourceRange(SpecLoc, SpecLoc); 11077 if (!Specifiers.empty()) Specifiers += " "; 11078 Specifiers += Spec; 11079 } 11080 11081 Sema &S; 11082 Sema::SemaDiagnosticBuilder Diagnostic; 11083 std::string Specifiers; 11084}; 11085} 11086 11087/// Check the validity of a declarator that we parsed for a deduction-guide. 11088/// These aren't actually declarators in the grammar, so we need to check that 11089/// the user didn't specify any pieces that are not part of the deduction-guide 11090/// grammar. 11091void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 11092 StorageClass &SC) { 11093 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 11094 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 11095 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", 11095, __extension__ __PRETTY_FUNCTION__
))
; 11096 11097 // C++ [temp.deduct.guide]p3: 11098 // A deduction-gide shall be declared in the same scope as the 11099 // corresponding class template. 11100 if (!CurContext->getRedeclContext()->Equals( 11101 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 11102 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 11103 << GuidedTemplateDecl; 11104 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 11105 } 11106 11107 auto &DS = D.getMutableDeclSpec(); 11108 // We leave 'friend' and 'virtual' to be rejected in the normal way. 11109 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 11110 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 11111 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 11112 BadSpecifierDiagnoser Diagnoser( 11113 *this, D.getIdentifierLoc(), 11114 diag::err_deduction_guide_invalid_specifier); 11115 11116 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 11117 DS.ClearStorageClassSpecs(); 11118 SC = SC_None; 11119 11120 // 'explicit' is permitted. 11121 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 11122 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 11123 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 11124 DS.ClearConstexprSpec(); 11125 11126 Diagnoser.check(DS.getConstSpecLoc(), "const"); 11127 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 11128 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 11129 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 11130 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 11131 DS.ClearTypeQualifiers(); 11132 11133 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 11134 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 11135 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 11136 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 11137 DS.ClearTypeSpecType(); 11138 } 11139 11140 if (D.isInvalidType()) 11141 return; 11142 11143 // Check the declarator is simple enough. 11144 bool FoundFunction = false; 11145 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 11146 if (Chunk.Kind == DeclaratorChunk::Paren) 11147 continue; 11148 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 11149 Diag(D.getDeclSpec().getBeginLoc(), 11150 diag::err_deduction_guide_with_complex_decl) 11151 << D.getSourceRange(); 11152 break; 11153 } 11154 if (!Chunk.Fun.hasTrailingReturnType()) { 11155 Diag(D.getName().getBeginLoc(), 11156 diag::err_deduction_guide_no_trailing_return_type); 11157 break; 11158 } 11159 11160 // Check that the return type is written as a specialization of 11161 // the template specified as the deduction-guide's name. 11162 // The template name may not be qualified. [temp.deduct.guide] 11163 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 11164 TypeSourceInfo *TSI = nullptr; 11165 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 11166 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", 11166, __extension__ __PRETTY_FUNCTION__
))
; 11167 bool AcceptableReturnType = false; 11168 bool MightInstantiateToSpecialization = false; 11169 if (auto RetTST = 11170 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) { 11171 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 11172 bool TemplateMatches = 11173 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 11174 auto TKind = SpecifiedName.getKind(); 11175 // A Using TemplateName can't actually be valid (either it's qualified, or 11176 // we're in the wrong scope). But we have diagnosed these problems 11177 // already. 11178 bool SimplyWritten = TKind == TemplateName::Template || 11179 TKind == TemplateName::UsingTemplate; 11180 if (SimplyWritten && TemplateMatches) 11181 AcceptableReturnType = true; 11182 else { 11183 // This could still instantiate to the right type, unless we know it 11184 // names the wrong class template. 11185 auto *TD = SpecifiedName.getAsTemplateDecl(); 11186 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 11187 !TemplateMatches); 11188 } 11189 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 11190 MightInstantiateToSpecialization = true; 11191 } 11192 11193 if (!AcceptableReturnType) { 11194 Diag(TSI->getTypeLoc().getBeginLoc(), 11195 diag::err_deduction_guide_bad_trailing_return_type) 11196 << GuidedTemplate << TSI->getType() 11197 << MightInstantiateToSpecialization 11198 << TSI->getTypeLoc().getSourceRange(); 11199 } 11200 11201 // Keep going to check that we don't have any inner declarator pieces (we 11202 // could still have a function returning a pointer to a function). 11203 FoundFunction = true; 11204 } 11205 11206 if (D.isFunctionDefinition()) 11207 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 11208} 11209 11210//===----------------------------------------------------------------------===// 11211// Namespace Handling 11212//===----------------------------------------------------------------------===// 11213 11214/// Diagnose a mismatch in 'inline' qualifiers when a namespace is 11215/// reopened. 11216static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 11217 SourceLocation Loc, 11218 IdentifierInfo *II, bool *IsInline, 11219 NamespaceDecl *PrevNS) { 11220 assert(*IsInline != PrevNS->isInline())(static_cast <bool> (*IsInline != PrevNS->isInline()
) ? void (0) : __assert_fail ("*IsInline != PrevNS->isInline()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 11220, __extension__ __PRETTY_FUNCTION__
))
; 11221 11222 // 'inline' must appear on the original definition, but not necessarily 11223 // on all extension definitions, so the note should point to the first 11224 // definition to avoid confusion. 11225 PrevNS = PrevNS->getFirstDecl(); 11226 11227 if (PrevNS->isInline()) 11228 // The user probably just forgot the 'inline', so suggest that it 11229 // be added back. 11230 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 11231 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 11232 else 11233 S.Diag(Loc, diag::err_inline_namespace_mismatch); 11234 11235 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 11236 *IsInline = PrevNS->isInline(); 11237} 11238 11239/// ActOnStartNamespaceDef - This is called at the start of a namespace 11240/// definition. 11241Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, 11242 SourceLocation InlineLoc, 11243 SourceLocation NamespaceLoc, 11244 SourceLocation IdentLoc, IdentifierInfo *II, 11245 SourceLocation LBrace, 11246 const ParsedAttributesView &AttrList, 11247 UsingDirectiveDecl *&UD, bool IsNested) { 11248 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 11249 // For anonymous namespace, take the location of the left brace. 11250 SourceLocation Loc = II ? IdentLoc : LBrace; 11251 bool IsInline = InlineLoc.isValid(); 11252 bool IsInvalid = false; 11253 bool IsStd = false; 11254 bool AddToKnown = false; 11255 Scope *DeclRegionScope = NamespcScope->getParent(); 11256 11257 NamespaceDecl *PrevNS = nullptr; 11258 if (II) { 11259 // C++ [namespace.def]p2: 11260 // The identifier in an original-namespace-definition shall not 11261 // have been previously defined in the declarative region in 11262 // which the original-namespace-definition appears. The 11263 // identifier in an original-namespace-definition is the name of 11264 // the namespace. Subsequently in that declarative region, it is 11265 // treated as an original-namespace-name. 11266 // 11267 // Since namespace names are unique in their scope, and we don't 11268 // look through using directives, just look for any ordinary names 11269 // as if by qualified name lookup. 11270 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 11271 ForExternalRedeclaration); 11272 LookupQualifiedName(R, CurContext->getRedeclContext()); 11273 NamedDecl *PrevDecl = 11274 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 11275 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 11276 11277 if (PrevNS) { 11278 // This is an extended namespace definition. 11279 if (IsInline != PrevNS->isInline()) 11280 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 11281 &IsInline, PrevNS); 11282 } else if (PrevDecl) { 11283 // This is an invalid name redefinition. 11284 Diag(Loc, diag::err_redefinition_different_kind) 11285 << II; 11286 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11287 IsInvalid = true; 11288 // Continue on to push Namespc as current DeclContext and return it. 11289 } else if (II->isStr("std") && 11290 CurContext->getRedeclContext()->isTranslationUnit()) { 11291 // This is the first "real" definition of the namespace "std", so update 11292 // our cache of the "std" namespace to point at this definition. 11293 PrevNS = getStdNamespace(); 11294 IsStd = true; 11295 AddToKnown = !IsInline; 11296 } else { 11297 // We've seen this namespace for the first time. 11298 AddToKnown = !IsInline; 11299 } 11300 } else { 11301 // Anonymous namespaces. 11302 11303 // Determine whether the parent already has an anonymous namespace. 11304 DeclContext *Parent = CurContext->getRedeclContext(); 11305 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11306 PrevNS = TU->getAnonymousNamespace(); 11307 } else { 11308 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 11309 PrevNS = ND->getAnonymousNamespace(); 11310 } 11311 11312 if (PrevNS && IsInline != PrevNS->isInline()) 11313 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 11314 &IsInline, PrevNS); 11315 } 11316 11317 NamespaceDecl *Namespc = NamespaceDecl::Create( 11318 Context, CurContext, IsInline, StartLoc, Loc, II, PrevNS, IsNested); 11319 if (IsInvalid) 11320 Namespc->setInvalidDecl(); 11321 11322 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 11323 AddPragmaAttributes(DeclRegionScope, Namespc); 11324 11325 // FIXME: Should we be merging attributes? 11326 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 11327 PushNamespaceVisibilityAttr(Attr, Loc); 11328 11329 if (IsStd) 11330 StdNamespace = Namespc; 11331 if (AddToKnown) 11332 KnownNamespaces[Namespc] = false; 11333 11334 if (II) { 11335 PushOnScopeChains(Namespc, DeclRegionScope); 11336 } else { 11337 // Link the anonymous namespace into its parent. 11338 DeclContext *Parent = CurContext->getRedeclContext(); 11339 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11340 TU->setAnonymousNamespace(Namespc); 11341 } else { 11342 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 11343 } 11344 11345 CurContext->addDecl(Namespc); 11346 11347 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 11348 // behaves as if it were replaced by 11349 // namespace unique { /* empty body */ } 11350 // using namespace unique; 11351 // namespace unique { namespace-body } 11352 // where all occurrences of 'unique' in a translation unit are 11353 // replaced by the same identifier and this identifier differs 11354 // from all other identifiers in the entire program. 11355 11356 // We just create the namespace with an empty name and then add an 11357 // implicit using declaration, just like the standard suggests. 11358 // 11359 // CodeGen enforces the "universally unique" aspect by giving all 11360 // declarations semantically contained within an anonymous 11361 // namespace internal linkage. 11362 11363 if (!PrevNS) { 11364 UD = UsingDirectiveDecl::Create(Context, Parent, 11365 /* 'using' */ LBrace, 11366 /* 'namespace' */ SourceLocation(), 11367 /* qualifier */ NestedNameSpecifierLoc(), 11368 /* identifier */ SourceLocation(), 11369 Namespc, 11370 /* Ancestor */ Parent); 11371 UD->setImplicit(); 11372 Parent->addDecl(UD); 11373 } 11374 } 11375 11376 ActOnDocumentableDecl(Namespc); 11377 11378 // Although we could have an invalid decl (i.e. the namespace name is a 11379 // redefinition), push it as current DeclContext and try to continue parsing. 11380 // FIXME: We should be able to push Namespc here, so that the each DeclContext 11381 // for the namespace has the declarations that showed up in that particular 11382 // namespace definition. 11383 PushDeclContext(NamespcScope, Namespc); 11384 return Namespc; 11385} 11386 11387/// getNamespaceDecl - Returns the namespace a decl represents. If the decl 11388/// is a namespace alias, returns the namespace it points to. 11389static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 11390 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 11391 return AD->getNamespace(); 11392 return dyn_cast_or_null<NamespaceDecl>(D); 11393} 11394 11395/// ActOnFinishNamespaceDef - This callback is called after a namespace is 11396/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 11397void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 11398 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 11399 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", 11399, __extension__ __PRETTY_FUNCTION__
))
; 11400 Namespc->setRBraceLoc(RBrace); 11401 PopDeclContext(); 11402 if (Namespc->hasAttr<VisibilityAttr>()) 11403 PopPragmaVisibility(true, RBrace); 11404 // If this namespace contains an export-declaration, export it now. 11405 if (DeferredExportedNamespaces.erase(Namespc)) 11406 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 11407} 11408 11409CXXRecordDecl *Sema::getStdBadAlloc() const { 11410 return cast_or_null<CXXRecordDecl>( 11411 StdBadAlloc.get(Context.getExternalSource())); 11412} 11413 11414EnumDecl *Sema::getStdAlignValT() const { 11415 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 11416} 11417 11418NamespaceDecl *Sema::getStdNamespace() const { 11419 return cast_or_null<NamespaceDecl>( 11420 StdNamespace.get(Context.getExternalSource())); 11421} 11422namespace { 11423 11424enum UnsupportedSTLSelect { 11425 USS_InvalidMember, 11426 USS_MissingMember, 11427 USS_NonTrivial, 11428 USS_Other 11429}; 11430 11431struct InvalidSTLDiagnoser { 11432 Sema &S; 11433 SourceLocation Loc; 11434 QualType TyForDiags; 11435 11436 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11437 const VarDecl *VD = nullptr) { 11438 { 11439 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11440 << TyForDiags << ((int)Sel); 11441 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11442 assert(!Name.empty())(static_cast <bool> (!Name.empty()) ? void (0) : __assert_fail
("!Name.empty()", "clang/lib/Sema/SemaDeclCXX.cpp", 11442, __extension__
__PRETTY_FUNCTION__))
; 11443 D << Name; 11444 } 11445 } 11446 if (Sel == USS_InvalidMember) { 11447 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11448 << VD << VD->getSourceRange(); 11449 } 11450 return QualType(); 11451 } 11452}; 11453} // namespace 11454 11455QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11456 SourceLocation Loc, 11457 ComparisonCategoryUsage Usage) { 11458 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", 11459, __extension__ __PRETTY_FUNCTION__
))
11459 "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", 11459, __extension__ __PRETTY_FUNCTION__
))
; 11460 11461 // Use an elaborated type for diagnostics which has a name containing the 11462 // prepended 'std' namespace but not any inline namespace names. 11463 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11464 auto *NNS = 11465 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11466 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11467 }; 11468 11469 // Check if we've already successfully checked the comparison category type 11470 // before. If so, skip checking it again. 11471 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11472 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11473 // The only thing we need to check is that the type has a reachable 11474 // definition in the current context. 11475 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11476 return QualType(); 11477 11478 return Info->getType(); 11479 } 11480 11481 // If lookup failed 11482 if (!Info) { 11483 std::string NameForDiags = "std::"; 11484 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11485 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11486 << NameForDiags << (int)Usage; 11487 return QualType(); 11488 } 11489 11490 assert(Info->Kind == Kind)(static_cast <bool> (Info->Kind == Kind) ? void (0) :
__assert_fail ("Info->Kind == Kind", "clang/lib/Sema/SemaDeclCXX.cpp"
, 11490, __extension__ __PRETTY_FUNCTION__))
; 11491 assert(Info->Record)(static_cast <bool> (Info->Record) ? void (0) : __assert_fail
("Info->Record", "clang/lib/Sema/SemaDeclCXX.cpp", 11491,
__extension__ __PRETTY_FUNCTION__))
; 11492 11493 // Update the Record decl in case we encountered a forward declaration on our 11494 // first pass. FIXME: This is a bit of a hack. 11495 if (Info->Record->hasDefinition()) 11496 Info->Record = Info->Record->getDefinition(); 11497 11498 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11499 return QualType(); 11500 11501 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11502 11503 if (!Info->Record->isTriviallyCopyable()) 11504 return UnsupportedSTLError(USS_NonTrivial); 11505 11506 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11507 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11508 // Tolerate empty base classes. 11509 if (Base->isEmpty()) 11510 continue; 11511 // Reject STL implementations which have at least one non-empty base. 11512 return UnsupportedSTLError(); 11513 } 11514 11515 // Check that the STL has implemented the types using a single integer field. 11516 // This expectation allows better codegen for builtin operators. We require: 11517 // (1) The class has exactly one field. 11518 // (2) The field is an integral or enumeration type. 11519 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11520 if (std::distance(FIt, FEnd) != 1 || 11521 !FIt->getType()->isIntegralOrEnumerationType()) { 11522 return UnsupportedSTLError(); 11523 } 11524 11525 // Build each of the require values and store them in Info. 11526 for (ComparisonCategoryResult CCR : 11527 ComparisonCategories::getPossibleResultsForType(Kind)) { 11528 StringRef MemName = ComparisonCategories::getResultString(CCR); 11529 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11530 11531 if (!ValInfo) 11532 return UnsupportedSTLError(USS_MissingMember, MemName); 11533 11534 VarDecl *VD = ValInfo->VD; 11535 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", 11535, __extension__ __PRETTY_FUNCTION__
))
; 11536 11537 // Attempt to diagnose reasons why the STL definition of this type 11538 // might be foobar, including it failing to be a constant expression. 11539 // TODO Handle more ways the lookup or result can be invalid. 11540 if (!VD->isStaticDataMember() || 11541 !VD->isUsableInConstantExpressions(Context)) 11542 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11543 11544 // Attempt to evaluate the var decl as a constant expression and extract 11545 // the value of its first field as a ICE. If this fails, the STL 11546 // implementation is not supported. 11547 if (!ValInfo->hasValidIntValue()) 11548 return UnsupportedSTLError(); 11549 11550 MarkVariableReferenced(Loc, VD); 11551 } 11552 11553 // We've successfully built the required types and expressions. Update 11554 // the cache and return the newly cached value. 11555 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11556 return Info->getType(); 11557} 11558 11559/// Retrieve the special "std" namespace, which may require us to 11560/// implicitly define the namespace. 11561NamespaceDecl *Sema::getOrCreateStdNamespace() { 11562 if (!StdNamespace) { 11563 // The "std" namespace has not yet been defined, so build one implicitly. 11564 StdNamespace = NamespaceDecl::Create( 11565 Context, Context.getTranslationUnitDecl(), 11566 /*Inline=*/false, SourceLocation(), SourceLocation(), 11567 &PP.getIdentifierTable().get("std"), 11568 /*PrevDecl=*/nullptr, /*Nested=*/false); 11569 getStdNamespace()->setImplicit(true); 11570 // We want the created NamespaceDecl to be available for redeclaration 11571 // lookups, but not for regular name lookups. 11572 Context.getTranslationUnitDecl()->addDecl(getStdNamespace()); 11573 getStdNamespace()->clearIdentifierNamespace(); 11574 } 11575 11576 return getStdNamespace(); 11577} 11578 11579bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11580 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", 11581, __extension__ __PRETTY_FUNCTION__
))
11581 "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", 11581, __extension__ __PRETTY_FUNCTION__
))
; 11582 11583 // We're looking for implicit instantiations of 11584 // template <typename E> class std::initializer_list. 11585 11586 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11587 return false; 11588 11589 ClassTemplateDecl *Template = nullptr; 11590 const TemplateArgument *Arguments = nullptr; 11591 11592 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11593 11594 ClassTemplateSpecializationDecl *Specialization = 11595 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11596 if (!Specialization) 11597 return false; 11598 11599 Template = Specialization->getSpecializedTemplate(); 11600 Arguments = Specialization->getTemplateArgs().data(); 11601 } else if (const TemplateSpecializationType *TST = 11602 Ty->getAs<TemplateSpecializationType>()) { 11603 Template = dyn_cast_or_null<ClassTemplateDecl>( 11604 TST->getTemplateName().getAsTemplateDecl()); 11605 Arguments = TST->template_arguments().begin(); 11606 } 11607 if (!Template) 11608 return false; 11609 11610 if (!StdInitializerList) { 11611 // Haven't recognized std::initializer_list yet, maybe this is it. 11612 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11613 if (TemplateClass->getIdentifier() != 11614 &PP.getIdentifierTable().get("initializer_list") || 11615 !getStdNamespace()->InEnclosingNamespaceSetOf( 11616 TemplateClass->getDeclContext())) 11617 return false; 11618 // This is a template called std::initializer_list, but is it the right 11619 // template? 11620 TemplateParameterList *Params = Template->getTemplateParameters(); 11621 if (Params->getMinRequiredArguments() != 1) 11622 return false; 11623 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11624 return false; 11625 11626 // It's the right template. 11627 StdInitializerList = Template; 11628 } 11629 11630 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11631 return false; 11632 11633 // This is an instance of std::initializer_list. Find the argument type. 11634 if (Element) 11635 *Element = Arguments[0].getAsType(); 11636 return true; 11637} 11638 11639static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11640 NamespaceDecl *Std = S.getStdNamespace(); 11641 if (!Std) { 11642 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11643 return nullptr; 11644 } 11645 11646 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11647 Loc, Sema::LookupOrdinaryName); 11648 if (!S.LookupQualifiedName(Result, Std)) { 11649 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11650 return nullptr; 11651 } 11652 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11653 if (!Template) { 11654 Result.suppressDiagnostics(); 11655 // We found something weird. Complain about the first thing we found. 11656 NamedDecl *Found = *Result.begin(); 11657 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11658 return nullptr; 11659 } 11660 11661 // We found some template called std::initializer_list. Now verify that it's 11662 // correct. 11663 TemplateParameterList *Params = Template->getTemplateParameters(); 11664 if (Params->getMinRequiredArguments() != 1 || 11665 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11666 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11667 return nullptr; 11668 } 11669 11670 return Template; 11671} 11672 11673QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11674 if (!StdInitializerList) { 11675 StdInitializerList = LookupStdInitializerList(*this, Loc); 11676 if (!StdInitializerList) 11677 return QualType(); 11678 } 11679 11680 TemplateArgumentListInfo Args(Loc, Loc); 11681 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11682 Context.getTrivialTypeSourceInfo(Element, 11683 Loc))); 11684 return Context.getElaboratedType( 11685 ElaboratedTypeKeyword::ETK_None, 11686 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()), 11687 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11688} 11689 11690bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11691 // C++ [dcl.init.list]p2: 11692 // A constructor is an initializer-list constructor if its first parameter 11693 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11694 // std::initializer_list<E> for some type E, and either there are no other 11695 // parameters or else all other parameters have default arguments. 11696 if (!Ctor->hasOneParamOrDefaultArgs()) 11697 return false; 11698 11699 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11700 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11701 ArgType = RT->getPointeeType().getUnqualifiedType(); 11702 11703 return isStdInitializerList(ArgType, nullptr); 11704} 11705 11706/// Determine whether a using statement is in a context where it will be 11707/// apply in all contexts. 11708static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11709 switch (CurContext->getDeclKind()) { 11710 case Decl::TranslationUnit: 11711 return true; 11712 case Decl::LinkageSpec: 11713 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11714 default: 11715 return false; 11716 } 11717} 11718 11719namespace { 11720 11721// Callback to only accept typo corrections that are namespaces. 11722class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11723public: 11724 bool ValidateCandidate(const TypoCorrection &candidate) override { 11725 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11726 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11727 return false; 11728 } 11729 11730 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11731 return std::make_unique<NamespaceValidatorCCC>(*this); 11732 } 11733}; 11734 11735} 11736 11737static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11738 CXXScopeSpec &SS, 11739 SourceLocation IdentLoc, 11740 IdentifierInfo *Ident) { 11741 R.clear(); 11742 NamespaceValidatorCCC CCC{}; 11743 if (TypoCorrection Corrected = 11744 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11745 Sema::CTK_ErrorRecovery)) { 11746 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11747 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11748 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11749 Ident->getName().equals(CorrectedStr); 11750 S.diagnoseTypo(Corrected, 11751 S.PDiag(diag::err_using_directive_member_suggest) 11752 << Ident << DC << DroppedSpecifier << SS.getRange(), 11753 S.PDiag(diag::note_namespace_defined_here)); 11754 } else { 11755 S.diagnoseTypo(Corrected, 11756 S.PDiag(diag::err_using_directive_suggest) << Ident, 11757 S.PDiag(diag::note_namespace_defined_here)); 11758 } 11759 R.addDecl(Corrected.getFoundDecl()); 11760 return true; 11761 } 11762 return false; 11763} 11764 11765Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11766 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11767 SourceLocation IdentLoc, 11768 IdentifierInfo *NamespcName, 11769 const ParsedAttributesView &AttrList) { 11770 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", 11770, __extension__ __PRETTY_FUNCTION__
))
; 11771 assert(NamespcName && "Invalid NamespcName.")(static_cast <bool> (NamespcName && "Invalid NamespcName."
) ? void (0) : __assert_fail ("NamespcName && \"Invalid NamespcName.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11771, __extension__ __PRETTY_FUNCTION__
))
; 11772 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", 11772, __extension__ __PRETTY_FUNCTION__
))
; 11773 11774 // This can only happen along a recovery path. 11775 while (S->isTemplateParamScope()) 11776 S = S->getParent(); 11777 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", 11777, __extension__ __PRETTY_FUNCTION__
))
; 11778 11779 UsingDirectiveDecl *UDir = nullptr; 11780 NestedNameSpecifier *Qualifier = nullptr; 11781 if (SS.isSet()) 11782 Qualifier = SS.getScopeRep(); 11783 11784 // Lookup namespace name. 11785 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11786 LookupParsedName(R, S, &SS); 11787 if (R.isAmbiguous()) 11788 return nullptr; 11789 11790 if (R.empty()) { 11791 R.clear(); 11792 // Allow "using namespace std;" or "using namespace ::std;" even if 11793 // "std" hasn't been defined yet, for GCC compatibility. 11794 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11795 NamespcName->isStr("std")) { 11796 Diag(IdentLoc, diag::ext_using_undefined_std); 11797 R.addDecl(getOrCreateStdNamespace()); 11798 R.resolveKind(); 11799 } 11800 // Otherwise, attempt typo correction. 11801 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11802 } 11803 11804 if (!R.empty()) { 11805 NamedDecl *Named = R.getRepresentativeDecl(); 11806 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11807 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", 11807, __extension__ __PRETTY_FUNCTION__
))
; 11808 11809 // The use of a nested name specifier may trigger deprecation warnings. 11810 DiagnoseUseOfDecl(Named, IdentLoc); 11811 11812 // C++ [namespace.udir]p1: 11813 // A using-directive specifies that the names in the nominated 11814 // namespace can be used in the scope in which the 11815 // using-directive appears after the using-directive. During 11816 // unqualified name lookup (3.4.1), the names appear as if they 11817 // were declared in the nearest enclosing namespace which 11818 // contains both the using-directive and the nominated 11819 // namespace. [Note: in this context, "contains" means "contains 11820 // directly or indirectly". ] 11821 11822 // Find enclosing context containing both using-directive and 11823 // nominated namespace. 11824 DeclContext *CommonAncestor = NS; 11825 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11826 CommonAncestor = CommonAncestor->getParent(); 11827 11828 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11829 SS.getWithLocInContext(Context), 11830 IdentLoc, Named, CommonAncestor); 11831 11832 if (IsUsingDirectiveInToplevelContext(CurContext) && 11833 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11834 Diag(IdentLoc, diag::warn_using_directive_in_header); 11835 } 11836 11837 PushUsingDirective(S, UDir); 11838 } else { 11839 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11840 } 11841 11842 if (UDir) 11843 ProcessDeclAttributeList(S, UDir, AttrList); 11844 11845 return UDir; 11846} 11847 11848void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11849 // If the scope has an associated entity and the using directive is at 11850 // namespace or translation unit scope, add the UsingDirectiveDecl into 11851 // its lookup structure so qualified name lookup can find it. 11852 DeclContext *Ctx = S->getEntity(); 11853 if (Ctx && !Ctx->isFunctionOrMethod()) 11854 Ctx->addDecl(UDir); 11855 else 11856 // Otherwise, it is at block scope. The using-directives will affect lookup 11857 // only to the end of the scope. 11858 S->PushUsingDirective(UDir); 11859} 11860 11861Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11862 SourceLocation UsingLoc, 11863 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11864 UnqualifiedId &Name, 11865 SourceLocation EllipsisLoc, 11866 const ParsedAttributesView &AttrList) { 11867 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", 11867, __extension__ __PRETTY_FUNCTION__
))
; 11868 11869 if (SS.isEmpty()) { 11870 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11871 return nullptr; 11872 } 11873 11874 switch (Name.getKind()) { 11875 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11876 case UnqualifiedIdKind::IK_Identifier: 11877 case UnqualifiedIdKind::IK_OperatorFunctionId: 11878 case UnqualifiedIdKind::IK_LiteralOperatorId: 11879 case UnqualifiedIdKind::IK_ConversionFunctionId: 11880 break; 11881 11882 case UnqualifiedIdKind::IK_ConstructorName: 11883 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11884 // C++11 inheriting constructors. 11885 Diag(Name.getBeginLoc(), 11886 getLangOpts().CPlusPlus11 11887 ? diag::warn_cxx98_compat_using_decl_constructor 11888 : diag::err_using_decl_constructor) 11889 << SS.getRange(); 11890 11891 if (getLangOpts().CPlusPlus11) break; 11892 11893 return nullptr; 11894 11895 case UnqualifiedIdKind::IK_DestructorName: 11896 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11897 return nullptr; 11898 11899 case UnqualifiedIdKind::IK_TemplateId: 11900 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11901 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11902 return nullptr; 11903 11904 case UnqualifiedIdKind::IK_DeductionGuideName: 11905 llvm_unreachable("cannot parse qualified deduction guide name")::llvm::llvm_unreachable_internal("cannot parse qualified deduction guide name"
, "clang/lib/Sema/SemaDeclCXX.cpp", 11905)
; 11906 } 11907 11908 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11909 DeclarationName TargetName = TargetNameInfo.getName(); 11910 if (!TargetName) 11911 return nullptr; 11912 11913 // Warn about access declarations. 11914 if (UsingLoc.isInvalid()) { 11915 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11916 ? diag::err_access_decl 11917 : diag::warn_access_decl_deprecated) 11918 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11919 } 11920 11921 if (EllipsisLoc.isInvalid()) { 11922 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11923 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11924 return nullptr; 11925 } else { 11926 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11927 !TargetNameInfo.containsUnexpandedParameterPack()) { 11928 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11929 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11930 EllipsisLoc = SourceLocation(); 11931 } 11932 } 11933 11934 NamedDecl *UD = 11935 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11936 SS, TargetNameInfo, EllipsisLoc, AttrList, 11937 /*IsInstantiation*/ false, 11938 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists)); 11939 if (UD) 11940 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11941 11942 return UD; 11943} 11944 11945Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 11946 SourceLocation UsingLoc, 11947 SourceLocation EnumLoc, 11948 SourceLocation IdentLoc, 11949 IdentifierInfo &II, CXXScopeSpec *SS) { 11950 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", 11950, __extension__ __PRETTY_FUNCTION__
))
; 11951 TypeSourceInfo *TSI = nullptr; 11952 QualType EnumTy = GetTypeFromParser( 11953 getTypeName(II, IdentLoc, S, SS, /*isClassName=*/false, 11954 /*HasTrailingDot=*/false, 11955 /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false, 11956 /*WantNontrivialTypeSourceInfo=*/true), 11957 &TSI); 11958 if (EnumTy.isNull()) { 11959 Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS) 11960 ? diag::err_using_enum_is_dependent 11961 : diag::err_unknown_typename) 11962 << II.getName() 11963 << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, IdentLoc); 11964 return nullptr; 11965 } 11966 11967 auto *Enum = dyn_cast_if_present<EnumDecl>(EnumTy->getAsTagDecl()); 11968 if (!Enum) { 11969 Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy; 11970 return nullptr; 11971 } 11972 11973 if (auto *Def = Enum->getDefinition()) 11974 Enum = Def; 11975 11976 if (TSI == nullptr) 11977 TSI = Context.getTrivialTypeSourceInfo(EnumTy, IdentLoc); 11978 11979 auto *UD = 11980 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, TSI, Enum); 11981 11982 if (UD) 11983 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11984 11985 return UD; 11986} 11987 11988/// Determine whether a using declaration considers the given 11989/// declarations as "equivalent", e.g., if they are redeclarations of 11990/// the same entity or are both typedefs of the same type. 11991static bool 11992IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11993 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11994 return true; 11995 11996 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11997 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11998 return Context.hasSameType(TD1->getUnderlyingType(), 11999 TD2->getUnderlyingType()); 12000 12001 // Two using_if_exists using-declarations are equivalent if both are 12002 // unresolved. 12003 if (isa<UnresolvedUsingIfExistsDecl>(D1) && 12004 isa<UnresolvedUsingIfExistsDecl>(D2)) 12005 return true; 12006 12007 return false; 12008} 12009 12010 12011/// Determines whether to create a using shadow decl for a particular 12012/// decl, given the set of decls existing prior to this using lookup. 12013bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig, 12014 const LookupResult &Previous, 12015 UsingShadowDecl *&PrevShadow) { 12016 // Diagnose finding a decl which is not from a base class of the 12017 // current class. We do this now because there are cases where this 12018 // function will silently decide not to build a shadow decl, which 12019 // will pre-empt further diagnostics. 12020 // 12021 // We don't need to do this in C++11 because we do the check once on 12022 // the qualifier. 12023 // 12024 // FIXME: diagnose the following if we care enough: 12025 // struct A { int foo; }; 12026 // struct B : A { using A::foo; }; 12027 // template <class T> struct C : A {}; 12028 // template <class T> struct D : C<T> { using B::foo; } // <--- 12029 // This is invalid (during instantiation) in C++03 because B::foo 12030 // resolves to the using decl in B, which is not a base class of D<T>. 12031 // We can't diagnose it immediately because C<T> is an unknown 12032 // specialization. The UsingShadowDecl in D<T> then points directly 12033 // to A::foo, which will look well-formed when we instantiate. 12034 // The right solution is to not collapse the shadow-decl chain. 12035 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) 12036 if (auto *Using = dyn_cast<UsingDecl>(BUD)) { 12037 DeclContext *OrigDC = Orig->getDeclContext(); 12038 12039 // Handle enums and anonymous structs. 12040 if (isa<EnumDecl>(OrigDC)) 12041 OrigDC = OrigDC->getParent(); 12042 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 12043 while (OrigRec->isAnonymousStructOrUnion()) 12044 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 12045 12046 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 12047 if (OrigDC == CurContext) { 12048 Diag(Using->getLocation(), 12049 diag::err_using_decl_nested_name_specifier_is_current_class) 12050 << Using->getQualifierLoc().getSourceRange(); 12051 Diag(Orig->getLocation(), diag::note_using_decl_target); 12052 Using->setInvalidDecl(); 12053 return true; 12054 } 12055 12056 Diag(Using->getQualifierLoc().getBeginLoc(), 12057 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12058 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext) 12059 << Using->getQualifierLoc().getSourceRange(); 12060 Diag(Orig->getLocation(), diag::note_using_decl_target); 12061 Using->setInvalidDecl(); 12062 return true; 12063 } 12064 } 12065 12066 if (Previous.empty()) return false; 12067 12068 NamedDecl *Target = Orig; 12069 if (isa<UsingShadowDecl>(Target)) 12070 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 12071 12072 // If the target happens to be one of the previous declarations, we 12073 // don't have a conflict. 12074 // 12075 // FIXME: but we might be increasing its access, in which case we 12076 // should redeclare it. 12077 NamedDecl *NonTag = nullptr, *Tag = nullptr; 12078 bool FoundEquivalentDecl = false; 12079 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 12080 I != E; ++I) { 12081 NamedDecl *D = (*I)->getUnderlyingDecl(); 12082 // We can have UsingDecls in our Previous results because we use the same 12083 // LookupResult for checking whether the UsingDecl itself is a valid 12084 // redeclaration. 12085 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D)) 12086 continue; 12087 12088 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 12089 // C++ [class.mem]p19: 12090 // If T is the name of a class, then [every named member other than 12091 // a non-static data member] shall have a name different from T 12092 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 12093 !isa<IndirectFieldDecl>(Target) && 12094 !isa<UnresolvedUsingValueDecl>(Target) && 12095 DiagnoseClassNameShadow( 12096 CurContext, 12097 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation()))) 12098 return true; 12099 } 12100 12101 if (IsEquivalentForUsingDecl(Context, D, Target)) { 12102 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 12103 PrevShadow = Shadow; 12104 FoundEquivalentDecl = true; 12105 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 12106 // We don't conflict with an existing using shadow decl of an equivalent 12107 // declaration, but we're not a redeclaration of it. 12108 FoundEquivalentDecl = true; 12109 } 12110 12111 if (isVisible(D)) 12112 (isa<TagDecl>(D) ? Tag : NonTag) = D; 12113 } 12114 12115 if (FoundEquivalentDecl) 12116 return false; 12117 12118 // Always emit a diagnostic for a mismatch between an unresolved 12119 // using_if_exists and a resolved using declaration in either direction. 12120 if (isa<UnresolvedUsingIfExistsDecl>(Target) != 12121 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) { 12122 if (!NonTag && !Tag) 12123 return false; 12124 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 12125 Diag(Target->getLocation(), diag::note_using_decl_target); 12126 Diag((NonTag ? NonTag : Tag)->getLocation(), 12127 diag::note_using_decl_conflict); 12128 BUD->setInvalidDecl(); 12129 return true; 12130 } 12131 12132 if (FunctionDecl *FD = Target->getAsFunction()) { 12133 NamedDecl *OldDecl = nullptr; 12134 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 12135 /*IsForUsingDecl*/ true)) { 12136 case Ovl_Overload: 12137 return false; 12138 12139 case Ovl_NonFunction: 12140 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 12141 break; 12142 12143 // We found a decl with the exact signature. 12144 case Ovl_Match: 12145 // If we're in a record, we want to hide the target, so we 12146 // return true (without a diagnostic) to tell the caller not to 12147 // build a shadow decl. 12148 if (CurContext->isRecord()) 12149 return true; 12150 12151 // If we're not in a record, this is an error. 12152 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 12153 break; 12154 } 12155 12156 Diag(Target->getLocation(), diag::note_using_decl_target); 12157 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 12158 BUD->setInvalidDecl(); 12159 return true; 12160 } 12161 12162 // Target is not a function. 12163 12164 if (isa<TagDecl>(Target)) { 12165 // No conflict between a tag and a non-tag. 12166 if (!Tag) return false; 12167 12168 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 12169 Diag(Target->getLocation(), diag::note_using_decl_target); 12170 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 12171 BUD->setInvalidDecl(); 12172 return true; 12173 } 12174 12175 // No conflict between a tag and a non-tag. 12176 if (!NonTag) return false; 12177 12178 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 12179 Diag(Target->getLocation(), diag::note_using_decl_target); 12180 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 12181 BUD->setInvalidDecl(); 12182 return true; 12183} 12184 12185/// Determine whether a direct base class is a virtual base class. 12186static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 12187 if (!Derived->getNumVBases()) 12188 return false; 12189 for (auto &B : Derived->bases()) 12190 if (B.getType()->getAsCXXRecordDecl() == Base) 12191 return B.isVirtual(); 12192 llvm_unreachable("not a direct base class")::llvm::llvm_unreachable_internal("not a direct base class", "clang/lib/Sema/SemaDeclCXX.cpp"
, 12192)
; 12193} 12194 12195/// Builds a shadow declaration corresponding to a 'using' declaration. 12196UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, 12197 NamedDecl *Orig, 12198 UsingShadowDecl *PrevDecl) { 12199 // If we resolved to another shadow declaration, just coalesce them. 12200 NamedDecl *Target = Orig; 12201 if (isa<UsingShadowDecl>(Target)) { 12202 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 12203 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", 12203, __extension__ __PRETTY_FUNCTION__
))
; 12204 } 12205 12206 NamedDecl *NonTemplateTarget = Target; 12207 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 12208 NonTemplateTarget = TargetTD->getTemplatedDecl(); 12209 12210 UsingShadowDecl *Shadow; 12211 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 12212 UsingDecl *Using = cast<UsingDecl>(BUD); 12213 bool IsVirtualBase = 12214 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 12215 Using->getQualifier()->getAsRecordDecl()); 12216 Shadow = ConstructorUsingShadowDecl::Create( 12217 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase); 12218 } else { 12219 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(), 12220 Target->getDeclName(), BUD, Target); 12221 } 12222 BUD->addShadowDecl(Shadow); 12223 12224 Shadow->setAccess(BUD->getAccess()); 12225 if (Orig->isInvalidDecl() || BUD->isInvalidDecl()) 12226 Shadow->setInvalidDecl(); 12227 12228 Shadow->setPreviousDecl(PrevDecl); 12229 12230 if (S) 12231 PushOnScopeChains(Shadow, S); 12232 else 12233 CurContext->addDecl(Shadow); 12234 12235 12236 return Shadow; 12237} 12238 12239/// Hides a using shadow declaration. This is required by the current 12240/// using-decl implementation when a resolvable using declaration in a 12241/// class is followed by a declaration which would hide or override 12242/// one or more of the using decl's targets; for example: 12243/// 12244/// struct Base { void foo(int); }; 12245/// struct Derived : Base { 12246/// using Base::foo; 12247/// void foo(int); 12248/// }; 12249/// 12250/// The governing language is C++03 [namespace.udecl]p12: 12251/// 12252/// When a using-declaration brings names from a base class into a 12253/// derived class scope, member functions in the derived class 12254/// override and/or hide member functions with the same name and 12255/// parameter types in a base class (rather than conflicting). 12256/// 12257/// There are two ways to implement this: 12258/// (1) optimistically create shadow decls when they're not hidden 12259/// by existing declarations, or 12260/// (2) don't create any shadow decls (or at least don't make them 12261/// visible) until we've fully parsed/instantiated the class. 12262/// The problem with (1) is that we might have to retroactively remove 12263/// a shadow decl, which requires several O(n) operations because the 12264/// decl structures are (very reasonably) not designed for removal. 12265/// (2) avoids this but is very fiddly and phase-dependent. 12266void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 12267 if (Shadow->getDeclName().getNameKind() == 12268 DeclarationName::CXXConversionFunctionName) 12269 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 12270 12271 // Remove it from the DeclContext... 12272 Shadow->getDeclContext()->removeDecl(Shadow); 12273 12274 // ...and the scope, if applicable... 12275 if (S) { 12276 S->RemoveDecl(Shadow); 12277 IdResolver.RemoveDecl(Shadow); 12278 } 12279 12280 // ...and the using decl. 12281 Shadow->getIntroducer()->removeShadowDecl(Shadow); 12282 12283 // TODO: complain somehow if Shadow was used. It shouldn't 12284 // be possible for this to happen, because...? 12285} 12286 12287/// Find the base specifier for a base class with the given type. 12288static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 12289 QualType DesiredBase, 12290 bool &AnyDependentBases) { 12291 // Check whether the named type is a direct base class. 12292 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 12293 .getUnqualifiedType(); 12294 for (auto &Base : Derived->bases()) { 12295 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 12296 if (CanonicalDesiredBase == BaseType) 12297 return &Base; 12298 if (BaseType->isDependentType()) 12299 AnyDependentBases = true; 12300 } 12301 return nullptr; 12302} 12303 12304namespace { 12305class UsingValidatorCCC final : public CorrectionCandidateCallback { 12306public: 12307 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 12308 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 12309 : HasTypenameKeyword(HasTypenameKeyword), 12310 IsInstantiation(IsInstantiation), OldNNS(NNS), 12311 RequireMemberOf(RequireMemberOf) {} 12312 12313 bool ValidateCandidate(const TypoCorrection &Candidate) override { 12314 NamedDecl *ND = Candidate.getCorrectionDecl(); 12315 12316 // Keywords are not valid here. 12317 if (!ND || isa<NamespaceDecl>(ND)) 12318 return false; 12319 12320 // Completely unqualified names are invalid for a 'using' declaration. 12321 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 12322 return false; 12323 12324 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 12325 // reject. 12326 12327 if (RequireMemberOf) { 12328 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12329 if (FoundRecord && FoundRecord->isInjectedClassName()) { 12330 // No-one ever wants a using-declaration to name an injected-class-name 12331 // of a base class, unless they're declaring an inheriting constructor. 12332 ASTContext &Ctx = ND->getASTContext(); 12333 if (!Ctx.getLangOpts().CPlusPlus11) 12334 return false; 12335 QualType FoundType = Ctx.getRecordType(FoundRecord); 12336 12337 // Check that the injected-class-name is named as a member of its own 12338 // type; we don't want to suggest 'using Derived::Base;', since that 12339 // means something else. 12340 NestedNameSpecifier *Specifier = 12341 Candidate.WillReplaceSpecifier() 12342 ? Candidate.getCorrectionSpecifier() 12343 : OldNNS; 12344 if (!Specifier->getAsType() || 12345 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 12346 return false; 12347 12348 // Check that this inheriting constructor declaration actually names a 12349 // direct base class of the current class. 12350 bool AnyDependentBases = false; 12351 if (!findDirectBaseWithType(RequireMemberOf, 12352 Ctx.getRecordType(FoundRecord), 12353 AnyDependentBases) && 12354 !AnyDependentBases) 12355 return false; 12356 } else { 12357 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 12358 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 12359 return false; 12360 12361 // FIXME: Check that the base class member is accessible? 12362 } 12363 } else { 12364 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12365 if (FoundRecord && FoundRecord->isInjectedClassName()) 12366 return false; 12367 } 12368 12369 if (isa<TypeDecl>(ND)) 12370 return HasTypenameKeyword || !IsInstantiation; 12371 12372 return !HasTypenameKeyword; 12373 } 12374 12375 std::unique_ptr<CorrectionCandidateCallback> clone() override { 12376 return std::make_unique<UsingValidatorCCC>(*this); 12377 } 12378 12379private: 12380 bool HasTypenameKeyword; 12381 bool IsInstantiation; 12382 NestedNameSpecifier *OldNNS; 12383 CXXRecordDecl *RequireMemberOf; 12384}; 12385} // end anonymous namespace 12386 12387/// Remove decls we can't actually see from a lookup being used to declare 12388/// shadow using decls. 12389/// 12390/// \param S - The scope of the potential shadow decl 12391/// \param Previous - The lookup of a potential shadow decl's name. 12392void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) { 12393 // It is really dumb that we have to do this. 12394 LookupResult::Filter F = Previous.makeFilter(); 12395 while (F.hasNext()) { 12396 NamedDecl *D = F.next(); 12397 if (!isDeclInScope(D, CurContext, S)) 12398 F.erase(); 12399 // If we found a local extern declaration that's not ordinarily visible, 12400 // and this declaration is being added to a non-block scope, ignore it. 12401 // We're only checking for scope conflicts here, not also for violations 12402 // of the linkage rules. 12403 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 12404 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 12405 F.erase(); 12406 } 12407 F.done(); 12408} 12409 12410/// Builds a using declaration. 12411/// 12412/// \param IsInstantiation - Whether this call arises from an 12413/// instantiation of an unresolved using declaration. We treat 12414/// the lookup differently for these declarations. 12415NamedDecl *Sema::BuildUsingDeclaration( 12416 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 12417 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 12418 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 12419 const ParsedAttributesView &AttrList, bool IsInstantiation, 12420 bool IsUsingIfExists) { 12421 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", 12421, __extension__ __PRETTY_FUNCTION__
))
; 12422 SourceLocation IdentLoc = NameInfo.getLoc(); 12423 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", 12423, __extension__ __PRETTY_FUNCTION__
))
; 12424 12425 // FIXME: We ignore attributes for now. 12426 12427 // For an inheriting constructor declaration, the name of the using 12428 // declaration is the name of a constructor in this class, not in the 12429 // base class. 12430 DeclarationNameInfo UsingName = NameInfo; 12431 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 12432 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 12433 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12434 Context.getCanonicalType(Context.getRecordType(RD)))); 12435 12436 // Do the redeclaration lookup in the current scope. 12437 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 12438 ForVisibleRedeclaration); 12439 Previous.setHideTags(false); 12440 if (S) { 12441 LookupName(Previous, S); 12442 12443 FilterUsingLookup(S, Previous); 12444 } else { 12445 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", 12445, __extension__ __PRETTY_FUNCTION__
))
; 12446 if (CurContext->isRecord()) 12447 LookupQualifiedName(Previous, CurContext); 12448 else { 12449 // No redeclaration check is needed here; in non-member contexts we 12450 // diagnosed all possible conflicts with other using-declarations when 12451 // building the template: 12452 // 12453 // For a dependent non-type using declaration, the only valid case is 12454 // if we instantiate to a single enumerator. We check for conflicts 12455 // between shadow declarations we introduce, and we check in the template 12456 // definition for conflicts between a non-type using declaration and any 12457 // other declaration, which together covers all cases. 12458 // 12459 // A dependent typename using declaration will never successfully 12460 // instantiate, since it will always name a class member, so we reject 12461 // that in the template definition. 12462 } 12463 } 12464 12465 // Check for invalid redeclarations. 12466 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 12467 SS, IdentLoc, Previous)) 12468 return nullptr; 12469 12470 // 'using_if_exists' doesn't make sense on an inherited constructor. 12471 if (IsUsingIfExists && UsingName.getName().getNameKind() == 12472 DeclarationName::CXXConstructorName) { 12473 Diag(UsingLoc, diag::err_using_if_exists_on_ctor); 12474 return nullptr; 12475 } 12476 12477 DeclContext *LookupContext = computeDeclContext(SS); 12478 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12479 if (!LookupContext || EllipsisLoc.isValid()) { 12480 NamedDecl *D; 12481 // Dependent scope, or an unexpanded pack 12482 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, 12483 SS, NameInfo, IdentLoc)) 12484 return nullptr; 12485 12486 if (HasTypenameKeyword) { 12487 // FIXME: not all declaration name kinds are legal here 12488 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 12489 UsingLoc, TypenameLoc, 12490 QualifierLoc, 12491 IdentLoc, NameInfo.getName(), 12492 EllipsisLoc); 12493 } else { 12494 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 12495 QualifierLoc, NameInfo, EllipsisLoc); 12496 } 12497 D->setAccess(AS); 12498 CurContext->addDecl(D); 12499 ProcessDeclAttributeList(S, D, AttrList); 12500 return D; 12501 } 12502 12503 auto Build = [&](bool Invalid) { 12504 UsingDecl *UD = 12505 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 12506 UsingName, HasTypenameKeyword); 12507 UD->setAccess(AS); 12508 CurContext->addDecl(UD); 12509 ProcessDeclAttributeList(S, UD, AttrList); 12510 UD->setInvalidDecl(Invalid); 12511 return UD; 12512 }; 12513 auto BuildInvalid = [&]{ return Build(true); }; 12514 auto BuildValid = [&]{ return Build(false); }; 12515 12516 if (RequireCompleteDeclContext(SS, LookupContext)) 12517 return BuildInvalid(); 12518 12519 // Look up the target name. 12520 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12521 12522 // Unlike most lookups, we don't always want to hide tag 12523 // declarations: tag names are visible through the using declaration 12524 // even if hidden by ordinary names, *except* in a dependent context 12525 // where they may be used by two-phase lookup. 12526 if (!IsInstantiation) 12527 R.setHideTags(false); 12528 12529 // For the purposes of this lookup, we have a base object type 12530 // equal to that of the current context. 12531 if (CurContext->isRecord()) { 12532 R.setBaseObjectType( 12533 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12534 } 12535 12536 LookupQualifiedName(R, LookupContext); 12537 12538 // Validate the context, now we have a lookup 12539 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 12540 IdentLoc, &R)) 12541 return nullptr; 12542 12543 if (R.empty() && IsUsingIfExists) 12544 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc, 12545 UsingName.getName()), 12546 AS_public); 12547 12548 // Try to correct typos if possible. If constructor name lookup finds no 12549 // results, that means the named class has no explicit constructors, and we 12550 // suppressed declaring implicit ones (probably because it's dependent or 12551 // invalid). 12552 if (R.empty() && 12553 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12554 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of 12555 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where 12556 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later. 12557 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12558 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12559 CurContext->isStdNamespace() && 12560 isa<TranslationUnitDecl>(LookupContext) && 12561 getSourceManager().isInSystemHeader(UsingLoc)) 12562 return nullptr; 12563 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12564 dyn_cast<CXXRecordDecl>(CurContext)); 12565 if (TypoCorrection Corrected = 12566 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12567 CTK_ErrorRecovery)) { 12568 // We reject candidates where DroppedSpecifier == true, hence the 12569 // literal '0' below. 12570 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12571 << NameInfo.getName() << LookupContext << 0 12572 << SS.getRange()); 12573 12574 // If we picked a correction with no attached Decl we can't do anything 12575 // useful with it, bail out. 12576 NamedDecl *ND = Corrected.getCorrectionDecl(); 12577 if (!ND) 12578 return BuildInvalid(); 12579 12580 // If we corrected to an inheriting constructor, handle it as one. 12581 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12582 if (RD && RD->isInjectedClassName()) { 12583 // The parent of the injected class name is the class itself. 12584 RD = cast<CXXRecordDecl>(RD->getParent()); 12585 12586 // Fix up the information we'll use to build the using declaration. 12587 if (Corrected.WillReplaceSpecifier()) { 12588 NestedNameSpecifierLocBuilder Builder; 12589 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12590 QualifierLoc.getSourceRange()); 12591 QualifierLoc = Builder.getWithLocInContext(Context); 12592 } 12593 12594 // In this case, the name we introduce is the name of a derived class 12595 // constructor. 12596 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12597 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12598 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12599 UsingName.setNamedTypeInfo(nullptr); 12600 for (auto *Ctor : LookupConstructors(RD)) 12601 R.addDecl(Ctor); 12602 R.resolveKind(); 12603 } else { 12604 // FIXME: Pick up all the declarations if we found an overloaded 12605 // function. 12606 UsingName.setName(ND->getDeclName()); 12607 R.addDecl(ND); 12608 } 12609 } else { 12610 Diag(IdentLoc, diag::err_no_member) 12611 << NameInfo.getName() << LookupContext << SS.getRange(); 12612 return BuildInvalid(); 12613 } 12614 } 12615 12616 if (R.isAmbiguous()) 12617 return BuildInvalid(); 12618 12619 if (HasTypenameKeyword) { 12620 // If we asked for a typename and got a non-type decl, error out. 12621 if (!R.getAsSingle<TypeDecl>() && 12622 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) { 12623 Diag(IdentLoc, diag::err_using_typename_non_type); 12624 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12625 Diag((*I)->getUnderlyingDecl()->getLocation(), 12626 diag::note_using_decl_target); 12627 return BuildInvalid(); 12628 } 12629 } else { 12630 // If we asked for a non-typename and we got a type, error out, 12631 // but only if this is an instantiation of an unresolved using 12632 // decl. Otherwise just silently find the type name. 12633 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12634 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12635 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12636 return BuildInvalid(); 12637 } 12638 } 12639 12640 // C++14 [namespace.udecl]p6: 12641 // A using-declaration shall not name a namespace. 12642 if (R.getAsSingle<NamespaceDecl>()) { 12643 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12644 << SS.getRange(); 12645 return BuildInvalid(); 12646 } 12647 12648 UsingDecl *UD = BuildValid(); 12649 12650 // Some additional rules apply to inheriting constructors. 12651 if (UsingName.getName().getNameKind() == 12652 DeclarationName::CXXConstructorName) { 12653 // Suppress access diagnostics; the access check is instead performed at the 12654 // point of use for an inheriting constructor. 12655 R.suppressDiagnostics(); 12656 if (CheckInheritingConstructorUsingDecl(UD)) 12657 return UD; 12658 } 12659 12660 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12661 UsingShadowDecl *PrevDecl = nullptr; 12662 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12663 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12664 } 12665 12666 return UD; 12667} 12668 12669NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 12670 SourceLocation UsingLoc, 12671 SourceLocation EnumLoc, 12672 SourceLocation NameLoc, 12673 TypeSourceInfo *EnumType, 12674 EnumDecl *ED) { 12675 bool Invalid = false; 12676 12677 if (CurContext->getRedeclContext()->isRecord()) { 12678 /// In class scope, check if this is a duplicate, for better a diagnostic. 12679 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc); 12680 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName, 12681 ForVisibleRedeclaration); 12682 12683 LookupName(Previous, S); 12684 12685 for (NamedDecl *D : Previous) 12686 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D)) 12687 if (UED->getEnumDecl() == ED) { 12688 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration) 12689 << SourceRange(EnumLoc, NameLoc); 12690 Diag(D->getLocation(), diag::note_using_enum_decl) << 1; 12691 Invalid = true; 12692 break; 12693 } 12694 } 12695 12696 if (RequireCompleteEnumDecl(ED, NameLoc)) 12697 Invalid = true; 12698 12699 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc, 12700 EnumLoc, NameLoc, EnumType); 12701 UD->setAccess(AS); 12702 CurContext->addDecl(UD); 12703 12704 if (Invalid) { 12705 UD->setInvalidDecl(); 12706 return UD; 12707 } 12708 12709 // Create the shadow decls for each enumerator 12710 for (EnumConstantDecl *EC : ED->enumerators()) { 12711 UsingShadowDecl *PrevDecl = nullptr; 12712 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation()); 12713 LookupResult Previous(*this, DNI, LookupOrdinaryName, 12714 ForVisibleRedeclaration); 12715 LookupName(Previous, S); 12716 FilterUsingLookup(S, Previous); 12717 12718 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl)) 12719 BuildUsingShadowDecl(S, UD, EC, PrevDecl); 12720 } 12721 12722 return UD; 12723} 12724 12725NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12726 ArrayRef<NamedDecl *> Expansions) { 12727 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", 12729, __extension__ __PRETTY_FUNCTION__
))
12728 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", 12729, __extension__ __PRETTY_FUNCTION__
))
12729 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", 12729, __extension__ __PRETTY_FUNCTION__
))
; 12730 12731 auto *UPD = 12732 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12733 UPD->setAccess(InstantiatedFrom->getAccess()); 12734 CurContext->addDecl(UPD); 12735 return UPD; 12736} 12737 12738/// Additional checks for a using declaration referring to a constructor name. 12739bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12740 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", 12740, __extension__ __PRETTY_FUNCTION__
))
; 12741 12742 const Type *SourceType = UD->getQualifier()->getAsType(); 12743 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", 12744, __extension__ __PRETTY_FUNCTION__
))
12744 "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", 12744, __extension__ __PRETTY_FUNCTION__
))
; 12745 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12746 12747 // Check whether the named type is a direct base class. 12748 bool AnyDependentBases = false; 12749 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12750 AnyDependentBases); 12751 if (!Base && !AnyDependentBases) { 12752 Diag(UD->getUsingLoc(), 12753 diag::err_using_decl_constructor_not_in_direct_base) 12754 << UD->getNameInfo().getSourceRange() 12755 << QualType(SourceType, 0) << TargetClass; 12756 UD->setInvalidDecl(); 12757 return true; 12758 } 12759 12760 if (Base) 12761 Base->setInheritConstructors(); 12762 12763 return false; 12764} 12765 12766/// Checks that the given using declaration is not an invalid 12767/// redeclaration. Note that this is checking only for the using decl 12768/// itself, not for any ill-formedness among the UsingShadowDecls. 12769bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12770 bool HasTypenameKeyword, 12771 const CXXScopeSpec &SS, 12772 SourceLocation NameLoc, 12773 const LookupResult &Prev) { 12774 NestedNameSpecifier *Qual = SS.getScopeRep(); 12775 12776 // C++03 [namespace.udecl]p8: 12777 // C++0x [namespace.udecl]p10: 12778 // A using-declaration is a declaration and can therefore be used 12779 // repeatedly where (and only where) multiple declarations are 12780 // allowed. 12781 // 12782 // That's in non-member contexts. 12783 if (!CurContext->getRedeclContext()->isRecord()) { 12784 // A dependent qualifier outside a class can only ever resolve to an 12785 // enumeration type. Therefore it conflicts with any other non-type 12786 // declaration in the same scope. 12787 // FIXME: How should we check for dependent type-type conflicts at block 12788 // scope? 12789 if (Qual->isDependent() && !HasTypenameKeyword) { 12790 for (auto *D : Prev) { 12791 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12792 bool OldCouldBeEnumerator = 12793 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12794 Diag(NameLoc, 12795 OldCouldBeEnumerator ? diag::err_redefinition 12796 : diag::err_redefinition_different_kind) 12797 << Prev.getLookupName(); 12798 Diag(D->getLocation(), diag::note_previous_definition); 12799 return true; 12800 } 12801 } 12802 } 12803 return false; 12804 } 12805 12806 const NestedNameSpecifier *CNNS = 12807 Context.getCanonicalNestedNameSpecifier(Qual); 12808 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12809 NamedDecl *D = *I; 12810 12811 bool DTypename; 12812 NestedNameSpecifier *DQual; 12813 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12814 DTypename = UD->hasTypename(); 12815 DQual = UD->getQualifier(); 12816 } else if (UnresolvedUsingValueDecl *UD 12817 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12818 DTypename = false; 12819 DQual = UD->getQualifier(); 12820 } else if (UnresolvedUsingTypenameDecl *UD 12821 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12822 DTypename = true; 12823 DQual = UD->getQualifier(); 12824 } else continue; 12825 12826 // using decls differ if one says 'typename' and the other doesn't. 12827 // FIXME: non-dependent using decls? 12828 if (HasTypenameKeyword != DTypename) continue; 12829 12830 // using decls differ if they name different scopes (but note that 12831 // template instantiation can cause this check to trigger when it 12832 // didn't before instantiation). 12833 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual)) 12834 continue; 12835 12836 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12837 Diag(D->getLocation(), diag::note_using_decl) << 1; 12838 return true; 12839 } 12840 12841 return false; 12842} 12843 12844/// Checks that the given nested-name qualifier used in a using decl 12845/// in the current context is appropriately related to the current 12846/// scope. If an error is found, diagnoses it and returns true. 12847/// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the 12848/// result of that lookup. UD is likewise nullptr, except when we have an 12849/// already-populated UsingDecl whose shadow decls contain the same information 12850/// (i.e. we're instantiating a UsingDecl with non-dependent scope). 12851bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, 12852 const CXXScopeSpec &SS, 12853 const DeclarationNameInfo &NameInfo, 12854 SourceLocation NameLoc, 12855 const LookupResult *R, const UsingDecl *UD) { 12856 DeclContext *NamedContext = computeDeclContext(SS); 12857 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", 12858, __extension__ __PRETTY_FUNCTION__
))
12858 "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", 12858, __extension__ __PRETTY_FUNCTION__
))
; 12859 12860 // C++ 20 permits using an enumerator that does not have a class-hierarchy 12861 // relationship. 12862 bool Cxx20Enumerator = false; 12863 if (NamedContext) { 12864 EnumConstantDecl *EC = nullptr; 12865 if (R) 12866 EC = R->getAsSingle<EnumConstantDecl>(); 12867 else if (UD && UD->shadow_size() == 1) 12868 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl()); 12869 if (EC) 12870 Cxx20Enumerator = getLangOpts().CPlusPlus20; 12871 12872 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) { 12873 // C++14 [namespace.udecl]p7: 12874 // A using-declaration shall not name a scoped enumerator. 12875 // C++20 p1099 permits enumerators. 12876 if (EC && R && ED->isScoped()) 12877 Diag(SS.getBeginLoc(), 12878 getLangOpts().CPlusPlus20 12879 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator 12880 : diag::ext_using_decl_scoped_enumerator) 12881 << SS.getRange(); 12882 12883 // We want to consider the scope of the enumerator 12884 NamedContext = ED->getDeclContext(); 12885 } 12886 } 12887 12888 if (!CurContext->isRecord()) { 12889 // C++03 [namespace.udecl]p3: 12890 // C++0x [namespace.udecl]p8: 12891 // A using-declaration for a class member shall be a member-declaration. 12892 // C++20 [namespace.udecl]p7 12893 // ... other than an enumerator ... 12894 12895 // If we weren't able to compute a valid scope, it might validly be a 12896 // dependent class or enumeration scope. If we have a 'typename' keyword, 12897 // the scope must resolve to a class type. 12898 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord() 12899 : !HasTypename) 12900 return false; // OK 12901 12902 Diag(NameLoc, 12903 Cxx20Enumerator 12904 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator 12905 : diag::err_using_decl_can_not_refer_to_class_member) 12906 << SS.getRange(); 12907 12908 if (Cxx20Enumerator) 12909 return false; // OK 12910 12911 auto *RD = NamedContext 12912 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12913 : nullptr; 12914 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) { 12915 // See if there's a helpful fixit 12916 12917 if (!R) { 12918 // We will have already diagnosed the problem on the template 12919 // definition, Maybe we should do so again? 12920 } else if (R->getAsSingle<TypeDecl>()) { 12921 if (getLangOpts().CPlusPlus11) { 12922 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12923 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12924 << 0 // alias declaration 12925 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12926 NameInfo.getName().getAsString() + 12927 " = "); 12928 } else { 12929 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12930 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12931 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12932 << 1 // typedef declaration 12933 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12934 << FixItHint::CreateInsertion( 12935 InsertLoc, " " + NameInfo.getName().getAsString()); 12936 } 12937 } else if (R->getAsSingle<VarDecl>()) { 12938 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12939 // repeating the type of the static data member here. 12940 FixItHint FixIt; 12941 if (getLangOpts().CPlusPlus11) { 12942 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12943 FixIt = FixItHint::CreateReplacement( 12944 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12945 } 12946 12947 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12948 << 2 // reference declaration 12949 << FixIt; 12950 } else if (R->getAsSingle<EnumConstantDecl>()) { 12951 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12952 // repeating the type of the enumeration here, and we can't do so if 12953 // the type is anonymous. 12954 FixItHint FixIt; 12955 if (getLangOpts().CPlusPlus11) { 12956 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12957 FixIt = FixItHint::CreateReplacement( 12958 UsingLoc, 12959 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12960 } 12961 12962 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12963 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12964 << FixIt; 12965 } 12966 } 12967 12968 return true; // Fail 12969 } 12970 12971 // If the named context is dependent, we can't decide much. 12972 if (!NamedContext) { 12973 // FIXME: in C++0x, we can diagnose if we can prove that the 12974 // nested-name-specifier does not refer to a base class, which is 12975 // still possible in some cases. 12976 12977 // Otherwise we have to conservatively report that things might be 12978 // okay. 12979 return false; 12980 } 12981 12982 // The current scope is a record. 12983 if (!NamedContext->isRecord()) { 12984 // Ideally this would point at the last name in the specifier, 12985 // but we don't have that level of source info. 12986 Diag(SS.getBeginLoc(), 12987 Cxx20Enumerator 12988 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator 12989 : diag::err_using_decl_nested_name_specifier_is_not_class) 12990 << SS.getScopeRep() << SS.getRange(); 12991 12992 if (Cxx20Enumerator) 12993 return false; // OK 12994 12995 return true; 12996 } 12997 12998 if (!NamedContext->isDependentContext() && 12999 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 13000 return true; 13001 13002 if (getLangOpts().CPlusPlus11) { 13003 // C++11 [namespace.udecl]p3: 13004 // In a using-declaration used as a member-declaration, the 13005 // nested-name-specifier shall name a base class of the class 13006 // being defined. 13007 13008 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 13009 cast<CXXRecordDecl>(NamedContext))) { 13010 13011 if (Cxx20Enumerator) { 13012 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator) 13013 << SS.getRange(); 13014 return false; 13015 } 13016 13017 if (CurContext == NamedContext) { 13018 Diag(SS.getBeginLoc(), 13019 diag::err_using_decl_nested_name_specifier_is_current_class) 13020 << SS.getRange(); 13021 return !getLangOpts().CPlusPlus20; 13022 } 13023 13024 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 13025 Diag(SS.getBeginLoc(), 13026 diag::err_using_decl_nested_name_specifier_is_not_base_class) 13027 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext) 13028 << SS.getRange(); 13029 } 13030 return true; 13031 } 13032 13033 return false; 13034 } 13035 13036 // C++03 [namespace.udecl]p4: 13037 // A using-declaration used as a member-declaration shall refer 13038 // to a member of a base class of the class being defined [etc.]. 13039 13040 // Salient point: SS doesn't have to name a base class as long as 13041 // lookup only finds members from base classes. Therefore we can 13042 // diagnose here only if we can prove that can't happen, 13043 // i.e. if the class hierarchies provably don't intersect. 13044 13045 // TODO: it would be nice if "definitely valid" results were cached 13046 // in the UsingDecl and UsingShadowDecl so that these checks didn't 13047 // need to be repeated. 13048 13049 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 13050 auto Collect = [&Bases](const CXXRecordDecl *Base) { 13051 Bases.insert(Base); 13052 return true; 13053 }; 13054 13055 // Collect all bases. Return false if we find a dependent base. 13056 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 13057 return false; 13058 13059 // Returns true if the base is dependent or is one of the accumulated base 13060 // classes. 13061 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 13062 return !Bases.count(Base); 13063 }; 13064 13065 // Return false if the class has a dependent base or if it or one 13066 // of its bases is present in the base set of the current context. 13067 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 13068 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 13069 return false; 13070 13071 Diag(SS.getRange().getBegin(), 13072 diag::err_using_decl_nested_name_specifier_is_not_base_class) 13073 << SS.getScopeRep() 13074 << cast<CXXRecordDecl>(CurContext) 13075 << SS.getRange(); 13076 13077 return true; 13078} 13079 13080Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 13081 MultiTemplateParamsArg TemplateParamLists, 13082 SourceLocation UsingLoc, UnqualifiedId &Name, 13083 const ParsedAttributesView &AttrList, 13084 TypeResult Type, Decl *DeclFromDeclSpec) { 13085 // Skip up to the relevant declaration scope. 13086 while (S->isTemplateParamScope()) 13087 S = S->getParent(); 13088 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", 13089, __extension__ __PRETTY_FUNCTION__
))
13089 "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", 13089, __extension__ __PRETTY_FUNCTION__
))
; 13090 13091 if (Type.isInvalid()) 13092 return nullptr; 13093 13094 bool Invalid = false; 13095 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 13096 TypeSourceInfo *TInfo = nullptr; 13097 GetTypeFromParser(Type.get(), &TInfo); 13098 13099 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 13100 return nullptr; 13101 13102 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 13103 UPPC_DeclarationType)) { 13104 Invalid = true; 13105 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 13106 TInfo->getTypeLoc().getBeginLoc()); 13107 } 13108 13109 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 13110 TemplateParamLists.size() 13111 ? forRedeclarationInCurContext() 13112 : ForVisibleRedeclaration); 13113 LookupName(Previous, S); 13114 13115 // Warn about shadowing the name of a template parameter. 13116 if (Previous.isSingleResult() && 13117 Previous.getFoundDecl()->isTemplateParameter()) { 13118 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 13119 Previous.clear(); 13120 } 13121 13122 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", 13123, __extension__ __PRETTY_FUNCTION__
))
13123 "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", 13123, __extension__ __PRETTY_FUNCTION__
))
; 13124 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 13125 Name.StartLocation, 13126 Name.Identifier, TInfo); 13127 13128 NewTD->setAccess(AS); 13129 13130 if (Invalid) 13131 NewTD->setInvalidDecl(); 13132 13133 ProcessDeclAttributeList(S, NewTD, AttrList); 13134 AddPragmaAttributes(S, NewTD); 13135 13136 CheckTypedefForVariablyModifiedType(S, NewTD); 13137 Invalid |= NewTD->isInvalidDecl(); 13138 13139 bool Redeclaration = false; 13140 13141 NamedDecl *NewND; 13142 if (TemplateParamLists.size()) { 13143 TypeAliasTemplateDecl *OldDecl = nullptr; 13144 TemplateParameterList *OldTemplateParams = nullptr; 13145 13146 if (TemplateParamLists.size() != 1) { 13147 Diag(UsingLoc, diag::err_alias_template_extra_headers) 13148 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 13149 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 13150 } 13151 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 13152 13153 // Check that we can declare a template here. 13154 if (CheckTemplateDeclScope(S, TemplateParams)) 13155 return nullptr; 13156 13157 // Only consider previous declarations in the same scope. 13158 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 13159 /*ExplicitInstantiationOrSpecialization*/false); 13160 if (!Previous.empty()) { 13161 Redeclaration = true; 13162 13163 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 13164 if (!OldDecl && !Invalid) { 13165 Diag(UsingLoc, diag::err_redefinition_different_kind) 13166 << Name.Identifier; 13167 13168 NamedDecl *OldD = Previous.getRepresentativeDecl(); 13169 if (OldD->getLocation().isValid()) 13170 Diag(OldD->getLocation(), diag::note_previous_definition); 13171 13172 Invalid = true; 13173 } 13174 13175 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 13176 if (TemplateParameterListsAreEqual(TemplateParams, 13177 OldDecl->getTemplateParameters(), 13178 /*Complain=*/true, 13179 TPL_TemplateMatch)) 13180 OldTemplateParams = 13181 OldDecl->getMostRecentDecl()->getTemplateParameters(); 13182 else 13183 Invalid = true; 13184 13185 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 13186 if (!Invalid && 13187 !Context.hasSameType(OldTD->getUnderlyingType(), 13188 NewTD->getUnderlyingType())) { 13189 // FIXME: The C++0x standard does not clearly say this is ill-formed, 13190 // but we can't reasonably accept it. 13191 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 13192 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 13193 if (OldTD->getLocation().isValid()) 13194 Diag(OldTD->getLocation(), diag::note_previous_definition); 13195 Invalid = true; 13196 } 13197 } 13198 } 13199 13200 // Merge any previous default template arguments into our parameters, 13201 // and check the parameter list. 13202 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 13203 TPC_TypeAliasTemplate)) 13204 return nullptr; 13205 13206 TypeAliasTemplateDecl *NewDecl = 13207 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 13208 Name.Identifier, TemplateParams, 13209 NewTD); 13210 NewTD->setDescribedAliasTemplate(NewDecl); 13211 13212 NewDecl->setAccess(AS); 13213 13214 if (Invalid) 13215 NewDecl->setInvalidDecl(); 13216 else if (OldDecl) { 13217 NewDecl->setPreviousDecl(OldDecl); 13218 CheckRedeclarationInModule(NewDecl, OldDecl); 13219 } 13220 13221 NewND = NewDecl; 13222 } else { 13223 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 13224 setTagNameForLinkagePurposes(TD, NewTD); 13225 handleTagNumbering(TD, S); 13226 } 13227 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 13228 NewND = NewTD; 13229 } 13230 13231 PushOnScopeChains(NewND, S); 13232 ActOnDocumentableDecl(NewND); 13233 return NewND; 13234} 13235 13236Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 13237 SourceLocation AliasLoc, 13238 IdentifierInfo *Alias, CXXScopeSpec &SS, 13239 SourceLocation IdentLoc, 13240 IdentifierInfo *Ident) { 13241 13242 // Lookup the namespace name. 13243 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 13244 LookupParsedName(R, S, &SS); 13245 13246 if (R.isAmbiguous()) 13247 return nullptr; 13248 13249 if (R.empty()) { 13250 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 13251 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 13252 return nullptr; 13253 } 13254 } 13255 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", 13255, __extension__ __PRETTY_FUNCTION__
))
; 13256 NamedDecl *ND = R.getRepresentativeDecl(); 13257 13258 // Check if we have a previous declaration with the same name. 13259 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 13260 ForVisibleRedeclaration); 13261 LookupName(PrevR, S); 13262 13263 // Check we're not shadowing a template parameter. 13264 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 13265 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 13266 PrevR.clear(); 13267 } 13268 13269 // Filter out any other lookup result from an enclosing scope. 13270 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 13271 /*AllowInlineNamespace*/false); 13272 13273 // Find the previous declaration and check that we can redeclare it. 13274 NamespaceAliasDecl *Prev = nullptr; 13275 if (PrevR.isSingleResult()) { 13276 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 13277 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 13278 // We already have an alias with the same name that points to the same 13279 // namespace; check that it matches. 13280 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 13281 Prev = AD; 13282 } else if (isVisible(PrevDecl)) { 13283 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 13284 << Alias; 13285 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 13286 << AD->getNamespace(); 13287 return nullptr; 13288 } 13289 } else if (isVisible(PrevDecl)) { 13290 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 13291 ? diag::err_redefinition 13292 : diag::err_redefinition_different_kind; 13293 Diag(AliasLoc, DiagID) << Alias; 13294 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13295 return nullptr; 13296 } 13297 } 13298 13299 // The use of a nested name specifier may trigger deprecation warnings. 13300 DiagnoseUseOfDecl(ND, IdentLoc); 13301 13302 NamespaceAliasDecl *AliasDecl = 13303 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 13304 Alias, SS.getWithLocInContext(Context), 13305 IdentLoc, ND); 13306 if (Prev) 13307 AliasDecl->setPreviousDecl(Prev); 13308 13309 PushOnScopeChains(AliasDecl, S); 13310 return AliasDecl; 13311} 13312 13313namespace { 13314struct SpecialMemberExceptionSpecInfo 13315 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 13316 SourceLocation Loc; 13317 Sema::ImplicitExceptionSpecification ExceptSpec; 13318 13319 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 13320 Sema::CXXSpecialMember CSM, 13321 Sema::InheritedConstructorInfo *ICI, 13322 SourceLocation Loc) 13323 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 13324 13325 bool visitBase(CXXBaseSpecifier *Base); 13326 bool visitField(FieldDecl *FD); 13327 13328 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 13329 unsigned Quals); 13330 13331 void visitSubobjectCall(Subobject Subobj, 13332 Sema::SpecialMemberOverloadResult SMOR); 13333}; 13334} 13335 13336bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 13337 auto *RT = Base->getType()->getAs<RecordType>(); 13338 if (!RT) 13339 return false; 13340 13341 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 13342 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 13343 if (auto *BaseCtor = SMOR.getMethod()) { 13344 visitSubobjectCall(Base, BaseCtor); 13345 return false; 13346 } 13347 13348 visitClassSubobject(BaseClass, Base, 0); 13349 return false; 13350} 13351 13352bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 13353 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 13354 Expr *E = FD->getInClassInitializer(); 13355 if (!E) 13356 // FIXME: It's a little wasteful to build and throw away a 13357 // CXXDefaultInitExpr here. 13358 // FIXME: We should have a single context note pointing at Loc, and 13359 // this location should be MD->getLocation() instead, since that's 13360 // the location where we actually use the default init expression. 13361 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 13362 if (E) 13363 ExceptSpec.CalledExpr(E); 13364 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 13365 ->getAs<RecordType>()) { 13366 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 13367 FD->getType().getCVRQualifiers()); 13368 } 13369 return false; 13370} 13371 13372void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 13373 Subobject Subobj, 13374 unsigned Quals) { 13375 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 13376 bool IsMutable = Field && Field->isMutable(); 13377 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 13378} 13379 13380void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 13381 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 13382 // Note, if lookup fails, it doesn't matter what exception specification we 13383 // choose because the special member will be deleted. 13384 if (CXXMethodDecl *MD = SMOR.getMethod()) 13385 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 13386} 13387 13388bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 13389 llvm::APSInt Result; 13390 ExprResult Converted = CheckConvertedConstantExpression( 13391 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 13392 ExplicitSpec.setExpr(Converted.get()); 13393 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 13394 ExplicitSpec.setKind(Result.getBoolValue() 13395 ? ExplicitSpecKind::ResolvedTrue 13396 : ExplicitSpecKind::ResolvedFalse); 13397 return true; 13398 } 13399 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 13400 return false; 13401} 13402 13403ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 13404 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 13405 if (!ExplicitExpr->isTypeDependent()) 13406 tryResolveExplicitSpecifier(ES); 13407 return ES; 13408} 13409 13410static Sema::ImplicitExceptionSpecification 13411ComputeDefaultedSpecialMemberExceptionSpec( 13412 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 13413 Sema::InheritedConstructorInfo *ICI) { 13414 ComputingExceptionSpec CES(S, MD, Loc); 13415 13416 CXXRecordDecl *ClassDecl = MD->getParent(); 13417 13418 // C++ [except.spec]p14: 13419 // An implicitly declared special member function (Clause 12) shall have an 13420 // exception-specification. [...] 13421 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 13422 if (ClassDecl->isInvalidDecl()) 13423 return Info.ExceptSpec; 13424 13425 // FIXME: If this diagnostic fires, we're probably missing a check for 13426 // attempting to resolve an exception specification before it's known 13427 // at a higher level. 13428 if (S.RequireCompleteType(MD->getLocation(), 13429 S.Context.getRecordType(ClassDecl), 13430 diag::err_exception_spec_incomplete_type)) 13431 return Info.ExceptSpec; 13432 13433 // C++1z [except.spec]p7: 13434 // [Look for exceptions thrown by] a constructor selected [...] to 13435 // initialize a potentially constructed subobject, 13436 // C++1z [except.spec]p8: 13437 // The exception specification for an implicitly-declared destructor, or a 13438 // destructor without a noexcept-specifier, is potentially-throwing if and 13439 // only if any of the destructors for any of its potentially constructed 13440 // subojects is potentially throwing. 13441 // FIXME: We respect the first rule but ignore the "potentially constructed" 13442 // in the second rule to resolve a core issue (no number yet) that would have 13443 // us reject: 13444 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 13445 // struct B : A {}; 13446 // struct C : B { void f(); }; 13447 // ... due to giving B::~B() a non-throwing exception specification. 13448 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 13449 : Info.VisitAllBases); 13450 13451 return Info.ExceptSpec; 13452} 13453 13454namespace { 13455/// RAII object to register a special member as being currently declared. 13456struct DeclaringSpecialMember { 13457 Sema &S; 13458 Sema::SpecialMemberDecl D; 13459 Sema::ContextRAII SavedContext; 13460 bool WasAlreadyBeingDeclared; 13461 13462 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 13463 : S(S), D(RD, CSM), SavedContext(S, RD) { 13464 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 13465 if (WasAlreadyBeingDeclared) 13466 // This almost never happens, but if it does, ensure that our cache 13467 // doesn't contain a stale result. 13468 S.SpecialMemberCache.clear(); 13469 else { 13470 // Register a note to be produced if we encounter an error while 13471 // declaring the special member. 13472 Sema::CodeSynthesisContext Ctx; 13473 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 13474 // FIXME: We don't have a location to use here. Using the class's 13475 // location maintains the fiction that we declare all special members 13476 // with the class, but (1) it's not clear that lying about that helps our 13477 // users understand what's going on, and (2) there may be outer contexts 13478 // on the stack (some of which are relevant) and printing them exposes 13479 // our lies. 13480 Ctx.PointOfInstantiation = RD->getLocation(); 13481 Ctx.Entity = RD; 13482 Ctx.SpecialMember = CSM; 13483 S.pushCodeSynthesisContext(Ctx); 13484 } 13485 } 13486 ~DeclaringSpecialMember() { 13487 if (!WasAlreadyBeingDeclared) { 13488 S.SpecialMembersBeingDeclared.erase(D); 13489 S.popCodeSynthesisContext(); 13490 } 13491 } 13492 13493 /// Are we already trying to declare this special member? 13494 bool isAlreadyBeingDeclared() const { 13495 return WasAlreadyBeingDeclared; 13496 } 13497}; 13498} 13499 13500void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 13501 // Look up any existing declarations, but don't trigger declaration of all 13502 // implicit special members with this name. 13503 DeclarationName Name = FD->getDeclName(); 13504 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 13505 ForExternalRedeclaration); 13506 for (auto *D : FD->getParent()->lookup(Name)) 13507 if (auto *Acceptable = R.getAcceptableDecl(D)) 13508 R.addDecl(Acceptable); 13509 R.resolveKind(); 13510 R.suppressDiagnostics(); 13511 13512 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false, 13513 FD->isThisDeclarationADefinition()); 13514} 13515 13516void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 13517 QualType ResultTy, 13518 ArrayRef<QualType> Args) { 13519 // Build an exception specification pointing back at this constructor. 13520 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 13521 13522 LangAS AS = getDefaultCXXMethodAddrSpace(); 13523 if (AS != LangAS::Default) { 13524 EPI.TypeQuals.addAddressSpace(AS); 13525 } 13526 13527 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 13528 SpecialMem->setType(QT); 13529 13530 // During template instantiation of implicit special member functions we need 13531 // a reliable TypeSourceInfo for the function prototype in order to allow 13532 // functions to be substituted. 13533 if (inTemplateInstantiation() && 13534 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) { 13535 TypeSourceInfo *TSI = 13536 Context.getTrivialTypeSourceInfo(SpecialMem->getType()); 13537 SpecialMem->setTypeSourceInfo(TSI); 13538 } 13539} 13540 13541CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 13542 CXXRecordDecl *ClassDecl) { 13543 // C++ [class.ctor]p5: 13544 // A default constructor for a class X is a constructor of class X 13545 // that can be called without an argument. If there is no 13546 // user-declared constructor for class X, a default constructor is 13547 // implicitly declared. An implicitly-declared default constructor 13548 // is an inline public member of its class. 13549 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", 13550, __extension__ __PRETTY_FUNCTION__
))
13550 "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", 13550, __extension__ __PRETTY_FUNCTION__
))
; 13551 13552 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 13553 if (DSM.isAlreadyBeingDeclared()) 13554 return nullptr; 13555 13556 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13557 CXXDefaultConstructor, 13558 false); 13559 13560 // Create the actual constructor declaration. 13561 CanQualType ClassType 13562 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13563 SourceLocation ClassLoc = ClassDecl->getLocation(); 13564 DeclarationName Name 13565 = Context.DeclarationNames.getCXXConstructorName(ClassType); 13566 DeclarationNameInfo NameInfo(Name, ClassLoc); 13567 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 13568 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 13569 /*TInfo=*/nullptr, ExplicitSpecifier(), 13570 getCurFPFeatures().isFPConstrained(), 13571 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 13572 Constexpr ? ConstexprSpecKind::Constexpr 13573 : ConstexprSpecKind::Unspecified); 13574 DefaultCon->setAccess(AS_public); 13575 DefaultCon->setDefaulted(); 13576 13577 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, std::nullopt); 13578 13579 if (getLangOpts().CUDA) 13580 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 13581 DefaultCon, 13582 /* ConstRHS */ false, 13583 /* Diagnose */ false); 13584 13585 // We don't need to use SpecialMemberIsTrivial here; triviality for default 13586 // constructors is easy to compute. 13587 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 13588 13589 // Note that we have declared this constructor. 13590 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 13591 13592 Scope *S = getScopeForContext(ClassDecl); 13593 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 13594 13595 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 13596 SetDeclDeleted(DefaultCon, ClassLoc); 13597 13598 if (S) 13599 PushOnScopeChains(DefaultCon, S, false); 13600 ClassDecl->addDecl(DefaultCon); 13601 13602 return DefaultCon; 13603} 13604 13605void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 13606 CXXConstructorDecl *Constructor) { 13607 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", 13610, __extension__ __PRETTY_FUNCTION__
))
13608 !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", 13610, __extension__ __PRETTY_FUNCTION__
))
13609 !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", 13610, __extension__ __PRETTY_FUNCTION__
))
13610 "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", 13610, __extension__ __PRETTY_FUNCTION__
))
; 13611 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13612 return; 13613 13614 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13615 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", 13615, __extension__ __PRETTY_FUNCTION__
))
; 13616 13617 SynthesizedFunctionScope Scope(*this, Constructor); 13618 13619 // The exception specification is needed because we are defining the 13620 // function. 13621 ResolveExceptionSpec(CurrentLocation, 13622 Constructor->getType()->castAs<FunctionProtoType>()); 13623 MarkVTableUsed(CurrentLocation, ClassDecl); 13624 13625 // Add a context note for diagnostics produced after this point. 13626 Scope.addContextNote(CurrentLocation); 13627 13628 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13629 Constructor->setInvalidDecl(); 13630 return; 13631 } 13632 13633 SourceLocation Loc = Constructor->getEndLoc().isValid() 13634 ? Constructor->getEndLoc() 13635 : Constructor->getLocation(); 13636 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13637 Constructor->markUsed(Context); 13638 13639 if (ASTMutationListener *L = getASTMutationListener()) { 13640 L->CompletedImplicitDefinition(Constructor); 13641 } 13642 13643 DiagnoseUninitializedFields(*this, Constructor); 13644} 13645 13646void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13647 // Perform any delayed checks on exception specifications. 13648 CheckDelayedMemberExceptionSpecs(); 13649} 13650 13651/// Find or create the fake constructor we synthesize to model constructing an 13652/// object of a derived class via a constructor of a base class. 13653CXXConstructorDecl * 13654Sema::findInheritingConstructor(SourceLocation Loc, 13655 CXXConstructorDecl *BaseCtor, 13656 ConstructorUsingShadowDecl *Shadow) { 13657 CXXRecordDecl *Derived = Shadow->getParent(); 13658 SourceLocation UsingLoc = Shadow->getLocation(); 13659 13660 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13661 // For now we use the name of the base class constructor as a member of the 13662 // derived class to indicate a (fake) inherited constructor name. 13663 DeclarationName Name = BaseCtor->getDeclName(); 13664 13665 // Check to see if we already have a fake constructor for this inherited 13666 // constructor call. 13667 for (NamedDecl *Ctor : Derived->lookup(Name)) 13668 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13669 ->getInheritedConstructor() 13670 .getConstructor(), 13671 BaseCtor)) 13672 return cast<CXXConstructorDecl>(Ctor); 13673 13674 DeclarationNameInfo NameInfo(Name, UsingLoc); 13675 TypeSourceInfo *TInfo = 13676 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13677 FunctionProtoTypeLoc ProtoLoc = 13678 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13679 13680 // Check the inherited constructor is valid and find the list of base classes 13681 // from which it was inherited. 13682 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13683 13684 bool Constexpr = 13685 BaseCtor->isConstexpr() && 13686 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13687 false, BaseCtor, &ICI); 13688 13689 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13690 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13691 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 13692 /*isInline=*/true, 13693 /*isImplicitlyDeclared=*/true, 13694 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, 13695 InheritedConstructor(Shadow, BaseCtor), 13696 BaseCtor->getTrailingRequiresClause()); 13697 if (Shadow->isInvalidDecl()) 13698 DerivedCtor->setInvalidDecl(); 13699 13700 // Build an unevaluated exception specification for this fake constructor. 13701 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13702 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13703 EPI.ExceptionSpec.Type = EST_Unevaluated; 13704 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13705 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13706 FPT->getParamTypes(), EPI)); 13707 13708 // Build the parameter declarations. 13709 SmallVector<ParmVarDecl *, 16> ParamDecls; 13710 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13711 TypeSourceInfo *TInfo = 13712 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13713 ParmVarDecl *PD = ParmVarDecl::Create( 13714 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13715 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13716 PD->setScopeInfo(0, I); 13717 PD->setImplicit(); 13718 // Ensure attributes are propagated onto parameters (this matters for 13719 // format, pass_object_size, ...). 13720 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13721 ParamDecls.push_back(PD); 13722 ProtoLoc.setParam(I, PD); 13723 } 13724 13725 // Set up the new constructor. 13726 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", 13726, __extension__ __PRETTY_FUNCTION__
))
; 13727 DerivedCtor->setAccess(BaseCtor->getAccess()); 13728 DerivedCtor->setParams(ParamDecls); 13729 Derived->addDecl(DerivedCtor); 13730 13731 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13732 SetDeclDeleted(DerivedCtor, UsingLoc); 13733 13734 return DerivedCtor; 13735} 13736 13737void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13738 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13739 Ctor->getInheritedConstructor().getShadowDecl()); 13740 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13741 /*Diagnose*/true); 13742} 13743 13744void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13745 CXXConstructorDecl *Constructor) { 13746 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13747 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", 13749, __extension__ __PRETTY_FUNCTION__
))
13748 !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", 13749, __extension__ __PRETTY_FUNCTION__
))
13749 !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", 13749, __extension__ __PRETTY_FUNCTION__
))
; 13750 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13751 return; 13752 13753 // Initializations are performed "as if by a defaulted default constructor", 13754 // so enter the appropriate scope. 13755 SynthesizedFunctionScope Scope(*this, Constructor); 13756 13757 // The exception specification is needed because we are defining the 13758 // function. 13759 ResolveExceptionSpec(CurrentLocation, 13760 Constructor->getType()->castAs<FunctionProtoType>()); 13761 MarkVTableUsed(CurrentLocation, ClassDecl); 13762 13763 // Add a context note for diagnostics produced after this point. 13764 Scope.addContextNote(CurrentLocation); 13765 13766 ConstructorUsingShadowDecl *Shadow = 13767 Constructor->getInheritedConstructor().getShadowDecl(); 13768 CXXConstructorDecl *InheritedCtor = 13769 Constructor->getInheritedConstructor().getConstructor(); 13770 13771 // [class.inhctor.init]p1: 13772 // initialization proceeds as if a defaulted default constructor is used to 13773 // initialize the D object and each base class subobject from which the 13774 // constructor was inherited 13775 13776 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13777 CXXRecordDecl *RD = Shadow->getParent(); 13778 SourceLocation InitLoc = Shadow->getLocation(); 13779 13780 // Build explicit initializers for all base classes from which the 13781 // constructor was inherited. 13782 SmallVector<CXXCtorInitializer*, 8> Inits; 13783 for (bool VBase : {false, true}) { 13784 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13785 if (B.isVirtual() != VBase) 13786 continue; 13787 13788 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13789 if (!BaseRD) 13790 continue; 13791 13792 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13793 if (!BaseCtor.first) 13794 continue; 13795 13796 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13797 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13798 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13799 13800 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13801 Inits.push_back(new (Context) CXXCtorInitializer( 13802 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13803 SourceLocation())); 13804 } 13805 } 13806 13807 // We now proceed as if for a defaulted default constructor, with the relevant 13808 // initializers replaced. 13809 13810 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13811 Constructor->setInvalidDecl(); 13812 return; 13813 } 13814 13815 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13816 Constructor->markUsed(Context); 13817 13818 if (ASTMutationListener *L = getASTMutationListener()) { 13819 L->CompletedImplicitDefinition(Constructor); 13820 } 13821 13822 DiagnoseUninitializedFields(*this, Constructor); 13823} 13824 13825CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13826 // C++ [class.dtor]p2: 13827 // If a class has no user-declared destructor, a destructor is 13828 // declared implicitly. An implicitly-declared destructor is an 13829 // inline public member of its class. 13830 assert(ClassDecl->needsImplicitDestructor())(static_cast <bool> (ClassDecl->needsImplicitDestructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitDestructor()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 13830, __extension__ __PRETTY_FUNCTION__
))
; 13831 13832 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13833 if (DSM.isAlreadyBeingDeclared()) 13834 return nullptr; 13835 13836 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13837 CXXDestructor, 13838 false); 13839 13840 // Create the actual destructor declaration. 13841 CanQualType ClassType 13842 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13843 SourceLocation ClassLoc = ClassDecl->getLocation(); 13844 DeclarationName Name 13845 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13846 DeclarationNameInfo NameInfo(Name, ClassLoc); 13847 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create( 13848 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr, 13849 getCurFPFeatures().isFPConstrained(), 13850 /*isInline=*/true, 13851 /*isImplicitlyDeclared=*/true, 13852 Constexpr ? ConstexprSpecKind::Constexpr 13853 : ConstexprSpecKind::Unspecified); 13854 Destructor->setAccess(AS_public); 13855 Destructor->setDefaulted(); 13856 13857 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, std::nullopt); 13858 13859 if (getLangOpts().CUDA) 13860 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13861 Destructor, 13862 /* ConstRHS */ false, 13863 /* Diagnose */ false); 13864 13865 // We don't need to use SpecialMemberIsTrivial here; triviality for 13866 // destructors is easy to compute. 13867 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13868 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13869 ClassDecl->hasTrivialDestructorForCall()); 13870 13871 // Note that we have declared this destructor. 13872 ++getASTContext().NumImplicitDestructorsDeclared; 13873 13874 Scope *S = getScopeForContext(ClassDecl); 13875 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13876 13877 // We can't check whether an implicit destructor is deleted before we complete 13878 // the definition of the class, because its validity depends on the alignment 13879 // of the class. We'll check this from ActOnFields once the class is complete. 13880 if (ClassDecl->isCompleteDefinition() && 13881 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13882 SetDeclDeleted(Destructor, ClassLoc); 13883 13884 // Introduce this destructor into its scope. 13885 if (S) 13886 PushOnScopeChains(Destructor, S, false); 13887 ClassDecl->addDecl(Destructor); 13888 13889 return Destructor; 13890} 13891 13892void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13893 CXXDestructorDecl *Destructor) { 13894 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", 13897, __extension__ __PRETTY_FUNCTION__
))
13895 !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", 13897, __extension__ __PRETTY_FUNCTION__
))
13896 !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", 13897, __extension__ __PRETTY_FUNCTION__
))
13897 "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", 13897, __extension__ __PRETTY_FUNCTION__
))
; 13898 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13899 return; 13900 13901 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13902 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", 13902, __extension__ __PRETTY_FUNCTION__
))
; 13903 13904 SynthesizedFunctionScope Scope(*this, Destructor); 13905 13906 // The exception specification is needed because we are defining the 13907 // function. 13908 ResolveExceptionSpec(CurrentLocation, 13909 Destructor->getType()->castAs<FunctionProtoType>()); 13910 MarkVTableUsed(CurrentLocation, ClassDecl); 13911 13912 // Add a context note for diagnostics produced after this point. 13913 Scope.addContextNote(CurrentLocation); 13914 13915 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13916 Destructor->getParent()); 13917 13918 if (CheckDestructor(Destructor)) { 13919 Destructor->setInvalidDecl(); 13920 return; 13921 } 13922 13923 SourceLocation Loc = Destructor->getEndLoc().isValid() 13924 ? Destructor->getEndLoc() 13925 : Destructor->getLocation(); 13926 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13927 Destructor->markUsed(Context); 13928 13929 if (ASTMutationListener *L = getASTMutationListener()) { 13930 L->CompletedImplicitDefinition(Destructor); 13931 } 13932} 13933 13934void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13935 CXXDestructorDecl *Destructor) { 13936 if (Destructor->isInvalidDecl()) 13937 return; 13938 13939 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13940 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", 13941, __extension__ __PRETTY_FUNCTION__
))
13941 "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", 13941, __extension__ __PRETTY_FUNCTION__
))
; 13942 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", 13943, __extension__ __PRETTY_FUNCTION__
))
13943 "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", 13943, __extension__ __PRETTY_FUNCTION__
))
; 13944 13945 SynthesizedFunctionScope Scope(*this, Destructor); 13946 13947 // Add a context note for diagnostics produced after this point. 13948 Scope.addContextNote(CurrentLocation); 13949 13950 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13951} 13952 13953/// Perform any semantic analysis which needs to be delayed until all 13954/// pending class member declarations have been parsed. 13955void Sema::ActOnFinishCXXMemberDecls() { 13956 // If the context is an invalid C++ class, just suppress these checks. 13957 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13958 if (Record->isInvalidDecl()) { 13959 DelayedOverridingExceptionSpecChecks.clear(); 13960 DelayedEquivalentExceptionSpecChecks.clear(); 13961 return; 13962 } 13963 checkForMultipleExportedDefaultConstructors(*this, Record); 13964 } 13965} 13966 13967void Sema::ActOnFinishCXXNonNestedClass() { 13968 referenceDLLExportedClassMethods(); 13969 13970 if (!DelayedDllExportMemberFunctions.empty()) { 13971 SmallVector<CXXMethodDecl*, 4> WorkList; 13972 std::swap(DelayedDllExportMemberFunctions, WorkList); 13973 for (CXXMethodDecl *M : WorkList) { 13974 DefineDefaultedFunction(*this, M, M->getLocation()); 13975 13976 // Pass the method to the consumer to get emitted. This is not necessary 13977 // for explicit instantiation definitions, as they will get emitted 13978 // anyway. 13979 if (M->getParent()->getTemplateSpecializationKind() != 13980 TSK_ExplicitInstantiationDefinition) 13981 ActOnFinishInlineFunctionDef(M); 13982 } 13983 } 13984} 13985 13986void Sema::referenceDLLExportedClassMethods() { 13987 if (!DelayedDllExportClasses.empty()) { 13988 // Calling ReferenceDllExportedMembers might cause the current function to 13989 // be called again, so use a local copy of DelayedDllExportClasses. 13990 SmallVector<CXXRecordDecl *, 4> WorkList; 13991 std::swap(DelayedDllExportClasses, WorkList); 13992 for (CXXRecordDecl *Class : WorkList) 13993 ReferenceDllExportedMembers(*this, Class); 13994 } 13995} 13996 13997void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13998 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", 13999, __extension__ __PRETTY_FUNCTION__
))
13999 "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", 13999, __extension__ __PRETTY_FUNCTION__
))
; 14000 14001 if (Destructor->isDependentContext()) 14002 return; 14003 14004 // C++11 [class.dtor]p3: 14005 // A declaration of a destructor that does not have an exception- 14006 // specification is implicitly considered to have the same exception- 14007 // specification as an implicit declaration. 14008 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 14009 if (DtorType->hasExceptionSpec()) 14010 return; 14011 14012 // Replace the destructor's type, building off the existing one. Fortunately, 14013 // the only thing of interest in the destructor type is its extended info. 14014 // The return and arguments are fixed. 14015 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 14016 EPI.ExceptionSpec.Type = EST_Unevaluated; 14017 EPI.ExceptionSpec.SourceDecl = Destructor; 14018 Destructor->setType( 14019 Context.getFunctionType(Context.VoidTy, std::nullopt, EPI)); 14020 14021 // FIXME: If the destructor has a body that could throw, and the newly created 14022 // spec doesn't allow exceptions, we should emit a warning, because this 14023 // change in behavior can break conforming C++03 programs at runtime. 14024 // However, we don't have a body or an exception specification yet, so it 14025 // needs to be done somewhere else. 14026} 14027 14028namespace { 14029/// An abstract base class for all helper classes used in building the 14030// copy/move operators. These classes serve as factory functions and help us 14031// avoid using the same Expr* in the AST twice. 14032class ExprBuilder { 14033 ExprBuilder(const ExprBuilder&) = delete; 14034 ExprBuilder &operator=(const ExprBuilder&) = delete; 14035 14036protected: 14037 static Expr *assertNotNull(Expr *E) { 14038 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", 14038, __extension__ __PRETTY_FUNCTION__
))
; 14039 return E; 14040 } 14041 14042public: 14043 ExprBuilder() {} 14044 virtual ~ExprBuilder() {} 14045 14046 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 14047}; 14048 14049class RefBuilder: public ExprBuilder { 14050 VarDecl *Var; 14051 QualType VarType; 14052 14053public: 14054 Expr *build(Sema &S, SourceLocation Loc) const override { 14055 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 14056 } 14057 14058 RefBuilder(VarDecl *Var, QualType VarType) 14059 : Var(Var), VarType(VarType) {} 14060}; 14061 14062class ThisBuilder: public ExprBuilder { 14063public: 14064 Expr *build(Sema &S, SourceLocation Loc) const override { 14065 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 14066 } 14067}; 14068 14069class CastBuilder: public ExprBuilder { 14070 const ExprBuilder &Builder; 14071 QualType Type; 14072 ExprValueKind Kind; 14073 const CXXCastPath &Path; 14074 14075public: 14076 Expr *build(Sema &S, SourceLocation Loc) const override { 14077 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 14078 CK_UncheckedDerivedToBase, Kind, 14079 &Path).get()); 14080 } 14081 14082 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 14083 const CXXCastPath &Path) 14084 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 14085}; 14086 14087class DerefBuilder: public ExprBuilder { 14088 const ExprBuilder &Builder; 14089 14090public: 14091 Expr *build(Sema &S, SourceLocation Loc) const override { 14092 return assertNotNull( 14093 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 14094 } 14095 14096 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 14097}; 14098 14099class MemberBuilder: public ExprBuilder { 14100 const ExprBuilder &Builder; 14101 QualType Type; 14102 CXXScopeSpec SS; 14103 bool IsArrow; 14104 LookupResult &MemberLookup; 14105 14106public: 14107 Expr *build(Sema &S, SourceLocation Loc) const override { 14108 return assertNotNull(S.BuildMemberReferenceExpr( 14109 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 14110 nullptr, MemberLookup, nullptr, nullptr).get()); 14111 } 14112 14113 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 14114 LookupResult &MemberLookup) 14115 : Builder(Builder), Type(Type), IsArrow(IsArrow), 14116 MemberLookup(MemberLookup) {} 14117}; 14118 14119class MoveCastBuilder: public ExprBuilder { 14120 const ExprBuilder &Builder; 14121 14122public: 14123 Expr *build(Sema &S, SourceLocation Loc) const override { 14124 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 14125 } 14126 14127 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 14128}; 14129 14130class LvalueConvBuilder: public ExprBuilder { 14131 const ExprBuilder &Builder; 14132 14133public: 14134 Expr *build(Sema &S, SourceLocation Loc) const override { 14135 return assertNotNull( 14136 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 14137 } 14138 14139 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 14140}; 14141 14142class SubscriptBuilder: public ExprBuilder { 14143 const ExprBuilder &Base; 14144 const ExprBuilder &Index; 14145 14146public: 14147 Expr *build(Sema &S, SourceLocation Loc) const override { 14148 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 14149 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 14150 } 14151 14152 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 14153 : Base(Base), Index(Index) {} 14154}; 14155 14156} // end anonymous namespace 14157 14158/// When generating a defaulted copy or move assignment operator, if a field 14159/// should be copied with __builtin_memcpy rather than via explicit assignments, 14160/// do so. This optimization only applies for arrays of scalars, and for arrays 14161/// of class type where the selected copy/move-assignment operator is trivial. 14162static StmtResult 14163buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 14164 const ExprBuilder &ToB, const ExprBuilder &FromB) { 14165 // Compute the size of the memory buffer to be copied. 14166 QualType SizeType = S.Context.getSizeType(); 14167 llvm::APInt Size(S.Context.getTypeSize(SizeType), 14168 S.Context.getTypeSizeInChars(T).getQuantity()); 14169 14170 // Take the address of the field references for "from" and "to". We 14171 // directly construct UnaryOperators here because semantic analysis 14172 // does not permit us to take the address of an xvalue. 14173 Expr *From = FromB.build(S, Loc); 14174 From = UnaryOperator::Create( 14175 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 14176 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 14177 Expr *To = ToB.build(S, Loc); 14178 To = UnaryOperator::Create( 14179 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 14180 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 14181 14182 const Type *E = T->getBaseElementTypeUnsafe(); 14183 bool NeedsCollectableMemCpy = 14184 E->isRecordType() && 14185 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 14186 14187 // Create a reference to the __builtin_objc_memmove_collectable function 14188 StringRef MemCpyName = NeedsCollectableMemCpy ? 14189 "__builtin_objc_memmove_collectable" : 14190 "__builtin_memcpy"; 14191 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 14192 Sema::LookupOrdinaryName); 14193 S.LookupName(R, S.TUScope, true); 14194 14195 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 14196 if (!MemCpy) 14197 // Something went horribly wrong earlier, and we will have complained 14198 // about it. 14199 return StmtError(); 14200 14201 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 14202 VK_PRValue, Loc, nullptr); 14203 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", 14203, __extension__ __PRETTY_FUNCTION__
))
; 14204 14205 Expr *CallArgs[] = { 14206 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 14207 }; 14208 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 14209 Loc, CallArgs, Loc); 14210 14211 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", 14211, __extension__ __PRETTY_FUNCTION__
))
; 14212 return Call.getAs<Stmt>(); 14213} 14214 14215/// Builds a statement that copies/moves the given entity from \p From to 14216/// \c To. 14217/// 14218/// This routine is used to copy/move the members of a class with an 14219/// implicitly-declared copy/move assignment operator. When the entities being 14220/// copied are arrays, this routine builds for loops to copy them. 14221/// 14222/// \param S The Sema object used for type-checking. 14223/// 14224/// \param Loc The location where the implicit copy/move is being generated. 14225/// 14226/// \param T The type of the expressions being copied/moved. Both expressions 14227/// must have this type. 14228/// 14229/// \param To The expression we are copying/moving to. 14230/// 14231/// \param From The expression we are copying/moving from. 14232/// 14233/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 14234/// Otherwise, it's a non-static member subobject. 14235/// 14236/// \param Copying Whether we're copying or moving. 14237/// 14238/// \param Depth Internal parameter recording the depth of the recursion. 14239/// 14240/// \returns A statement or a loop that copies the expressions, or StmtResult(0) 14241/// if a memcpy should be used instead. 14242static StmtResult 14243buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 14244 const ExprBuilder &To, const ExprBuilder &From, 14245 bool CopyingBaseSubobject, bool Copying, 14246 unsigned Depth = 0) { 14247 // C++11 [class.copy]p28: 14248 // Each subobject is assigned in the manner appropriate to its type: 14249 // 14250 // - if the subobject is of class type, as if by a call to operator= with 14251 // the subobject as the object expression and the corresponding 14252 // subobject of x as a single function argument (as if by explicit 14253 // qualification; that is, ignoring any possible virtual overriding 14254 // functions in more derived classes); 14255 // 14256 // C++03 [class.copy]p13: 14257 // - if the subobject is of class type, the copy assignment operator for 14258 // the class is used (as if by explicit qualification; that is, 14259 // ignoring any possible virtual overriding functions in more derived 14260 // classes); 14261 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 14262 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 14263 14264 // Look for operator=. 14265 DeclarationName Name 14266 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14267 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 14268 S.LookupQualifiedName(OpLookup, ClassDecl, false); 14269 14270 // Prior to C++11, filter out any result that isn't a copy/move-assignment 14271 // operator. 14272 if (!S.getLangOpts().CPlusPlus11) { 14273 LookupResult::Filter F = OpLookup.makeFilter(); 14274 while (F.hasNext()) { 14275 NamedDecl *D = F.next(); 14276 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 14277 if (Method->isCopyAssignmentOperator() || 14278 (!Copying && Method->isMoveAssignmentOperator())) 14279 continue; 14280 14281 F.erase(); 14282 } 14283 F.done(); 14284 } 14285 14286 // Suppress the protected check (C++ [class.protected]) for each of the 14287 // assignment operators we found. This strange dance is required when 14288 // we're assigning via a base classes's copy-assignment operator. To 14289 // ensure that we're getting the right base class subobject (without 14290 // ambiguities), we need to cast "this" to that subobject type; to 14291 // ensure that we don't go through the virtual call mechanism, we need 14292 // to qualify the operator= name with the base class (see below). However, 14293 // this means that if the base class has a protected copy assignment 14294 // operator, the protected member access check will fail. So, we 14295 // rewrite "protected" access to "public" access in this case, since we 14296 // know by construction that we're calling from a derived class. 14297 if (CopyingBaseSubobject) { 14298 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 14299 L != LEnd; ++L) { 14300 if (L.getAccess() == AS_protected) 14301 L.setAccess(AS_public); 14302 } 14303 } 14304 14305 // Create the nested-name-specifier that will be used to qualify the 14306 // reference to operator=; this is required to suppress the virtual 14307 // call mechanism. 14308 CXXScopeSpec SS; 14309 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 14310 SS.MakeTrivial(S.Context, 14311 NestedNameSpecifier::Create(S.Context, nullptr, false, 14312 CanonicalT), 14313 Loc); 14314 14315 // Create the reference to operator=. 14316 ExprResult OpEqualRef 14317 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 14318 SS, /*TemplateKWLoc=*/SourceLocation(), 14319 /*FirstQualifierInScope=*/nullptr, 14320 OpLookup, 14321 /*TemplateArgs=*/nullptr, /*S*/nullptr, 14322 /*SuppressQualifierCheck=*/true); 14323 if (OpEqualRef.isInvalid()) 14324 return StmtError(); 14325 14326 // Build the call to the assignment operator. 14327 14328 Expr *FromInst = From.build(S, Loc); 14329 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 14330 OpEqualRef.getAs<Expr>(), 14331 Loc, FromInst, Loc); 14332 if (Call.isInvalid()) 14333 return StmtError(); 14334 14335 // If we built a call to a trivial 'operator=' while copying an array, 14336 // bail out. We'll replace the whole shebang with a memcpy. 14337 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 14338 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 14339 return StmtResult((Stmt*)nullptr); 14340 14341 // Convert to an expression-statement, and clean up any produced 14342 // temporaries. 14343 return S.ActOnExprStmt(Call); 14344 } 14345 14346 // - if the subobject is of scalar type, the built-in assignment 14347 // operator is used. 14348 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 14349 if (!ArrayTy) { 14350 ExprResult Assignment = S.CreateBuiltinBinOp( 14351 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 14352 if (Assignment.isInvalid()) 14353 return StmtError(); 14354 return S.ActOnExprStmt(Assignment); 14355 } 14356 14357 // - if the subobject is an array, each element is assigned, in the 14358 // manner appropriate to the element type; 14359 14360 // Construct a loop over the array bounds, e.g., 14361 // 14362 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 14363 // 14364 // that will copy each of the array elements. 14365 QualType SizeType = S.Context.getSizeType(); 14366 14367 // Create the iteration variable. 14368 IdentifierInfo *IterationVarName = nullptr; 14369 { 14370 SmallString<8> Str; 14371 llvm::raw_svector_ostream OS(Str); 14372 OS << "__i" << Depth; 14373 IterationVarName = &S.Context.Idents.get(OS.str()); 14374 } 14375 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 14376 IterationVarName, SizeType, 14377 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 14378 SC_None); 14379 14380 // Initialize the iteration variable to zero. 14381 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 14382 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 14383 14384 // Creates a reference to the iteration variable. 14385 RefBuilder IterationVarRef(IterationVar, SizeType); 14386 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 14387 14388 // Create the DeclStmt that holds the iteration variable. 14389 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 14390 14391 // Subscript the "from" and "to" expressions with the iteration variable. 14392 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 14393 MoveCastBuilder FromIndexMove(FromIndexCopy); 14394 const ExprBuilder *FromIndex; 14395 if (Copying) 14396 FromIndex = &FromIndexCopy; 14397 else 14398 FromIndex = &FromIndexMove; 14399 14400 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 14401 14402 // Build the copy/move for an individual element of the array. 14403 StmtResult Copy = 14404 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 14405 ToIndex, *FromIndex, CopyingBaseSubobject, 14406 Copying, Depth + 1); 14407 // Bail out if copying fails or if we determined that we should use memcpy. 14408 if (Copy.isInvalid() || !Copy.get()) 14409 return Copy; 14410 14411 // Create the comparison against the array bound. 14412 llvm::APInt Upper 14413 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 14414 Expr *Comparison = BinaryOperator::Create( 14415 S.Context, IterationVarRefRVal.build(S, Loc), 14416 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 14417 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc, 14418 S.CurFPFeatureOverrides()); 14419 14420 // Create the pre-increment of the iteration variable. We can determine 14421 // whether the increment will overflow based on the value of the array 14422 // bound. 14423 Expr *Increment = UnaryOperator::Create( 14424 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 14425 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 14426 14427 // Construct the loop that copies all elements of this array. 14428 return S.ActOnForStmt( 14429 Loc, Loc, InitStmt, 14430 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 14431 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 14432} 14433 14434static StmtResult 14435buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 14436 const ExprBuilder &To, const ExprBuilder &From, 14437 bool CopyingBaseSubobject, bool Copying) { 14438 // Maybe we should use a memcpy? 14439 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 14440 T.isTriviallyCopyableType(S.Context)) 14441 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14442 14443 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 14444 CopyingBaseSubobject, 14445 Copying, 0)); 14446 14447 // If we ended up picking a trivial assignment operator for an array of a 14448 // non-trivially-copyable class type, just emit a memcpy. 14449 if (!Result.isInvalid() && !Result.get()) 14450 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14451 14452 return Result; 14453} 14454 14455CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 14456 // Note: The following rules are largely analoguous to the copy 14457 // constructor rules. Note that virtual bases are not taken into account 14458 // for determining the argument type of the operator. Note also that 14459 // operators taking an object instead of a reference are allowed. 14460 assert(ClassDecl->needsImplicitCopyAssignment())(static_cast <bool> (ClassDecl->needsImplicitCopyAssignment
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitCopyAssignment()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 14460, __extension__ __PRETTY_FUNCTION__
))
; 14461 14462 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 14463 if (DSM.isAlreadyBeingDeclared()) 14464 return nullptr; 14465 14466 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14467 ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr); 14468 LangAS AS = getDefaultCXXMethodAddrSpace(); 14469 if (AS != LangAS::Default) 14470 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14471 QualType RetType = Context.getLValueReferenceType(ArgType); 14472 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 14473 if (Const) 14474 ArgType = ArgType.withConst(); 14475 14476 ArgType = Context.getLValueReferenceType(ArgType); 14477 14478 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14479 CXXCopyAssignment, 14480 Const); 14481 14482 // An implicitly-declared copy assignment operator is an inline public 14483 // member of its class. 14484 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14485 SourceLocation ClassLoc = ClassDecl->getLocation(); 14486 DeclarationNameInfo NameInfo(Name, ClassLoc); 14487 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 14488 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14489 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14490 getCurFPFeatures().isFPConstrained(), 14491 /*isInline=*/true, 14492 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14493 SourceLocation()); 14494 CopyAssignment->setAccess(AS_public); 14495 CopyAssignment->setDefaulted(); 14496 CopyAssignment->setImplicit(); 14497 14498 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 14499 14500 if (getLangOpts().CUDA) 14501 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 14502 CopyAssignment, 14503 /* ConstRHS */ Const, 14504 /* Diagnose */ false); 14505 14506 // Add the parameter to the operator. 14507 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 14508 ClassLoc, ClassLoc, 14509 /*Id=*/nullptr, ArgType, 14510 /*TInfo=*/nullptr, SC_None, 14511 nullptr); 14512 CopyAssignment->setParams(FromParam); 14513 14514 CopyAssignment->setTrivial( 14515 ClassDecl->needsOverloadResolutionForCopyAssignment() 14516 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 14517 : ClassDecl->hasTrivialCopyAssignment()); 14518 14519 // Note that we have added this copy-assignment operator. 14520 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 14521 14522 Scope *S = getScopeForContext(ClassDecl); 14523 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 14524 14525 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 14526 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 14527 SetDeclDeleted(CopyAssignment, ClassLoc); 14528 } 14529 14530 if (S) 14531 PushOnScopeChains(CopyAssignment, S, false); 14532 ClassDecl->addDecl(CopyAssignment); 14533 14534 return CopyAssignment; 14535} 14536 14537/// Diagnose an implicit copy operation for a class which is odr-used, but 14538/// which is deprecated because the class has a user-declared copy constructor, 14539/// copy assignment operator, or destructor. 14540static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 14541 assert(CopyOp->isImplicit())(static_cast <bool> (CopyOp->isImplicit()) ? void (0
) : __assert_fail ("CopyOp->isImplicit()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 14541, __extension__ __PRETTY_FUNCTION__))
; 14542 14543 CXXRecordDecl *RD = CopyOp->getParent(); 14544 CXXMethodDecl *UserDeclaredOperation = nullptr; 14545 14546 if (RD->hasUserDeclaredDestructor()) { 14547 UserDeclaredOperation = RD->getDestructor(); 14548 } else if (!isa<CXXConstructorDecl>(CopyOp) && 14549 RD->hasUserDeclaredCopyConstructor()) { 14550 // Find any user-declared copy constructor. 14551 for (auto *I : RD->ctors()) { 14552 if (I->isCopyConstructor()) { 14553 UserDeclaredOperation = I; 14554 break; 14555 } 14556 } 14557 assert(UserDeclaredOperation)(static_cast <bool> (UserDeclaredOperation) ? void (0) :
__assert_fail ("UserDeclaredOperation", "clang/lib/Sema/SemaDeclCXX.cpp"
, 14557, __extension__ __PRETTY_FUNCTION__))
; 14558 } else if (isa<CXXConstructorDecl>(CopyOp) && 14559 RD->hasUserDeclaredCopyAssignment()) { 14560 // Find any user-declared move assignment operator. 14561 for (auto *I : RD->methods()) { 14562 if (I->isCopyAssignmentOperator()) { 14563 UserDeclaredOperation = I; 14564 break; 14565 } 14566 } 14567 assert(UserDeclaredOperation)(static_cast <bool> (UserDeclaredOperation) ? void (0) :
__assert_fail ("UserDeclaredOperation", "clang/lib/Sema/SemaDeclCXX.cpp"
, 14567, __extension__ __PRETTY_FUNCTION__))
; 14568 } 14569 14570 if (UserDeclaredOperation) { 14571 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided(); 14572 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation); 14573 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp); 14574 unsigned DiagID = 14575 (UDOIsUserProvided && UDOIsDestructor) 14576 ? diag::warn_deprecated_copy_with_user_provided_dtor 14577 : (UDOIsUserProvided && !UDOIsDestructor) 14578 ? diag::warn_deprecated_copy_with_user_provided_copy 14579 : (!UDOIsUserProvided && UDOIsDestructor) 14580 ? diag::warn_deprecated_copy_with_dtor 14581 : diag::warn_deprecated_copy; 14582 S.Diag(UserDeclaredOperation->getLocation(), DiagID) 14583 << RD << IsCopyAssignment; 14584 } 14585} 14586 14587void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 14588 CXXMethodDecl *CopyAssignOperator) { 14589 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", 14594, __extension__ __PRETTY_FUNCTION__
))
14590 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", 14594, __extension__ __PRETTY_FUNCTION__
))
14591 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", 14594, __extension__ __PRETTY_FUNCTION__
))
14592 !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", 14594, __extension__ __PRETTY_FUNCTION__
))
14593 !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", 14594, __extension__ __PRETTY_FUNCTION__
))
14594 "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", 14594, __extension__ __PRETTY_FUNCTION__
))
; 14595 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 14596 return; 14597 14598 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 14599 if (ClassDecl->isInvalidDecl()) { 14600 CopyAssignOperator->setInvalidDecl(); 14601 return; 14602 } 14603 14604 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 14605 14606 // The exception specification is needed because we are defining the 14607 // function. 14608 ResolveExceptionSpec(CurrentLocation, 14609 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 14610 14611 // Add a context note for diagnostics produced after this point. 14612 Scope.addContextNote(CurrentLocation); 14613 14614 // C++11 [class.copy]p18: 14615 // The [definition of an implicitly declared copy assignment operator] is 14616 // deprecated if the class has a user-declared copy constructor or a 14617 // user-declared destructor. 14618 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 14619 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 14620 14621 // C++0x [class.copy]p30: 14622 // The implicitly-defined or explicitly-defaulted copy assignment operator 14623 // for a non-union class X performs memberwise copy assignment of its 14624 // subobjects. The direct base classes of X are assigned first, in the 14625 // order of their declaration in the base-specifier-list, and then the 14626 // immediate non-static data members of X are assigned, in the order in 14627 // which they were declared in the class definition. 14628 14629 // The statements that form the synthesized function body. 14630 SmallVector<Stmt*, 8> Statements; 14631 14632 // The parameter for the "other" object, which we are copying from. 14633 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 14634 Qualifiers OtherQuals = Other->getType().getQualifiers(); 14635 QualType OtherRefType = Other->getType(); 14636 if (const LValueReferenceType *OtherRef 14637 = OtherRefType->getAs<LValueReferenceType>()) { 14638 OtherRefType = OtherRef->getPointeeType(); 14639 OtherQuals = OtherRefType.getQualifiers(); 14640 } 14641 14642 // Our location for everything implicitly-generated. 14643 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14644 ? CopyAssignOperator->getEndLoc() 14645 : CopyAssignOperator->getLocation(); 14646 14647 // Builds a DeclRefExpr for the "other" object. 14648 RefBuilder OtherRef(Other, OtherRefType); 14649 14650 // Builds the "this" pointer. 14651 ThisBuilder This; 14652 14653 // Assign base classes. 14654 bool Invalid = false; 14655 for (auto &Base : ClassDecl->bases()) { 14656 // Form the assignment: 14657 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14658 QualType BaseType = Base.getType().getUnqualifiedType(); 14659 if (!BaseType->isRecordType()) { 14660 Invalid = true; 14661 continue; 14662 } 14663 14664 CXXCastPath BasePath; 14665 BasePath.push_back(&Base); 14666 14667 // Construct the "from" expression, which is an implicit cast to the 14668 // appropriately-qualified base type. 14669 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14670 VK_LValue, BasePath); 14671 14672 // Dereference "this". 14673 DerefBuilder DerefThis(This); 14674 CastBuilder To(DerefThis, 14675 Context.getQualifiedType( 14676 BaseType, CopyAssignOperator->getMethodQualifiers()), 14677 VK_LValue, BasePath); 14678 14679 // Build the copy. 14680 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14681 To, From, 14682 /*CopyingBaseSubobject=*/true, 14683 /*Copying=*/true); 14684 if (Copy.isInvalid()) { 14685 CopyAssignOperator->setInvalidDecl(); 14686 return; 14687 } 14688 14689 // Success! Record the copy. 14690 Statements.push_back(Copy.getAs<Expr>()); 14691 } 14692 14693 // Assign non-static members. 14694 for (auto *Field : ClassDecl->fields()) { 14695 // FIXME: We should form some kind of AST representation for the implied 14696 // memcpy in a union copy operation. 14697 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14698 continue; 14699 14700 if (Field->isInvalidDecl()) { 14701 Invalid = true; 14702 continue; 14703 } 14704 14705 // Check for members of reference type; we can't copy those. 14706 if (Field->getType()->isReferenceType()) { 14707 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14708 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14709 Diag(Field->getLocation(), diag::note_declared_at); 14710 Invalid = true; 14711 continue; 14712 } 14713 14714 // Check for members of const-qualified, non-class type. 14715 QualType BaseType = Context.getBaseElementType(Field->getType()); 14716 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14717 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14718 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14719 Diag(Field->getLocation(), diag::note_declared_at); 14720 Invalid = true; 14721 continue; 14722 } 14723 14724 // Suppress assigning zero-width bitfields. 14725 if (Field->isZeroLengthBitField(Context)) 14726 continue; 14727 14728 QualType FieldType = Field->getType().getNonReferenceType(); 14729 if (FieldType->isIncompleteArrayType()) { 14730 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", 14731, __extension__ __PRETTY_FUNCTION__
))
14731 "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", 14731, __extension__ __PRETTY_FUNCTION__
))
; 14732 continue; 14733 } 14734 14735 // Build references to the field in the object we're copying from and to. 14736 CXXScopeSpec SS; // Intentionally empty 14737 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14738 LookupMemberName); 14739 MemberLookup.addDecl(Field); 14740 MemberLookup.resolveKind(); 14741 14742 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14743 14744 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/!LangOpts.HLSL, 14745 MemberLookup); 14746 14747 // Build the copy of this field. 14748 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14749 To, From, 14750 /*CopyingBaseSubobject=*/false, 14751 /*Copying=*/true); 14752 if (Copy.isInvalid()) { 14753 CopyAssignOperator->setInvalidDecl(); 14754 return; 14755 } 14756 14757 // Success! Record the copy. 14758 Statements.push_back(Copy.getAs<Stmt>()); 14759 } 14760 14761 if (!Invalid) { 14762 // Add a "return *this;" 14763 Expr *ThisExpr = nullptr; 14764 if (!LangOpts.HLSL) { 14765 ExprResult ThisObj = 14766 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14767 ThisExpr = ThisObj.get(); 14768 } else { 14769 ThisExpr = This.build(*this, Loc); 14770 } 14771 14772 StmtResult Return = BuildReturnStmt(Loc, ThisExpr); 14773 if (Return.isInvalid()) 14774 Invalid = true; 14775 else 14776 Statements.push_back(Return.getAs<Stmt>()); 14777 } 14778 14779 if (Invalid) { 14780 CopyAssignOperator->setInvalidDecl(); 14781 return; 14782 } 14783 14784 StmtResult Body; 14785 { 14786 CompoundScopeRAII CompoundScope(*this); 14787 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14788 /*isStmtExpr=*/false); 14789 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", 14789, __extension__ __PRETTY_FUNCTION__
))
; 14790 } 14791 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14792 CopyAssignOperator->markUsed(Context); 14793 14794 if (ASTMutationListener *L = getASTMutationListener()) { 14795 L->CompletedImplicitDefinition(CopyAssignOperator); 14796 } 14797} 14798 14799CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14800 assert(ClassDecl->needsImplicitMoveAssignment())(static_cast <bool> (ClassDecl->needsImplicitMoveAssignment
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitMoveAssignment()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 14800, __extension__ __PRETTY_FUNCTION__
))
; 14801 14802 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14803 if (DSM.isAlreadyBeingDeclared()) 14804 return nullptr; 14805 14806 // Note: The following rules are largely analoguous to the move 14807 // constructor rules. 14808 14809 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14810 ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr); 14811 LangAS AS = getDefaultCXXMethodAddrSpace(); 14812 if (AS != LangAS::Default) 14813 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14814 QualType RetType = Context.getLValueReferenceType(ArgType); 14815 ArgType = Context.getRValueReferenceType(ArgType); 14816 14817 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14818 CXXMoveAssignment, 14819 false); 14820 14821 // An implicitly-declared move assignment operator is an inline public 14822 // member of its class. 14823 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14824 SourceLocation ClassLoc = ClassDecl->getLocation(); 14825 DeclarationNameInfo NameInfo(Name, ClassLoc); 14826 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14827 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14828 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14829 getCurFPFeatures().isFPConstrained(), 14830 /*isInline=*/true, 14831 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14832 SourceLocation()); 14833 MoveAssignment->setAccess(AS_public); 14834 MoveAssignment->setDefaulted(); 14835 MoveAssignment->setImplicit(); 14836 14837 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType); 14838 14839 if (getLangOpts().CUDA) 14840 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14841 MoveAssignment, 14842 /* ConstRHS */ false, 14843 /* Diagnose */ false); 14844 14845 // Add the parameter to the operator. 14846 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14847 ClassLoc, ClassLoc, 14848 /*Id=*/nullptr, ArgType, 14849 /*TInfo=*/nullptr, SC_None, 14850 nullptr); 14851 MoveAssignment->setParams(FromParam); 14852 14853 MoveAssignment->setTrivial( 14854 ClassDecl->needsOverloadResolutionForMoveAssignment() 14855 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14856 : ClassDecl->hasTrivialMoveAssignment()); 14857 14858 // Note that we have added this copy-assignment operator. 14859 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14860 14861 Scope *S = getScopeForContext(ClassDecl); 14862 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14863 14864 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14865 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14866 SetDeclDeleted(MoveAssignment, ClassLoc); 14867 } 14868 14869 if (S) 14870 PushOnScopeChains(MoveAssignment, S, false); 14871 ClassDecl->addDecl(MoveAssignment); 14872 14873 return MoveAssignment; 14874} 14875 14876/// Check if we're implicitly defining a move assignment operator for a class 14877/// with virtual bases. Such a move assignment might move-assign the virtual 14878/// base multiple times. 14879static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14880 SourceLocation CurrentLocation) { 14881 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", 14881, __extension__ __PRETTY_FUNCTION__
))
; 14882 14883 // Only a virtual base could get implicitly move-assigned multiple times. 14884 // Only a non-trivial move assignment can observe this. We only want to 14885 // diagnose if we implicitly define an assignment operator that assigns 14886 // two base classes, both of which move-assign the same virtual base. 14887 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14888 Class->getNumBases() < 2) 14889 return; 14890 14891 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14892 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14893 VBaseMap VBases; 14894 14895 for (auto &BI : Class->bases()) { 14896 Worklist.push_back(&BI); 14897 while (!Worklist.empty()) { 14898 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14899 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14900 14901 // If the base has no non-trivial move assignment operators, 14902 // we don't care about moves from it. 14903 if (!Base->hasNonTrivialMoveAssignment()) 14904 continue; 14905 14906 // If there's nothing virtual here, skip it. 14907 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14908 continue; 14909 14910 // If we're not actually going to call a move assignment for this base, 14911 // or the selected move assignment is trivial, skip it. 14912 Sema::SpecialMemberOverloadResult SMOR = 14913 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14914 /*ConstArg*/false, /*VolatileArg*/false, 14915 /*RValueThis*/true, /*ConstThis*/false, 14916 /*VolatileThis*/false); 14917 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14918 !SMOR.getMethod()->isMoveAssignmentOperator()) 14919 continue; 14920 14921 if (BaseSpec->isVirtual()) { 14922 // We're going to move-assign this virtual base, and its move 14923 // assignment operator is not trivial. If this can happen for 14924 // multiple distinct direct bases of Class, diagnose it. (If it 14925 // only happens in one base, we'll diagnose it when synthesizing 14926 // that base class's move assignment operator.) 14927 CXXBaseSpecifier *&Existing = 14928 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14929 .first->second; 14930 if (Existing && Existing != &BI) { 14931 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14932 << Class << Base; 14933 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14934 << (Base->getCanonicalDecl() == 14935 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14936 << Base << Existing->getType() << Existing->getSourceRange(); 14937 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14938 << (Base->getCanonicalDecl() == 14939 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14940 << Base << BI.getType() << BaseSpec->getSourceRange(); 14941 14942 // Only diagnose each vbase once. 14943 Existing = nullptr; 14944 } 14945 } else { 14946 // Only walk over bases that have defaulted move assignment operators. 14947 // We assume that any user-provided move assignment operator handles 14948 // the multiple-moves-of-vbase case itself somehow. 14949 if (!SMOR.getMethod()->isDefaulted()) 14950 continue; 14951 14952 // We're going to move the base classes of Base. Add them to the list. 14953 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases())); 14954 } 14955 } 14956 } 14957} 14958 14959void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14960 CXXMethodDecl *MoveAssignOperator) { 14961 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", 14966, __extension__ __PRETTY_FUNCTION__
))
14962 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", 14966, __extension__ __PRETTY_FUNCTION__
))
14963 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", 14966, __extension__ __PRETTY_FUNCTION__
))
14964 !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", 14966, __extension__ __PRETTY_FUNCTION__
))
14965 !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", 14966, __extension__ __PRETTY_FUNCTION__
))
14966 "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", 14966, __extension__ __PRETTY_FUNCTION__
))
; 14967 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14968 return; 14969 14970 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14971 if (ClassDecl->isInvalidDecl()) { 14972 MoveAssignOperator->setInvalidDecl(); 14973 return; 14974 } 14975 14976 // C++0x [class.copy]p28: 14977 // The implicitly-defined or move assignment operator for a non-union class 14978 // X performs memberwise move assignment of its subobjects. The direct base 14979 // classes of X are assigned first, in the order of their declaration in the 14980 // base-specifier-list, and then the immediate non-static data members of X 14981 // are assigned, in the order in which they were declared in the class 14982 // definition. 14983 14984 // Issue a warning if our implicit move assignment operator will move 14985 // from a virtual base more than once. 14986 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14987 14988 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14989 14990 // The exception specification is needed because we are defining the 14991 // function. 14992 ResolveExceptionSpec(CurrentLocation, 14993 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14994 14995 // Add a context note for diagnostics produced after this point. 14996 Scope.addContextNote(CurrentLocation); 14997 14998 // The statements that form the synthesized function body. 14999 SmallVector<Stmt*, 8> Statements; 15000 15001 // The parameter for the "other" object, which we are move from. 15002 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 15003 QualType OtherRefType = 15004 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 15005 15006 // Our location for everything implicitly-generated. 15007 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 15008 ? MoveAssignOperator->getEndLoc() 15009 : MoveAssignOperator->getLocation(); 15010 15011 // Builds a reference to the "other" object. 15012 RefBuilder OtherRef(Other, OtherRefType); 15013 // Cast to rvalue. 15014 MoveCastBuilder MoveOther(OtherRef); 15015 15016 // Builds the "this" pointer. 15017 ThisBuilder This; 15018 15019 // Assign base classes. 15020 bool Invalid = false; 15021 for (auto &Base : ClassDecl->bases()) { 15022 // C++11 [class.copy]p28: 15023 // It is unspecified whether subobjects representing virtual base classes 15024 // are assigned more than once by the implicitly-defined copy assignment 15025 // operator. 15026 // FIXME: Do not assign to a vbase that will be assigned by some other base 15027 // class. For a move-assignment, this can result in the vbase being moved 15028 // multiple times. 15029 15030 // Form the assignment: 15031 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 15032 QualType BaseType = Base.getType().getUnqualifiedType(); 15033 if (!BaseType->isRecordType()) { 15034 Invalid = true; 15035 continue; 15036 } 15037 15038 CXXCastPath BasePath; 15039 BasePath.push_back(&Base); 15040 15041 // Construct the "from" expression, which is an implicit cast to the 15042 // appropriately-qualified base type. 15043 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 15044 15045 // Dereference "this". 15046 DerefBuilder DerefThis(This); 15047 15048 // Implicitly cast "this" to the appropriately-qualified base type. 15049 CastBuilder To(DerefThis, 15050 Context.getQualifiedType( 15051 BaseType, MoveAssignOperator->getMethodQualifiers()), 15052 VK_LValue, BasePath); 15053 15054 // Build the move. 15055 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 15056 To, From, 15057 /*CopyingBaseSubobject=*/true, 15058 /*Copying=*/false); 15059 if (Move.isInvalid()) { 15060 MoveAssignOperator->setInvalidDecl(); 15061 return; 15062 } 15063 15064 // Success! Record the move. 15065 Statements.push_back(Move.getAs<Expr>()); 15066 } 15067 15068 // Assign non-static members. 15069 for (auto *Field : ClassDecl->fields()) { 15070 // FIXME: We should form some kind of AST representation for the implied 15071 // memcpy in a union copy operation. 15072 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 15073 continue; 15074 15075 if (Field->isInvalidDecl()) { 15076 Invalid = true; 15077 continue; 15078 } 15079 15080 // Check for members of reference type; we can't move those. 15081 if (Field->getType()->isReferenceType()) { 15082 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 15083 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 15084 Diag(Field->getLocation(), diag::note_declared_at); 15085 Invalid = true; 15086 continue; 15087 } 15088 15089 // Check for members of const-qualified, non-class type. 15090 QualType BaseType = Context.getBaseElementType(Field->getType()); 15091 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 15092 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 15093 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 15094 Diag(Field->getLocation(), diag::note_declared_at); 15095 Invalid = true; 15096 continue; 15097 } 15098 15099 // Suppress assigning zero-width bitfields. 15100 if (Field->isZeroLengthBitField(Context)) 15101 continue; 15102 15103 QualType FieldType = Field->getType().getNonReferenceType(); 15104 if (FieldType->isIncompleteArrayType()) { 15105 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", 15106, __extension__ __PRETTY_FUNCTION__
))
15106 "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", 15106, __extension__ __PRETTY_FUNCTION__
))
; 15107 continue; 15108 } 15109 15110 // Build references to the field in the object we're copying from and to. 15111 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 15112 LookupMemberName); 15113 MemberLookup.addDecl(Field); 15114 MemberLookup.resolveKind(); 15115 MemberBuilder From(MoveOther, OtherRefType, 15116 /*IsArrow=*/false, MemberLookup); 15117 MemberBuilder To(This, getCurrentThisType(), 15118 /*IsArrow=*/true, MemberLookup); 15119 15120 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", 15122, __extension__ __PRETTY_FUNCTION__
))
15121 "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", 15122, __extension__ __PRETTY_FUNCTION__
))
15122 "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", 15122, __extension__ __PRETTY_FUNCTION__
))
; 15123 15124 // Build the move of this field. 15125 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 15126 To, From, 15127 /*CopyingBaseSubobject=*/false, 15128 /*Copying=*/false); 15129 if (Move.isInvalid()) { 15130 MoveAssignOperator->setInvalidDecl(); 15131 return; 15132 } 15133 15134 // Success! Record the copy. 15135 Statements.push_back(Move.getAs<Stmt>()); 15136 } 15137 15138 if (!Invalid) { 15139 // Add a "return *this;" 15140 ExprResult ThisObj = 15141 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 15142 15143 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 15144 if (Return.isInvalid()) 15145 Invalid = true; 15146 else 15147 Statements.push_back(Return.getAs<Stmt>()); 15148 } 15149 15150 if (Invalid) { 15151 MoveAssignOperator->setInvalidDecl(); 15152 return; 15153 } 15154 15155 StmtResult Body; 15156 { 15157 CompoundScopeRAII CompoundScope(*this); 15158 Body = ActOnCompoundStmt(Loc, Loc, Statements, 15159 /*isStmtExpr=*/false); 15160 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", 15160, __extension__ __PRETTY_FUNCTION__
))
; 15161 } 15162 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 15163 MoveAssignOperator->markUsed(Context); 15164 15165 if (ASTMutationListener *L = getASTMutationListener()) { 15166 L->CompletedImplicitDefinition(MoveAssignOperator); 15167 } 15168} 15169 15170CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 15171 CXXRecordDecl *ClassDecl) { 15172 // C++ [class.copy]p4: 15173 // If the class definition does not explicitly declare a copy 15174 // constructor, one is declared implicitly. 15175 assert(ClassDecl->needsImplicitCopyConstructor())(static_cast <bool> (ClassDecl->needsImplicitCopyConstructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitCopyConstructor()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15175, __extension__ __PRETTY_FUNCTION__
))
; 15176 15177 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 15178 if (DSM.isAlreadyBeingDeclared()) 15179 return nullptr; 15180 15181 QualType ClassType = Context.getTypeDeclType(ClassDecl); 15182 QualType ArgType = ClassType; 15183 ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr); 15184 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 15185 if (Const) 15186 ArgType = ArgType.withConst(); 15187 15188 LangAS AS = getDefaultCXXMethodAddrSpace(); 15189 if (AS != LangAS::Default) 15190 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 15191 15192 ArgType = Context.getLValueReferenceType(ArgType); 15193 15194 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 15195 CXXCopyConstructor, 15196 Const); 15197 15198 DeclarationName Name 15199 = Context.DeclarationNames.getCXXConstructorName( 15200 Context.getCanonicalType(ClassType)); 15201 SourceLocation ClassLoc = ClassDecl->getLocation(); 15202 DeclarationNameInfo NameInfo(Name, ClassLoc); 15203 15204 // An implicitly-declared copy constructor is an inline public 15205 // member of its class. 15206 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 15207 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 15208 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 15209 /*isInline=*/true, 15210 /*isImplicitlyDeclared=*/true, 15211 Constexpr ? ConstexprSpecKind::Constexpr 15212 : ConstexprSpecKind::Unspecified); 15213 CopyConstructor->setAccess(AS_public); 15214 CopyConstructor->setDefaulted(); 15215 15216 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 15217 15218 if (getLangOpts().CUDA) 15219 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 15220 CopyConstructor, 15221 /* ConstRHS */ Const, 15222 /* Diagnose */ false); 15223 15224 // During template instantiation of special member functions we need a 15225 // reliable TypeSourceInfo for the parameter types in order to allow functions 15226 // to be substituted. 15227 TypeSourceInfo *TSI = nullptr; 15228 if (inTemplateInstantiation() && ClassDecl->isLambda()) 15229 TSI = Context.getTrivialTypeSourceInfo(ArgType); 15230 15231 // Add the parameter to the constructor. 15232 ParmVarDecl *FromParam = 15233 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc, 15234 /*IdentifierInfo=*/nullptr, ArgType, 15235 /*TInfo=*/TSI, SC_None, nullptr); 15236 CopyConstructor->setParams(FromParam); 15237 15238 CopyConstructor->setTrivial( 15239 ClassDecl->needsOverloadResolutionForCopyConstructor() 15240 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 15241 : ClassDecl->hasTrivialCopyConstructor()); 15242 15243 CopyConstructor->setTrivialForCall( 15244 ClassDecl->hasAttr<TrivialABIAttr>() || 15245 (ClassDecl->needsOverloadResolutionForCopyConstructor() 15246 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 15247 TAH_ConsiderTrivialABI) 15248 : ClassDecl->hasTrivialCopyConstructorForCall())); 15249 15250 // Note that we have declared this constructor. 15251 ++getASTContext().NumImplicitCopyConstructorsDeclared; 15252 15253 Scope *S = getScopeForContext(ClassDecl); 15254 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 15255 15256 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 15257 ClassDecl->setImplicitCopyConstructorIsDeleted(); 15258 SetDeclDeleted(CopyConstructor, ClassLoc); 15259 } 15260 15261 if (S) 15262 PushOnScopeChains(CopyConstructor, S, false); 15263 ClassDecl->addDecl(CopyConstructor); 15264 15265 return CopyConstructor; 15266} 15267 15268void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 15269 CXXConstructorDecl *CopyConstructor) { 15270 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", 15274, __extension__ __PRETTY_FUNCTION__
))
15271 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", 15274, __extension__ __PRETTY_FUNCTION__
))
15272 !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", 15274, __extension__ __PRETTY_FUNCTION__
))
15273 !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", 15274, __extension__ __PRETTY_FUNCTION__
))
15274 "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", 15274, __extension__ __PRETTY_FUNCTION__
))
; 15275 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 15276 return; 15277 15278 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 15279 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", 15279, __extension__ __PRETTY_FUNCTION__
))
; 15280 15281 SynthesizedFunctionScope Scope(*this, CopyConstructor); 15282 15283 // The exception specification is needed because we are defining the 15284 // function. 15285 ResolveExceptionSpec(CurrentLocation, 15286 CopyConstructor->getType()->castAs<FunctionProtoType>()); 15287 MarkVTableUsed(CurrentLocation, ClassDecl); 15288 15289 // Add a context note for diagnostics produced after this point. 15290 Scope.addContextNote(CurrentLocation); 15291 15292 // C++11 [class.copy]p7: 15293 // The [definition of an implicitly declared copy constructor] is 15294 // deprecated if the class has a user-declared copy assignment operator 15295 // or a user-declared destructor. 15296 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 15297 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 15298 15299 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 15300 CopyConstructor->setInvalidDecl(); 15301 } else { 15302 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 15303 ? CopyConstructor->getEndLoc() 15304 : CopyConstructor->getLocation(); 15305 Sema::CompoundScopeRAII CompoundScope(*this); 15306 CopyConstructor->setBody( 15307 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false) 15308 .getAs<Stmt>()); 15309 CopyConstructor->markUsed(Context); 15310 } 15311 15312 if (ASTMutationListener *L = getASTMutationListener()) { 15313 L->CompletedImplicitDefinition(CopyConstructor); 15314 } 15315} 15316 15317CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 15318 CXXRecordDecl *ClassDecl) { 15319 assert(ClassDecl->needsImplicitMoveConstructor())(static_cast <bool> (ClassDecl->needsImplicitMoveConstructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitMoveConstructor()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15319, __extension__ __PRETTY_FUNCTION__
))
; 15320 15321 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 15322 if (DSM.isAlreadyBeingDeclared()) 15323 return nullptr; 15324 15325 QualType ClassType = Context.getTypeDeclType(ClassDecl); 15326 15327 QualType ArgType = ClassType; 15328 ArgType = Context.getElaboratedType(ETK_None, nullptr, ArgType, nullptr); 15329 LangAS AS = getDefaultCXXMethodAddrSpace(); 15330 if (AS != LangAS::Default) 15331 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 15332 ArgType = Context.getRValueReferenceType(ArgType); 15333 15334 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 15335 CXXMoveConstructor, 15336 false); 15337 15338 DeclarationName Name 15339 = Context.DeclarationNames.getCXXConstructorName( 15340 Context.getCanonicalType(ClassType)); 15341 SourceLocation ClassLoc = ClassDecl->getLocation(); 15342 DeclarationNameInfo NameInfo(Name, ClassLoc); 15343 15344 // C++11 [class.copy]p11: 15345 // An implicitly-declared copy/move constructor is an inline public 15346 // member of its class. 15347 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 15348 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 15349 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 15350 /*isInline=*/true, 15351 /*isImplicitlyDeclared=*/true, 15352 Constexpr ? ConstexprSpecKind::Constexpr 15353 : ConstexprSpecKind::Unspecified); 15354 MoveConstructor->setAccess(AS_public); 15355 MoveConstructor->setDefaulted(); 15356 15357 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 15358 15359 if (getLangOpts().CUDA) 15360 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 15361 MoveConstructor, 15362 /* ConstRHS */ false, 15363 /* Diagnose */ false); 15364 15365 // Add the parameter to the constructor. 15366 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 15367 ClassLoc, ClassLoc, 15368 /*IdentifierInfo=*/nullptr, 15369 ArgType, /*TInfo=*/nullptr, 15370 SC_None, nullptr); 15371 MoveConstructor->setParams(FromParam); 15372 15373 MoveConstructor->setTrivial( 15374 ClassDecl->needsOverloadResolutionForMoveConstructor() 15375 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 15376 : ClassDecl->hasTrivialMoveConstructor()); 15377 15378 MoveConstructor->setTrivialForCall( 15379 ClassDecl->hasAttr<TrivialABIAttr>() || 15380 (ClassDecl->needsOverloadResolutionForMoveConstructor() 15381 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 15382 TAH_ConsiderTrivialABI) 15383 : ClassDecl->hasTrivialMoveConstructorForCall())); 15384 15385 // Note that we have declared this constructor. 15386 ++getASTContext().NumImplicitMoveConstructorsDeclared; 15387 15388 Scope *S = getScopeForContext(ClassDecl); 15389 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 15390 15391 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 15392 ClassDecl->setImplicitMoveConstructorIsDeleted(); 15393 SetDeclDeleted(MoveConstructor, ClassLoc); 15394 } 15395 15396 if (S) 15397 PushOnScopeChains(MoveConstructor, S, false); 15398 ClassDecl->addDecl(MoveConstructor); 15399 15400 return MoveConstructor; 15401} 15402 15403void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 15404 CXXConstructorDecl *MoveConstructor) { 15405 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", 15409, __extension__ __PRETTY_FUNCTION__
))
15406 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", 15409, __extension__ __PRETTY_FUNCTION__
))
15407 !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", 15409, __extension__ __PRETTY_FUNCTION__
))
15408 !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", 15409, __extension__ __PRETTY_FUNCTION__
))
15409 "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", 15409, __extension__ __PRETTY_FUNCTION__
))
; 15410 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 15411 return; 15412 15413 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 15414 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", 15414, __extension__ __PRETTY_FUNCTION__
))
; 15415 15416 SynthesizedFunctionScope Scope(*this, MoveConstructor); 15417 15418 // The exception specification is needed because we are defining the 15419 // function. 15420 ResolveExceptionSpec(CurrentLocation, 15421 MoveConstructor->getType()->castAs<FunctionProtoType>()); 15422 MarkVTableUsed(CurrentLocation, ClassDecl); 15423 15424 // Add a context note for diagnostics produced after this point. 15425 Scope.addContextNote(CurrentLocation); 15426 15427 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 15428 MoveConstructor->setInvalidDecl(); 15429 } else { 15430 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 15431 ? MoveConstructor->getEndLoc() 15432 : MoveConstructor->getLocation(); 15433 Sema::CompoundScopeRAII CompoundScope(*this); 15434 MoveConstructor->setBody( 15435 ActOnCompoundStmt(Loc, Loc, std::nullopt, /*isStmtExpr=*/false) 15436 .getAs<Stmt>()); 15437 MoveConstructor->markUsed(Context); 15438 } 15439 15440 if (ASTMutationListener *L = getASTMutationListener()) { 15441 L->CompletedImplicitDefinition(MoveConstructor); 15442 } 15443} 15444 15445bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 15446 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 15447} 15448 15449void Sema::DefineImplicitLambdaToFunctionPointerConversion( 15450 SourceLocation CurrentLocation, 15451 CXXConversionDecl *Conv) { 15452 SynthesizedFunctionScope Scope(*this, Conv); 15453 assert(!Conv->getReturnType()->isUndeducedType())(static_cast <bool> (!Conv->getReturnType()->isUndeducedType
()) ? void (0) : __assert_fail ("!Conv->getReturnType()->isUndeducedType()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15453, __extension__ __PRETTY_FUNCTION__
))
; 15454 15455 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType(); 15456 CallingConv CC = 15457 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv(); 15458 15459 CXXRecordDecl *Lambda = Conv->getParent(); 15460 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 15461 FunctionDecl *Invoker = 15462 CallOp->isStatic() ? CallOp : Lambda->getLambdaStaticInvoker(CC); 15463 15464 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 15465 CallOp = InstantiateFunctionDeclaration( 15466 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15467 if (!CallOp) 15468 return; 15469 15470 if (CallOp != Invoker) { 15471 Invoker = InstantiateFunctionDeclaration( 15472 Invoker->getDescribedFunctionTemplate(), TemplateArgs, 15473 CurrentLocation); 15474 if (!Invoker) 15475 return; 15476 } 15477 } 15478 15479 if (CallOp->isInvalidDecl()) 15480 return; 15481 15482 // Mark the call operator referenced (and add to pending instantiations 15483 // if necessary). 15484 // For both the conversion and static-invoker template specializations 15485 // we construct their body's in this function, so no need to add them 15486 // to the PendingInstantiations. 15487 MarkFunctionReferenced(CurrentLocation, CallOp); 15488 15489 if (Invoker != CallOp) { 15490 // Fill in the __invoke function with a dummy implementation. IR generation 15491 // will fill in the actual details. Update its type in case it contained 15492 // an 'auto'. 15493 Invoker->markUsed(Context); 15494 Invoker->setReferenced(); 15495 Invoker->setType(Conv->getReturnType()->getPointeeType()); 15496 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 15497 } 15498 15499 // Construct the body of the conversion function { return __invoke; }. 15500 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue, 15501 Conv->getLocation()); 15502 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", 15502, __extension__ __PRETTY_FUNCTION__
))
; 15503 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 15504 Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(), 15505 Conv->getLocation(), Conv->getLocation())); 15506 Conv->markUsed(Context); 15507 Conv->setReferenced(); 15508 15509 if (ASTMutationListener *L = getASTMutationListener()) { 15510 L->CompletedImplicitDefinition(Conv); 15511 if (Invoker != CallOp) 15512 L->CompletedImplicitDefinition(Invoker); 15513 } 15514} 15515 15516void Sema::DefineImplicitLambdaToBlockPointerConversion( 15517 SourceLocation CurrentLocation, CXXConversionDecl *Conv) { 15518 assert(!Conv->getParent()->isGenericLambda())(static_cast <bool> (!Conv->getParent()->isGenericLambda
()) ? void (0) : __assert_fail ("!Conv->getParent()->isGenericLambda()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15518, __extension__ __PRETTY_FUNCTION__
))
; 15519 15520 SynthesizedFunctionScope Scope(*this, Conv); 15521 15522 // Copy-initialize the lambda object as needed to capture it. 15523 Expr *This = ActOnCXXThis(CurrentLocation).get(); 15524 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 15525 15526 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 15527 Conv->getLocation(), 15528 Conv, DerefThis); 15529 15530 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 15531 // behavior. Note that only the general conversion function does this 15532 // (since it's unusable otherwise); in the case where we inline the 15533 // block literal, it has block literal lifetime semantics. 15534 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 15535 BuildBlock = ImplicitCastExpr::Create( 15536 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 15537 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride()); 15538 15539 if (BuildBlock.isInvalid()) { 15540 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15541 Conv->setInvalidDecl(); 15542 return; 15543 } 15544 15545 // Create the return statement that returns the block from the conversion 15546 // function. 15547 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 15548 if (Return.isInvalid()) { 15549 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15550 Conv->setInvalidDecl(); 15551 return; 15552 } 15553 15554 // Set the body of the conversion function. 15555 Stmt *ReturnS = Return.get(); 15556 Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(), 15557 Conv->getLocation(), Conv->getLocation())); 15558 Conv->markUsed(Context); 15559 15560 // We're done; notify the mutation listener, if any. 15561 if (ASTMutationListener *L = getASTMutationListener()) { 15562 L->CompletedImplicitDefinition(Conv); 15563 } 15564} 15565 15566/// Determine whether the given list arguments contains exactly one 15567/// "real" (non-default) argument. 15568static bool hasOneRealArgument(MultiExprArg Args) { 15569 switch (Args.size()) { 15570 case 0: 15571 return false; 15572 15573 default: 15574 if (!Args[1]->isDefaultArgument()) 15575 return false; 15576 15577 [[fallthrough]]; 15578 case 1: 15579 return !Args[0]->isDefaultArgument(); 15580 } 15581 15582 return false; 15583} 15584 15585ExprResult 15586Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15587 NamedDecl *FoundDecl, 15588 CXXConstructorDecl *Constructor, 15589 MultiExprArg ExprArgs, 15590 bool HadMultipleCandidates, 15591 bool IsListInitialization, 15592 bool IsStdInitListInitialization, 15593 bool RequiresZeroInit, 15594 unsigned ConstructKind, 15595 SourceRange ParenRange) { 15596 bool Elidable = false; 15597 15598 // C++0x [class.copy]p34: 15599 // When certain criteria are met, an implementation is allowed to 15600 // omit the copy/move construction of a class object, even if the 15601 // copy/move constructor and/or destructor for the object have 15602 // side effects. [...] 15603 // - when a temporary class object that has not been bound to a 15604 // reference (12.2) would be copied/moved to a class object 15605 // with the same cv-unqualified type, the copy/move operation 15606 // can be omitted by constructing the temporary object 15607 // directly into the target of the omitted copy/move 15608 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 15609 // FIXME: Converting constructors should also be accepted. 15610 // But to fix this, the logic that digs down into a CXXConstructExpr 15611 // to find the source object needs to handle it. 15612 // Right now it assumes the source object is passed directly as the 15613 // first argument. 15614 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 15615 Expr *SubExpr = ExprArgs[0]; 15616 // FIXME: Per above, this is also incorrect if we want to accept 15617 // converting constructors, as isTemporaryObject will 15618 // reject temporaries with different type from the 15619 // CXXRecord itself. 15620 Elidable = SubExpr->isTemporaryObject( 15621 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 15622 } 15623 15624 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 15625 FoundDecl, Constructor, 15626 Elidable, ExprArgs, HadMultipleCandidates, 15627 IsListInitialization, 15628 IsStdInitListInitialization, RequiresZeroInit, 15629 ConstructKind, ParenRange); 15630} 15631 15632ExprResult 15633Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15634 NamedDecl *FoundDecl, 15635 CXXConstructorDecl *Constructor, 15636 bool Elidable, 15637 MultiExprArg ExprArgs, 15638 bool HadMultipleCandidates, 15639 bool IsListInitialization, 15640 bool IsStdInitListInitialization, 15641 bool RequiresZeroInit, 15642 unsigned ConstructKind, 15643 SourceRange ParenRange) { 15644 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 15645 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 15646 // The only way to get here is if we did overlaod resolution to find the 15647 // shadow decl, so we don't need to worry about re-checking the trailing 15648 // requires clause. 15649 if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc)) 15650 return ExprError(); 15651 } 15652 15653 return BuildCXXConstructExpr( 15654 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 15655 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 15656 RequiresZeroInit, ConstructKind, ParenRange); 15657} 15658 15659/// BuildCXXConstructExpr - Creates a complete call to a constructor, 15660/// including handling of its default argument expressions. 15661ExprResult 15662Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15663 CXXConstructorDecl *Constructor, 15664 bool Elidable, 15665 MultiExprArg ExprArgs, 15666 bool HadMultipleCandidates, 15667 bool IsListInitialization, 15668 bool IsStdInitListInitialization, 15669 bool RequiresZeroInit, 15670 unsigned ConstructKind, 15671 SourceRange ParenRange) { 15672 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", 15675, __extension__ __PRETTY_FUNCTION__
))
15673 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", 15675, __extension__ __PRETTY_FUNCTION__
))
15674 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", 15675, __extension__ __PRETTY_FUNCTION__
))
15675 "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", 15675, __extension__ __PRETTY_FUNCTION__
))
; 15676 MarkFunctionReferenced(ConstructLoc, Constructor); 15677 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15678 return ExprError(); 15679 15680 return CheckForImmediateInvocation( 15681 CXXConstructExpr::Create( 15682 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15683 HadMultipleCandidates, IsListInitialization, 15684 IsStdInitListInitialization, RequiresZeroInit, 15685 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15686 ParenRange), 15687 Constructor); 15688} 15689 15690void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15691 if (VD->isInvalidDecl()) return; 15692 // If initializing the variable failed, don't also diagnose problems with 15693 // the destructor, they're likely related. 15694 if (VD->getInit() && VD->getInit()->containsErrors()) 15695 return; 15696 15697 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15698 if (ClassDecl->isInvalidDecl()) return; 15699 if (ClassDecl->hasIrrelevantDestructor()) return; 15700 if (ClassDecl->isDependentContext()) return; 15701 15702 if (VD->isNoDestroy(getASTContext())) 15703 return; 15704 15705 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15706 15707 // If this is an array, we'll require the destructor during initialization, so 15708 // we can skip over this. We still want to emit exit-time destructor warnings 15709 // though. 15710 if (!VD->getType()->isArrayType()) { 15711 MarkFunctionReferenced(VD->getLocation(), Destructor); 15712 CheckDestructorAccess(VD->getLocation(), Destructor, 15713 PDiag(diag::err_access_dtor_var) 15714 << VD->getDeclName() << VD->getType()); 15715 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15716 } 15717 15718 if (Destructor->isTrivial()) return; 15719 15720 // If the destructor is constexpr, check whether the variable has constant 15721 // destruction now. 15722 if (Destructor->isConstexpr()) { 15723 bool HasConstantInit = false; 15724 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15725 HasConstantInit = VD->evaluateValue(); 15726 SmallVector<PartialDiagnosticAt, 8> Notes; 15727 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15728 HasConstantInit) { 15729 Diag(VD->getLocation(), 15730 diag::err_constexpr_var_requires_const_destruction) << VD; 15731 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15732 Diag(Notes[I].first, Notes[I].second); 15733 } 15734 } 15735 15736 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Context)) 15737 return; 15738 15739 // Emit warning for non-trivial dtor in global scope (a real global, 15740 // class-static, function-static). 15741 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15742 15743 // TODO: this should be re-enabled for static locals by !CXAAtExit 15744 if (!VD->isStaticLocal()) 15745 Diag(VD->getLocation(), diag::warn_global_destructor); 15746} 15747 15748/// Given a constructor and the set of arguments provided for the 15749/// constructor, convert the arguments and add any required default arguments 15750/// to form a proper call to this constructor. 15751/// 15752/// \returns true if an error occurred, false otherwise. 15753bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15754 QualType DeclInitType, MultiExprArg ArgsPtr, 15755 SourceLocation Loc, 15756 SmallVectorImpl<Expr *> &ConvertedArgs, 15757 bool AllowExplicit, 15758 bool IsListInitialization) { 15759 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15760 unsigned NumArgs = ArgsPtr.size(); 15761 Expr **Args = ArgsPtr.data(); 15762 15763 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15764 unsigned NumParams = Proto->getNumParams(); 15765 15766 // If too few arguments are available, we'll fill in the rest with defaults. 15767 if (NumArgs < NumParams) 15768 ConvertedArgs.reserve(NumParams); 15769 else 15770 ConvertedArgs.reserve(NumArgs); 15771 15772 VariadicCallType CallType = 15773 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15774 SmallVector<Expr *, 8> AllArgs; 15775 bool Invalid = GatherArgumentsForCall( 15776 Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs, 15777 CallType, AllowExplicit, IsListInitialization); 15778 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15779 15780 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15781 15782 CheckConstructorCall(Constructor, DeclInitType, 15783 llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto, 15784 Loc); 15785 15786 return Invalid; 15787} 15788 15789static inline bool 15790CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15791 const FunctionDecl *FnDecl) { 15792 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15793 if (isa<NamespaceDecl>(DC)) { 15794 return SemaRef.Diag(FnDecl->getLocation(), 15795 diag::err_operator_new_delete_declared_in_namespace) 15796 << FnDecl->getDeclName(); 15797 } 15798 15799 if (isa<TranslationUnitDecl>(DC) && 15800 FnDecl->getStorageClass() == SC_Static) { 15801 return SemaRef.Diag(FnDecl->getLocation(), 15802 diag::err_operator_new_delete_declared_static) 15803 << FnDecl->getDeclName(); 15804 } 15805 15806 return false; 15807} 15808 15809static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, 15810 const PointerType *PtrTy) { 15811 auto &Ctx = SemaRef.Context; 15812 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers(); 15813 PtrQuals.removeAddressSpace(); 15814 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType( 15815 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals))); 15816} 15817 15818static inline bool 15819CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15820 CanQualType ExpectedResultType, 15821 CanQualType ExpectedFirstParamType, 15822 unsigned DependentParamTypeDiag, 15823 unsigned InvalidParamTypeDiag) { 15824 QualType ResultType = 15825 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15826 15827 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15828 // The operator is valid on any address space for OpenCL. 15829 // Drop address space from actual and expected result types. 15830 if (const auto *PtrTy = ResultType->getAs<PointerType>()) 15831 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15832 15833 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>()) 15834 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15835 } 15836 15837 // Check that the result type is what we expect. 15838 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15839 // Reject even if the type is dependent; an operator delete function is 15840 // required to have a non-dependent result type. 15841 return SemaRef.Diag( 15842 FnDecl->getLocation(), 15843 ResultType->isDependentType() 15844 ? diag::err_operator_new_delete_dependent_result_type 15845 : diag::err_operator_new_delete_invalid_result_type) 15846 << FnDecl->getDeclName() << ExpectedResultType; 15847 } 15848 15849 // A function template must have at least 2 parameters. 15850 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15851 return SemaRef.Diag(FnDecl->getLocation(), 15852 diag::err_operator_new_delete_template_too_few_parameters) 15853 << FnDecl->getDeclName(); 15854 15855 // The function decl must have at least 1 parameter. 15856 if (FnDecl->getNumParams() == 0) 15857 return SemaRef.Diag(FnDecl->getLocation(), 15858 diag::err_operator_new_delete_too_few_parameters) 15859 << FnDecl->getDeclName(); 15860 15861 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15862 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15863 // The operator is valid on any address space for OpenCL. 15864 // Drop address space from actual and expected first parameter types. 15865 if (const auto *PtrTy = 15866 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) 15867 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15868 15869 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>()) 15870 ExpectedFirstParamType = 15871 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15872 } 15873 15874 // Check that the first parameter type is what we expect. 15875 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15876 ExpectedFirstParamType) { 15877 // The first parameter type is not allowed to be dependent. As a tentative 15878 // DR resolution, we allow a dependent parameter type if it is the right 15879 // type anyway, to allow destroying operator delete in class templates. 15880 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15881 ? DependentParamTypeDiag 15882 : InvalidParamTypeDiag) 15883 << FnDecl->getDeclName() << ExpectedFirstParamType; 15884 } 15885 15886 return false; 15887} 15888 15889static bool 15890CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15891 // C++ [basic.stc.dynamic.allocation]p1: 15892 // A program is ill-formed if an allocation function is declared in a 15893 // namespace scope other than global scope or declared static in global 15894 // scope. 15895 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15896 return true; 15897 15898 CanQualType SizeTy = 15899 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15900 15901 // C++ [basic.stc.dynamic.allocation]p1: 15902 // The return type shall be void*. The first parameter shall have type 15903 // std::size_t. 15904 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15905 SizeTy, 15906 diag::err_operator_new_dependent_param_type, 15907 diag::err_operator_new_param_type)) 15908 return true; 15909 15910 // C++ [basic.stc.dynamic.allocation]p1: 15911 // The first parameter shall not have an associated default argument. 15912 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15913 return SemaRef.Diag(FnDecl->getLocation(), 15914 diag::err_operator_new_default_arg) 15915 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15916 15917 return false; 15918} 15919 15920static bool 15921CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15922 // C++ [basic.stc.dynamic.deallocation]p1: 15923 // A program is ill-formed if deallocation functions are declared in a 15924 // namespace scope other than global scope or declared static in global 15925 // scope. 15926 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15927 return true; 15928 15929 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15930 15931 // C++ P0722: 15932 // Within a class C, the first parameter of a destroying operator delete 15933 // shall be of type C *. The first parameter of any other deallocation 15934 // function shall be of type void *. 15935 CanQualType ExpectedFirstParamType = 15936 MD && MD->isDestroyingOperatorDelete() 15937 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15938 SemaRef.Context.getRecordType(MD->getParent()))) 15939 : SemaRef.Context.VoidPtrTy; 15940 15941 // C++ [basic.stc.dynamic.deallocation]p2: 15942 // Each deallocation function shall return void 15943 if (CheckOperatorNewDeleteTypes( 15944 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15945 diag::err_operator_delete_dependent_param_type, 15946 diag::err_operator_delete_param_type)) 15947 return true; 15948 15949 // C++ P0722: 15950 // A destroying operator delete shall be a usual deallocation function. 15951 if (MD && !MD->getParent()->isDependentContext() && 15952 MD->isDestroyingOperatorDelete() && 15953 !SemaRef.isUsualDeallocationFunction(MD)) { 15954 SemaRef.Diag(MD->getLocation(), 15955 diag::err_destroying_operator_delete_not_usual); 15956 return true; 15957 } 15958 15959 return false; 15960} 15961 15962/// CheckOverloadedOperatorDeclaration - Check whether the declaration 15963/// of this overloaded operator is well-formed. If so, returns false; 15964/// otherwise, emits appropriate diagnostics and returns true. 15965bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15966 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", 15967, __extension__ __PRETTY_FUNCTION__
))
15967 "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", 15967, __extension__ __PRETTY_FUNCTION__
))
; 15968 15969 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15970 15971 // C++ [over.oper]p5: 15972 // The allocation and deallocation functions, operator new, 15973 // operator new[], operator delete and operator delete[], are 15974 // described completely in 3.7.3. The attributes and restrictions 15975 // found in the rest of this subclause do not apply to them unless 15976 // explicitly stated in 3.7.3. 15977 if (Op == OO_Delete || Op == OO_Array_Delete) 15978 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15979 15980 if (Op == OO_New || Op == OO_Array_New) 15981 return CheckOperatorNewDeclaration(*this, FnDecl); 15982 15983 // C++ [over.oper]p7: 15984 // An operator function shall either be a member function or 15985 // be a non-member function and have at least one parameter 15986 // whose type is a class, a reference to a class, an enumeration, 15987 // or a reference to an enumeration. 15988 // Note: Before C++23, a member function could not be static. The only member 15989 // function allowed to be static is the call operator function. 15990 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15991 if (MethodDecl->isStatic()) { 15992 if (Op == OO_Call || Op == OO_Subscript) 15993 Diag(FnDecl->getLocation(), 15994 (LangOpts.CPlusPlus23 15995 ? diag::warn_cxx20_compat_operator_overload_static 15996 : diag::ext_operator_overload_static)) 15997 << FnDecl; 15998 else 15999 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static) 16000 << FnDecl; 16001 } 16002 } else { 16003 bool ClassOrEnumParam = false; 16004 for (auto *Param : FnDecl->parameters()) { 16005 QualType ParamType = Param->getType().getNonReferenceType(); 16006 if (ParamType->isDependentType() || ParamType->isRecordType() || 16007 ParamType->isEnumeralType()) { 16008 ClassOrEnumParam = true; 16009 break; 16010 } 16011 } 16012 16013 if (!ClassOrEnumParam) 16014 return Diag(FnDecl->getLocation(), 16015 diag::err_operator_overload_needs_class_or_enum) 16016 << FnDecl->getDeclName(); 16017 } 16018 16019 // C++ [over.oper]p8: 16020 // An operator function cannot have default arguments (8.3.6), 16021 // except where explicitly stated below. 16022 // 16023 // Only the function-call operator (C++ [over.call]p1) and the subscript 16024 // operator (CWG2507) allow default arguments. 16025 if (Op != OO_Call) { 16026 ParmVarDecl *FirstDefaultedParam = nullptr; 16027 for (auto *Param : FnDecl->parameters()) { 16028 if (Param->hasDefaultArg()) { 16029 FirstDefaultedParam = Param; 16030 break; 16031 } 16032 } 16033 if (FirstDefaultedParam) { 16034 if (Op == OO_Subscript) { 16035 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23 16036 ? diag::ext_subscript_overload 16037 : diag::error_subscript_overload) 16038 << FnDecl->getDeclName() << 1 16039 << FirstDefaultedParam->getDefaultArgRange(); 16040 } else { 16041 return Diag(FirstDefaultedParam->getLocation(), 16042 diag::err_operator_overload_default_arg) 16043 << FnDecl->getDeclName() 16044 << FirstDefaultedParam->getDefaultArgRange(); 16045 } 16046 } 16047 } 16048 16049 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 16050 { false, false, false } 16051#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 16052 , { Unary, Binary, MemberOnly } 16053#include "clang/Basic/OperatorKinds.def" 16054 }; 16055 16056 bool CanBeUnaryOperator = OperatorUses[Op][0]; 16057 bool CanBeBinaryOperator = OperatorUses[Op][1]; 16058 bool MustBeMemberOperator = OperatorUses[Op][2]; 16059 16060 // C++ [over.oper]p8: 16061 // [...] Operator functions cannot have more or fewer parameters 16062 // than the number required for the corresponding operator, as 16063 // described in the rest of this subclause. 16064 unsigned NumParams = FnDecl->getNumParams() 16065 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 16066 if (Op != OO_Call && Op != OO_Subscript && 16067 ((NumParams == 1 && !CanBeUnaryOperator) || 16068 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) || 16069 (NumParams > 2))) { 16070 // We have the wrong number of parameters. 16071 unsigned ErrorKind; 16072 if (CanBeUnaryOperator && CanBeBinaryOperator) { 16073 ErrorKind = 2; // 2 -> unary or binary. 16074 } else if (CanBeUnaryOperator) { 16075 ErrorKind = 0; // 0 -> unary 16076 } else { 16077 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", 16078, __extension__ __PRETTY_FUNCTION__
))
16078 "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", 16078, __extension__ __PRETTY_FUNCTION__
))
; 16079 ErrorKind = 1; // 1 -> binary 16080 } 16081 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 16082 << FnDecl->getDeclName() << NumParams << ErrorKind; 16083 } 16084 16085 if (Op == OO_Subscript && NumParams != 2) { 16086 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23 16087 ? diag::ext_subscript_overload 16088 : diag::error_subscript_overload) 16089 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2); 16090 } 16091 16092 // Overloaded operators other than operator() and operator[] cannot be 16093 // variadic. 16094 if (Op != OO_Call && 16095 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 16096 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 16097 << FnDecl->getDeclName(); 16098 } 16099 16100 // Some operators must be member functions. 16101 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 16102 return Diag(FnDecl->getLocation(), 16103 diag::err_operator_overload_must_be_member) 16104 << FnDecl->getDeclName(); 16105 } 16106 16107 // C++ [over.inc]p1: 16108 // The user-defined function called operator++ implements the 16109 // prefix and postfix ++ operator. If this function is a member 16110 // function with no parameters, or a non-member function with one 16111 // parameter of class or enumeration type, it defines the prefix 16112 // increment operator ++ for objects of that type. If the function 16113 // is a member function with one parameter (which shall be of type 16114 // int) or a non-member function with two parameters (the second 16115 // of which shall be of type int), it defines the postfix 16116 // increment operator ++ for objects of that type. 16117 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 16118 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 16119 QualType ParamType = LastParam->getType(); 16120 16121 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 16122 !ParamType->isDependentType()) 16123 return Diag(LastParam->getLocation(), 16124 diag::err_operator_overload_post_incdec_must_be_int) 16125 << LastParam->getType() << (Op == OO_MinusMinus); 16126 } 16127 16128 return false; 16129} 16130 16131static bool 16132checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 16133 FunctionTemplateDecl *TpDecl) { 16134 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 16135 16136 // Must have one or two template parameters. 16137 if (TemplateParams->size() == 1) { 16138 NonTypeTemplateParmDecl *PmDecl = 16139 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 16140 16141 // The template parameter must be a char parameter pack. 16142 if (PmDecl && PmDecl->isTemplateParameterPack() && 16143 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 16144 return false; 16145 16146 // C++20 [over.literal]p5: 16147 // A string literal operator template is a literal operator template 16148 // whose template-parameter-list comprises a single non-type 16149 // template-parameter of class type. 16150 // 16151 // As a DR resolution, we also allow placeholders for deduced class 16152 // template specializations. 16153 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl && 16154 !PmDecl->isTemplateParameterPack() && 16155 (PmDecl->getType()->isRecordType() || 16156 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) 16157 return false; 16158 } else if (TemplateParams->size() == 2) { 16159 TemplateTypeParmDecl *PmType = 16160 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 16161 NonTypeTemplateParmDecl *PmArgs = 16162 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 16163 16164 // The second template parameter must be a parameter pack with the 16165 // first template parameter as its type. 16166 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 16167 PmArgs->isTemplateParameterPack()) { 16168 const TemplateTypeParmType *TArgs = 16169 PmArgs->getType()->getAs<TemplateTypeParmType>(); 16170 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 16171 TArgs->getIndex() == PmType->getIndex()) { 16172 if (!SemaRef.inTemplateInstantiation()) 16173 SemaRef.Diag(TpDecl->getLocation(), 16174 diag::ext_string_literal_operator_template); 16175 return false; 16176 } 16177 } 16178 } 16179 16180 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 16181 diag::err_literal_operator_template) 16182 << TpDecl->getTemplateParameters()->getSourceRange(); 16183 return true; 16184} 16185 16186/// CheckLiteralOperatorDeclaration - Check whether the declaration 16187/// of this literal operator function is well-formed. If so, returns 16188/// false; otherwise, emits appropriate diagnostics and returns true. 16189bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 16190 if (isa<CXXMethodDecl>(FnDecl)) { 16191 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 16192 << FnDecl->getDeclName(); 16193 return true; 16194 } 16195 16196 if (FnDecl->isExternC()) { 16197 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 16198 if (const LinkageSpecDecl *LSD = 16199 FnDecl->getDeclContext()->getExternCContext()) 16200 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 16201 return true; 16202 } 16203 16204 // This might be the definition of a literal operator template. 16205 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 16206 16207 // This might be a specialization of a literal operator template. 16208 if (!TpDecl) 16209 TpDecl = FnDecl->getPrimaryTemplate(); 16210 16211 // template <char...> type operator "" name() and 16212 // template <class T, T...> type operator "" name() are the only valid 16213 // template signatures, and the only valid signatures with no parameters. 16214 // 16215 // C++20 also allows template <SomeClass T> type operator "" name(). 16216 if (TpDecl) { 16217 if (FnDecl->param_size() != 0) { 16218 Diag(FnDecl->getLocation(), 16219 diag::err_literal_operator_template_with_params); 16220 return true; 16221 } 16222 16223 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 16224 return true; 16225 16226 } else if (FnDecl->param_size() == 1) { 16227 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 16228 16229 QualType ParamType = Param->getType().getUnqualifiedType(); 16230 16231 // Only unsigned long long int, long double, any character type, and const 16232 // char * are allowed as the only parameters. 16233 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 16234 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 16235 Context.hasSameType(ParamType, Context.CharTy) || 16236 Context.hasSameType(ParamType, Context.WideCharTy) || 16237 Context.hasSameType(ParamType, Context.Char8Ty) || 16238 Context.hasSameType(ParamType, Context.Char16Ty) || 16239 Context.hasSameType(ParamType, Context.Char32Ty)) { 16240 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 16241 QualType InnerType = Ptr->getPointeeType(); 16242 16243 // Pointer parameter must be a const char *. 16244 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 16245 Context.CharTy) && 16246 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 16247 Diag(Param->getSourceRange().getBegin(), 16248 diag::err_literal_operator_param) 16249 << ParamType << "'const char *'" << Param->getSourceRange(); 16250 return true; 16251 } 16252 16253 } else if (ParamType->isRealFloatingType()) { 16254 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 16255 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 16256 return true; 16257 16258 } else if (ParamType->isIntegerType()) { 16259 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 16260 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 16261 return true; 16262 16263 } else { 16264 Diag(Param->getSourceRange().getBegin(), 16265 diag::err_literal_operator_invalid_param) 16266 << ParamType << Param->getSourceRange(); 16267 return true; 16268 } 16269 16270 } else if (FnDecl->param_size() == 2) { 16271 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 16272 16273 // First, verify that the first parameter is correct. 16274 16275 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 16276 16277 // Two parameter function must have a pointer to const as a 16278 // first parameter; let's strip those qualifiers. 16279 const PointerType *PT = FirstParamType->getAs<PointerType>(); 16280 16281 if (!PT) { 16282 Diag((*Param)->getSourceRange().getBegin(), 16283 diag::err_literal_operator_param) 16284 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16285 return true; 16286 } 16287 16288 QualType PointeeType = PT->getPointeeType(); 16289 // First parameter must be const 16290 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 16291 Diag((*Param)->getSourceRange().getBegin(), 16292 diag::err_literal_operator_param) 16293 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16294 return true; 16295 } 16296 16297 QualType InnerType = PointeeType.getUnqualifiedType(); 16298 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 16299 // const char32_t* are allowed as the first parameter to a two-parameter 16300 // function 16301 if (!(Context.hasSameType(InnerType, Context.CharTy) || 16302 Context.hasSameType(InnerType, Context.WideCharTy) || 16303 Context.hasSameType(InnerType, Context.Char8Ty) || 16304 Context.hasSameType(InnerType, Context.Char16Ty) || 16305 Context.hasSameType(InnerType, Context.Char32Ty))) { 16306 Diag((*Param)->getSourceRange().getBegin(), 16307 diag::err_literal_operator_param) 16308 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16309 return true; 16310 } 16311 16312 // Move on to the second and final parameter. 16313 ++Param; 16314 16315 // The second parameter must be a std::size_t. 16316 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 16317 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 16318 Diag((*Param)->getSourceRange().getBegin(), 16319 diag::err_literal_operator_param) 16320 << SecondParamType << Context.getSizeType() 16321 << (*Param)->getSourceRange(); 16322 return true; 16323 } 16324 } else { 16325 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 16326 return true; 16327 } 16328 16329 // Parameters are good. 16330 16331 // A parameter-declaration-clause containing a default argument is not 16332 // equivalent to any of the permitted forms. 16333 for (auto *Param : FnDecl->parameters()) { 16334 if (Param->hasDefaultArg()) { 16335 Diag(Param->getDefaultArgRange().getBegin(), 16336 diag::err_literal_operator_default_argument) 16337 << Param->getDefaultArgRange(); 16338 break; 16339 } 16340 } 16341 16342 StringRef LiteralName 16343 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 16344 if (LiteralName[0] != '_' && 16345 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 16346 // C++11 [usrlit.suffix]p1: 16347 // Literal suffix identifiers that do not start with an underscore 16348 // are reserved for future standardization. 16349 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 16350 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 16351 } 16352 16353 return false; 16354} 16355 16356/// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 16357/// linkage specification, including the language and (if present) 16358/// the '{'. ExternLoc is the location of the 'extern', Lang is the 16359/// language string literal. LBraceLoc, if valid, provides the location of 16360/// the '{' brace. Otherwise, this linkage specification does not 16361/// have any braces. 16362Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 16363 Expr *LangStr, 16364 SourceLocation LBraceLoc) { 16365 StringLiteral *Lit = cast<StringLiteral>(LangStr); 16366 if (!Lit->isOrdinary()) { 16367 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 16368 << LangStr->getSourceRange(); 16369 return nullptr; 16370 } 16371 16372 StringRef Lang = Lit->getString(); 16373 LinkageSpecDecl::LanguageIDs Language; 16374 if (Lang == "C") 16375 Language = LinkageSpecDecl::lang_c; 16376 else if (Lang == "C++") 16377 Language = LinkageSpecDecl::lang_cxx; 16378 else { 16379 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 16380 << LangStr->getSourceRange(); 16381 return nullptr; 16382 } 16383 16384 // FIXME: Add all the various semantics of linkage specifications 16385 16386 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 16387 LangStr->getExprLoc(), Language, 16388 LBraceLoc.isValid()); 16389 16390 /// C++ [module.unit]p7.2.3 16391 /// - Otherwise, if the declaration 16392 /// - ... 16393 /// - ... 16394 /// - appears within a linkage-specification, 16395 /// it is attached to the global module. 16396 /// 16397 /// If the declaration is already in global module fragment, we don't 16398 /// need to attach it again. 16399 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) { 16400 Module *GlobalModule = PushImplicitGlobalModuleFragment( 16401 ExternLoc, /*IsExported=*/D->isInExportDeclContext()); 16402 D->setLocalOwningModule(GlobalModule); 16403 } 16404 16405 CurContext->addDecl(D); 16406 PushDeclContext(S, D); 16407 return D; 16408} 16409 16410/// ActOnFinishLinkageSpecification - Complete the definition of 16411/// the C++ linkage specification LinkageSpec. If RBraceLoc is 16412/// valid, it's the position of the closing '}' brace in a linkage 16413/// specification that uses braces. 16414Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 16415 Decl *LinkageSpec, 16416 SourceLocation RBraceLoc) { 16417 if (RBraceLoc.isValid()) { 16418 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 16419 LSDecl->setRBraceLoc(RBraceLoc); 16420 } 16421 16422 // If the current module doesn't has Parent, it implies that the 16423 // LinkageSpec isn't in the module created by itself. So we don't 16424 // need to pop it. 16425 if (getLangOpts().CPlusPlusModules && getCurrentModule() && 16426 getCurrentModule()->isImplicitGlobalModule() && 16427 getCurrentModule()->Parent) 16428 PopImplicitGlobalModuleFragment(); 16429 16430 PopDeclContext(); 16431 return LinkageSpec; 16432} 16433 16434Decl *Sema::ActOnEmptyDeclaration(Scope *S, 16435 const ParsedAttributesView &AttrList, 16436 SourceLocation SemiLoc) { 16437 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 16438 // Attribute declarations appertain to empty declaration so we handle 16439 // them here. 16440 ProcessDeclAttributeList(S, ED, AttrList); 16441 16442 CurContext->addDecl(ED); 16443 return ED; 16444} 16445 16446/// Perform semantic analysis for the variable declaration that 16447/// occurs within a C++ catch clause, returning the newly-created 16448/// variable. 16449VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 16450 TypeSourceInfo *TInfo, 16451 SourceLocation StartLoc, 16452 SourceLocation Loc, 16453 IdentifierInfo *Name) { 16454 bool Invalid = false; 16455 QualType ExDeclType = TInfo->getType(); 16456 16457 // Arrays and functions decay. 16458 if (ExDeclType->isArrayType()) 16459 ExDeclType = Context.getArrayDecayedType(ExDeclType); 16460 else if (ExDeclType->isFunctionType()) 16461 ExDeclType = Context.getPointerType(ExDeclType); 16462 16463 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 16464 // The exception-declaration shall not denote a pointer or reference to an 16465 // incomplete type, other than [cv] void*. 16466 // N2844 forbids rvalue references. 16467 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 16468 Diag(Loc, diag::err_catch_rvalue_ref); 16469 Invalid = true; 16470 } 16471 16472 if (ExDeclType->isVariablyModifiedType()) { 16473 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 16474 Invalid = true; 16475 } 16476 16477 QualType BaseType = ExDeclType; 16478 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 16479 unsigned DK = diag::err_catch_incomplete; 16480 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 16481 BaseType = Ptr->getPointeeType(); 16482 Mode = 1; 16483 DK = diag::err_catch_incomplete_ptr; 16484 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 16485 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 16486 BaseType = Ref->getPointeeType(); 16487 Mode = 2; 16488 DK = diag::err_catch_incomplete_ref; 16489 } 16490 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 16491 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 16492 Invalid = true; 16493 16494 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 16495 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 16496 Invalid = true; 16497 } 16498 16499 if (!Invalid && !ExDeclType->isDependentType() && 16500 RequireNonAbstractType(Loc, ExDeclType, 16501 diag::err_abstract_type_in_decl, 16502 AbstractVariableType)) 16503 Invalid = true; 16504 16505 // Only the non-fragile NeXT runtime currently supports C++ catches 16506 // of ObjC types, and no runtime supports catching ObjC types by value. 16507 if (!Invalid && getLangOpts().ObjC) { 16508 QualType T = ExDeclType; 16509 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 16510 T = RT->getPointeeType(); 16511 16512 if (T->isObjCObjectType()) { 16513 Diag(Loc, diag::err_objc_object_catch); 16514 Invalid = true; 16515 } else if (T->isObjCObjectPointerType()) { 16516 // FIXME: should this be a test for macosx-fragile specifically? 16517 if (getLangOpts().ObjCRuntime.isFragile()) 16518 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 16519 } 16520 } 16521 16522 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 16523 ExDeclType, TInfo, SC_None); 16524 ExDecl->setExceptionVariable(true); 16525 16526 // In ARC, infer 'retaining' for variables of retainable type. 16527 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 16528 Invalid = true; 16529 16530 if (!Invalid && !ExDeclType->isDependentType()) { 16531 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 16532 // Insulate this from anything else we might currently be parsing. 16533 EnterExpressionEvaluationContext scope( 16534 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16535 16536 // C++ [except.handle]p16: 16537 // The object declared in an exception-declaration or, if the 16538 // exception-declaration does not specify a name, a temporary (12.2) is 16539 // copy-initialized (8.5) from the exception object. [...] 16540 // The object is destroyed when the handler exits, after the destruction 16541 // of any automatic objects initialized within the handler. 16542 // 16543 // We just pretend to initialize the object with itself, then make sure 16544 // it can be destroyed later. 16545 QualType initType = Context.getExceptionObjectType(ExDeclType); 16546 16547 InitializedEntity entity = 16548 InitializedEntity::InitializeVariable(ExDecl); 16549 InitializationKind initKind = 16550 InitializationKind::CreateCopy(Loc, SourceLocation()); 16551 16552 Expr *opaqueValue = 16553 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 16554 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 16555 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 16556 if (result.isInvalid()) 16557 Invalid = true; 16558 else { 16559 // If the constructor used was non-trivial, set this as the 16560 // "initializer". 16561 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 16562 if (!construct->getConstructor()->isTrivial()) { 16563 Expr *init = MaybeCreateExprWithCleanups(construct); 16564 ExDecl->setInit(init); 16565 } 16566 16567 // And make sure it's destructable. 16568 FinalizeVarWithDestructor(ExDecl, recordType); 16569 } 16570 } 16571 } 16572 16573 if (Invalid) 16574 ExDecl->setInvalidDecl(); 16575 16576 return ExDecl; 16577} 16578 16579/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 16580/// handler. 16581Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 16582 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16583 bool Invalid = D.isInvalidType(); 16584 16585 // Check for unexpanded parameter packs. 16586 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16587 UPPC_ExceptionType)) { 16588 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 16589 D.getIdentifierLoc()); 16590 Invalid = true; 16591 } 16592 16593 IdentifierInfo *II = D.getIdentifier(); 16594 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 16595 LookupOrdinaryName, 16596 ForVisibleRedeclaration)) { 16597 // The scope should be freshly made just for us. There is just no way 16598 // it contains any previous declaration, except for function parameters in 16599 // a function-try-block's catch statement. 16600 assert(!S->isDeclScope(PrevDecl))(static_cast <bool> (!S->isDeclScope(PrevDecl)) ? void
(0) : __assert_fail ("!S->isDeclScope(PrevDecl)", "clang/lib/Sema/SemaDeclCXX.cpp"
, 16600, __extension__ __PRETTY_FUNCTION__))
; 16601 if (isDeclInScope(PrevDecl, CurContext, S)) { 16602 Diag(D.getIdentifierLoc(), diag::err_redefinition) 16603 << D.getIdentifier(); 16604 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 16605 Invalid = true; 16606 } else if (PrevDecl->isTemplateParameter()) 16607 // Maybe we will complain about the shadowed template parameter. 16608 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16609 } 16610 16611 if (D.getCXXScopeSpec().isSet() && !Invalid) { 16612 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 16613 << D.getCXXScopeSpec().getRange(); 16614 Invalid = true; 16615 } 16616 16617 VarDecl *ExDecl = BuildExceptionDeclaration( 16618 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 16619 if (Invalid) 16620 ExDecl->setInvalidDecl(); 16621 16622 // Add the exception declaration into this scope. 16623 if (II) 16624 PushOnScopeChains(ExDecl, S); 16625 else 16626 CurContext->addDecl(ExDecl); 16627 16628 ProcessDeclAttributes(S, ExDecl, D); 16629 return ExDecl; 16630} 16631 16632Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16633 Expr *AssertExpr, 16634 Expr *AssertMessageExpr, 16635 SourceLocation RParenLoc) { 16636 StringLiteral *AssertMessage = 16637 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 16638 16639 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 16640 return nullptr; 16641 16642 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 16643 AssertMessage, RParenLoc, false); 16644} 16645 16646/// Convert \V to a string we can present to the user in a diagnostic 16647/// \T is the type of the expression that has been evaluated into \V 16648static bool ConvertAPValueToString(const APValue &V, QualType T, 16649 SmallVectorImpl<char> &Str) { 16650 if (!V.hasValue()) 16651 return false; 16652 16653 switch (V.getKind()) { 16654 case APValue::ValueKind::Int: 16655 if (T->isBooleanType()) { 16656 // Bools are reduced to ints during evaluation, but for 16657 // diagnostic purposes we want to print them as 16658 // true or false. 16659 int64_t BoolValue = V.getInt().getExtValue(); 16660 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", 16661, __extension__ __PRETTY_FUNCTION__
))
16661 "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", 16661, __extension__ __PRETTY_FUNCTION__
))
; 16662 llvm::raw_svector_ostream OS(Str); 16663 OS << (BoolValue ? "true" : "false"); 16664 } else if (T->isCharType()) { 16665 // Same is true for chars. 16666 Str.push_back('\''); 16667 Str.push_back(V.getInt().getExtValue()); 16668 Str.push_back('\''); 16669 } else 16670 V.getInt().toString(Str); 16671 16672 break; 16673 16674 case APValue::ValueKind::Float: 16675 V.getFloat().toString(Str); 16676 break; 16677 16678 case APValue::ValueKind::LValue: 16679 if (V.isNullPointer()) { 16680 llvm::raw_svector_ostream OS(Str); 16681 OS << "nullptr"; 16682 } else 16683 return false; 16684 break; 16685 16686 case APValue::ValueKind::ComplexFloat: { 16687 llvm::raw_svector_ostream OS(Str); 16688 OS << '('; 16689 V.getComplexFloatReal().toString(Str); 16690 OS << " + "; 16691 V.getComplexFloatImag().toString(Str); 16692 OS << "i)"; 16693 } break; 16694 16695 case APValue::ValueKind::ComplexInt: { 16696 llvm::raw_svector_ostream OS(Str); 16697 OS << '('; 16698 V.getComplexIntReal().toString(Str); 16699 OS << " + "; 16700 V.getComplexIntImag().toString(Str); 16701 OS << "i)"; 16702 } break; 16703 16704 default: 16705 return false; 16706 } 16707 16708 return true; 16709} 16710 16711/// Some Expression types are not useful to print notes about, 16712/// e.g. literals and values that have already been expanded 16713/// before such as int-valued template parameters. 16714static bool UsefulToPrintExpr(const Expr *E) { 16715 E = E->IgnoreParenImpCasts(); 16716 // Literals are pretty easy for humans to understand. 16717 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr, 16718 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(E)) 16719 return false; 16720 16721 // These have been substituted from template parameters 16722 // and appear as literals in the static assert error. 16723 if (isa<SubstNonTypeTemplateParmExpr>(E)) 16724 return false; 16725 16726 // -5 is also simple to understand. 16727 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(E)) 16728 return UsefulToPrintExpr(UnaryOp->getSubExpr()); 16729 16730 // Ignore nested binary operators. This could be a FIXME for improvements 16731 // to the diagnostics in the future. 16732 if (isa<BinaryOperator>(E)) 16733 return false; 16734 16735 return true; 16736} 16737 16738/// Try to print more useful information about a failed static_assert 16739/// with expression \E 16740void Sema::DiagnoseStaticAssertDetails(const Expr *E) { 16741 if (const auto *Op = dyn_cast<BinaryOperator>(E); 16742 Op && Op->getOpcode() != BO_LOr) { 16743 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts(); 16744 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts(); 16745 16746 // Ignore comparisons of boolean expressions with a boolean literal. 16747 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) || 16748 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType())) 16749 return; 16750 16751 // Don't print obvious expressions. 16752 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS)) 16753 return; 16754 16755 struct { 16756 const clang::Expr *Cond; 16757 Expr::EvalResult Result; 16758 SmallString<12> ValueString; 16759 bool Print; 16760 } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false}, 16761 {RHS, Expr::EvalResult(), {}, false}}; 16762 for (unsigned I = 0; I < 2; I++) { 16763 const Expr *Side = DiagSide[I].Cond; 16764 16765 Side->EvaluateAsRValue(DiagSide[I].Result, Context, true); 16766 16767 DiagSide[I].Print = ConvertAPValueToString( 16768 DiagSide[I].Result.Val, Side->getType(), DiagSide[I].ValueString); 16769 } 16770 if (DiagSide[0].Print && DiagSide[1].Print) { 16771 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to) 16772 << DiagSide[0].ValueString << Op->getOpcodeStr() 16773 << DiagSide[1].ValueString << Op->getSourceRange(); 16774 } 16775 } 16776} 16777 16778Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16779 Expr *AssertExpr, 16780 StringLiteral *AssertMessage, 16781 SourceLocation RParenLoc, 16782 bool Failed) { 16783 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", 16783, __extension__ __PRETTY_FUNCTION__
))
; 16784 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 16785 !Failed) { 16786 // In a static_assert-declaration, the constant-expression shall be a 16787 // constant expression that can be contextually converted to bool. 16788 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 16789 if (Converted.isInvalid()) 16790 Failed = true; 16791 16792 ExprResult FullAssertExpr = 16793 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 16794 /*DiscardedValue*/ false, 16795 /*IsConstexpr*/ true); 16796 if (FullAssertExpr.isInvalid()) 16797 Failed = true; 16798 else 16799 AssertExpr = FullAssertExpr.get(); 16800 16801 llvm::APSInt Cond; 16802 Expr *BaseExpr = AssertExpr; 16803 AllowFoldKind FoldKind = NoFold; 16804 16805 if (!getLangOpts().CPlusPlus) { 16806 // In C mode, allow folding as an extension for better compatibility with 16807 // C++ in terms of expressions like static_assert("test") or 16808 // static_assert(nullptr). 16809 FoldKind = AllowFold; 16810 } 16811 16812 if (!Failed && VerifyIntegerConstantExpression( 16813 BaseExpr, &Cond, 16814 diag::err_static_assert_expression_is_not_constant, 16815 FoldKind).isInvalid()) 16816 Failed = true; 16817 16818 // CWG2518 16819 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a 16820 // template definition, the declaration has no effect. 16821 bool InTemplateDefinition = 16822 getLangOpts().CPlusPlus && CurContext->isDependentContext(); 16823 16824 if (!Failed && !Cond && !InTemplateDefinition) { 16825 16826 SmallString<256> MsgBuffer; 16827 llvm::raw_svector_ostream Msg(MsgBuffer); 16828 if (AssertMessage) { 16829 const auto *MsgStr = cast<StringLiteral>(AssertMessage); 16830 if (MsgStr->isOrdinary()) 16831 Msg << MsgStr->getString(); 16832 else 16833 MsgStr->printPretty(Msg, nullptr, getPrintingPolicy()); 16834 } 16835 16836 Expr *InnerCond = nullptr; 16837 std::string InnerCondDescription; 16838 std::tie(InnerCond, InnerCondDescription) = 16839 findFailedBooleanCondition(Converted.get()); 16840 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16841 // Drill down into concept specialization expressions to see why they 16842 // weren't satisfied. 16843 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed) 16844 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16845 ConstraintSatisfaction Satisfaction; 16846 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16847 DiagnoseUnsatisfiedConstraint(Satisfaction); 16848 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16849 && !isa<IntegerLiteral>(InnerCond)) { 16850 Diag(InnerCond->getBeginLoc(), 16851 diag::err_static_assert_requirement_failed) 16852 << InnerCondDescription << !AssertMessage << Msg.str() 16853 << InnerCond->getSourceRange(); 16854 DiagnoseStaticAssertDetails(InnerCond); 16855 } else { 16856 Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed) 16857 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16858 PrintContextStack(); 16859 } 16860 Failed = true; 16861 } 16862 } else { 16863 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16864 /*DiscardedValue*/false, 16865 /*IsConstexpr*/true); 16866 if (FullAssertExpr.isInvalid()) 16867 Failed = true; 16868 else 16869 AssertExpr = FullAssertExpr.get(); 16870 } 16871 16872 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16873 AssertExpr, AssertMessage, RParenLoc, 16874 Failed); 16875 16876 CurContext->addDecl(Decl); 16877 return Decl; 16878} 16879 16880/// Perform semantic analysis of the given friend type declaration. 16881/// 16882/// \returns A friend declaration that. 16883FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16884 SourceLocation FriendLoc, 16885 TypeSourceInfo *TSInfo) { 16886 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", 16886, __extension__ __PRETTY_FUNCTION__
))
; 16887 16888 QualType T = TSInfo->getType(); 16889 SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange(); 16890 16891 // C++03 [class.friend]p2: 16892 // An elaborated-type-specifier shall be used in a friend declaration 16893 // for a class.* 16894 // 16895 // * The class-key of the elaborated-type-specifier is required. 16896 if (!CodeSynthesisContexts.empty()) { 16897 // Do not complain about the form of friend template types during any kind 16898 // of code synthesis. For template instantiation, we will have complained 16899 // when the template was defined. 16900 } else { 16901 if (!T->isElaboratedTypeSpecifier()) { 16902 // If we evaluated the type to a record type, suggest putting 16903 // a tag in front. 16904 if (const RecordType *RT = T->getAs<RecordType>()) { 16905 RecordDecl *RD = RT->getDecl(); 16906 16907 SmallString<16> InsertionText(" "); 16908 InsertionText += RD->getKindName(); 16909 16910 Diag(TypeRange.getBegin(), 16911 getLangOpts().CPlusPlus11 ? 16912 diag::warn_cxx98_compat_unelaborated_friend_type : 16913 diag::ext_unelaborated_friend_type) 16914 << (unsigned) RD->getTagKind() 16915 << T 16916 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16917 InsertionText); 16918 } else { 16919 Diag(FriendLoc, 16920 getLangOpts().CPlusPlus11 ? 16921 diag::warn_cxx98_compat_nonclass_type_friend : 16922 diag::ext_nonclass_type_friend) 16923 << T 16924 << TypeRange; 16925 } 16926 } else if (T->getAs<EnumType>()) { 16927 Diag(FriendLoc, 16928 getLangOpts().CPlusPlus11 ? 16929 diag::warn_cxx98_compat_enum_friend : 16930 diag::ext_enum_friend) 16931 << T 16932 << TypeRange; 16933 } 16934 16935 // C++11 [class.friend]p3: 16936 // A friend declaration that does not declare a function shall have one 16937 // of the following forms: 16938 // friend elaborated-type-specifier ; 16939 // friend simple-type-specifier ; 16940 // friend typename-specifier ; 16941 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16942 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16943 } 16944 16945 // If the type specifier in a friend declaration designates a (possibly 16946 // cv-qualified) class type, that class is declared as a friend; otherwise, 16947 // the friend declaration is ignored. 16948 return FriendDecl::Create(Context, CurContext, 16949 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16950 FriendLoc); 16951} 16952 16953/// Handle a friend tag declaration where the scope specifier was 16954/// templated. 16955DeclResult Sema::ActOnTemplatedFriendTag( 16956 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, 16957 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, 16958 const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists) { 16959 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16960 16961 bool IsMemberSpecialization = false; 16962 bool Invalid = false; 16963 16964 if (TemplateParameterList *TemplateParams = 16965 MatchTemplateParametersToScopeSpecifier( 16966 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16967 IsMemberSpecialization, Invalid)) { 16968 if (TemplateParams->size() > 0) { 16969 // This is a declaration of a class template. 16970 if (Invalid) 16971 return true; 16972 16973 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16974 NameLoc, Attr, TemplateParams, AS_public, 16975 /*ModulePrivateLoc=*/SourceLocation(), 16976 FriendLoc, TempParamLists.size() - 1, 16977 TempParamLists.data()).get(); 16978 } else { 16979 // The "template<>" header is extraneous. 16980 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16981 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16982 IsMemberSpecialization = true; 16983 } 16984 } 16985 16986 if (Invalid) return true; 16987 16988 bool isAllExplicitSpecializations = true; 16989 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16990 if (TempParamLists[I]->size()) { 16991 isAllExplicitSpecializations = false; 16992 break; 16993 } 16994 } 16995 16996 // FIXME: don't ignore attributes. 16997 16998 // If it's explicit specializations all the way down, just forget 16999 // about the template header and build an appropriate non-templated 17000 // friend. TODO: for source fidelity, remember the headers. 17001 if (isAllExplicitSpecializations) { 17002 if (SS.isEmpty()) { 17003 bool Owned = false; 17004 bool IsDependent = false; 17005 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, Attr, 17006 AS_public, 17007 /*ModulePrivateLoc=*/SourceLocation(), 17008 MultiTemplateParamsArg(), Owned, IsDependent, 17009 /*ScopedEnumKWLoc=*/SourceLocation(), 17010 /*ScopedEnumUsesClassTag=*/false, 17011 /*UnderlyingType=*/TypeResult(), 17012 /*IsTypeSpecifier=*/false, 17013 /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside); 17014 } 17015 17016 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 17017 ElaboratedTypeKeyword Keyword 17018 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 17019 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 17020 *Name, NameLoc); 17021 if (T.isNull()) 17022 return true; 17023 17024 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 17025 if (isa<DependentNameType>(T)) { 17026 DependentNameTypeLoc TL = 17027 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 17028 TL.setElaboratedKeywordLoc(TagLoc); 17029 TL.setQualifierLoc(QualifierLoc); 17030 TL.setNameLoc(NameLoc); 17031 } else { 17032 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 17033 TL.setElaboratedKeywordLoc(TagLoc); 17034 TL.setQualifierLoc(QualifierLoc); 17035 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 17036 } 17037 17038 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 17039 TSI, FriendLoc, TempParamLists); 17040 Friend->setAccess(AS_public); 17041 CurContext->addDecl(Friend); 17042 return Friend; 17043 } 17044 17045 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", 17045, __extension__ __PRETTY_FUNCTION__
))
; 17046 17047 17048 17049 // Handle the case of a templated-scope friend class. e.g. 17050 // template <class T> class A<T>::B; 17051 // FIXME: we don't support these right now. 17052 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 17053 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 17054 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 17055 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 17056 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 17057 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 17058 TL.setElaboratedKeywordLoc(TagLoc); 17059 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 17060 TL.setNameLoc(NameLoc); 17061 17062 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 17063 TSI, FriendLoc, TempParamLists); 17064 Friend->setAccess(AS_public); 17065 Friend->setUnsupportedFriend(true); 17066 CurContext->addDecl(Friend); 17067 return Friend; 17068} 17069 17070/// Handle a friend type declaration. This works in tandem with 17071/// ActOnTag. 17072/// 17073/// Notes on friend class templates: 17074/// 17075/// We generally treat friend class declarations as if they were 17076/// declaring a class. So, for example, the elaborated type specifier 17077/// in a friend declaration is required to obey the restrictions of a 17078/// class-head (i.e. no typedefs in the scope chain), template 17079/// parameters are required to match up with simple template-ids, &c. 17080/// However, unlike when declaring a template specialization, it's 17081/// okay to refer to a template specialization without an empty 17082/// template parameter declaration, e.g. 17083/// friend class A<T>::B<unsigned>; 17084/// We permit this as a special case; if there are any template 17085/// parameters present at all, require proper matching, i.e. 17086/// template <> template \<class T> friend class A<int>::B; 17087Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 17088 MultiTemplateParamsArg TempParams) { 17089 SourceLocation Loc = DS.getBeginLoc(); 17090 17091 assert(DS.isFriendSpecified())(static_cast <bool> (DS.isFriendSpecified()) ? void (0)
: __assert_fail ("DS.isFriendSpecified()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 17091, __extension__ __PRETTY_FUNCTION__))
; 17092 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", 17092, __extension__ __PRETTY_FUNCTION__
))
; 17093 17094 // C++ [class.friend]p3: 17095 // A friend declaration that does not declare a function shall have one of 17096 // the following forms: 17097 // friend elaborated-type-specifier ; 17098 // friend simple-type-specifier ; 17099 // friend typename-specifier ; 17100 // 17101 // Any declaration with a type qualifier does not have that form. (It's 17102 // legal to specify a qualified type as a friend, you just can't write the 17103 // keywords.) 17104 if (DS.getTypeQualifiers()) { 17105 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 17106 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 17107 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 17108 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 17109 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 17110 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 17111 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 17112 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 17113 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 17114 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 17115 } 17116 17117 // Try to convert the decl specifier to a type. This works for 17118 // friend templates because ActOnTag never produces a ClassTemplateDecl 17119 // for a TUK_Friend. 17120 Declarator TheDeclarator(DS, ParsedAttributesView::none(), 17121 DeclaratorContext::Member); 17122 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 17123 QualType T = TSI->getType(); 17124 if (TheDeclarator.isInvalidType()) 17125 return nullptr; 17126 17127 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 17128 return nullptr; 17129 17130 // This is definitely an error in C++98. It's probably meant to 17131 // be forbidden in C++0x, too, but the specification is just 17132 // poorly written. 17133 // 17134 // The problem is with declarations like the following: 17135 // template <T> friend A<T>::foo; 17136 // where deciding whether a class C is a friend or not now hinges 17137 // on whether there exists an instantiation of A that causes 17138 // 'foo' to equal C. There are restrictions on class-heads 17139 // (which we declare (by fiat) elaborated friend declarations to 17140 // be) that makes this tractable. 17141 // 17142 // FIXME: handle "template <> friend class A<T>;", which 17143 // is possibly well-formed? Who even knows? 17144 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 17145 Diag(Loc, diag::err_tagless_friend_type_template) 17146 << DS.getSourceRange(); 17147 return nullptr; 17148 } 17149 17150 // C++98 [class.friend]p1: A friend of a class is a function 17151 // or class that is not a member of the class . . . 17152 // This is fixed in DR77, which just barely didn't make the C++03 17153 // deadline. It's also a very silly restriction that seriously 17154 // affects inner classes and which nobody else seems to implement; 17155 // thus we never diagnose it, not even in -pedantic. 17156 // 17157 // But note that we could warn about it: it's always useless to 17158 // friend one of your own members (it's not, however, worthless to 17159 // friend a member of an arbitrary specialization of your template). 17160 17161 Decl *D; 17162 if (!TempParams.empty()) 17163 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 17164 TempParams, 17165 TSI, 17166 DS.getFriendSpecLoc()); 17167 else 17168 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 17169 17170 if (!D) 17171 return nullptr; 17172 17173 D->setAccess(AS_public); 17174 CurContext->addDecl(D); 17175 17176 return D; 17177} 17178 17179NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 17180 MultiTemplateParamsArg TemplateParams) { 17181 const DeclSpec &DS = D.getDeclSpec(); 17182 17183 assert(DS.isFriendSpecified())(static_cast <bool> (DS.isFriendSpecified()) ? void (0)
: __assert_fail ("DS.isFriendSpecified()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 17183, __extension__ __PRETTY_FUNCTION__))
; 17184 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", 17184, __extension__ __PRETTY_FUNCTION__
))
; 17185 17186 SourceLocation Loc = D.getIdentifierLoc(); 17187 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17188 17189 // C++ [class.friend]p1 17190 // A friend of a class is a function or class.... 17191 // Note that this sees through typedefs, which is intended. 17192 // It *doesn't* see through dependent types, which is correct 17193 // according to [temp.arg.type]p3: 17194 // If a declaration acquires a function type through a 17195 // type dependent on a template-parameter and this causes 17196 // a declaration that does not use the syntactic form of a 17197 // function declarator to have a function type, the program 17198 // is ill-formed. 17199 if (!TInfo->getType()->isFunctionType()) { 17200 Diag(Loc, diag::err_unexpected_friend); 17201 17202 // It might be worthwhile to try to recover by creating an 17203 // appropriate declaration. 17204 return nullptr; 17205 } 17206 17207 // C++ [namespace.memdef]p3 17208 // - If a friend declaration in a non-local class first declares a 17209 // class or function, the friend class or function is a member 17210 // of the innermost enclosing namespace. 17211 // - The name of the friend is not found by simple name lookup 17212 // until a matching declaration is provided in that namespace 17213 // scope (either before or after the class declaration granting 17214 // friendship). 17215 // - If a friend function is called, its name may be found by the 17216 // name lookup that considers functions from namespaces and 17217 // classes associated with the types of the function arguments. 17218 // - When looking for a prior declaration of a class or a function 17219 // declared as a friend, scopes outside the innermost enclosing 17220 // namespace scope are not considered. 17221 17222 CXXScopeSpec &SS = D.getCXXScopeSpec(); 17223 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 17224 assert(NameInfo.getName())(static_cast <bool> (NameInfo.getName()) ? void (0) : __assert_fail
("NameInfo.getName()", "clang/lib/Sema/SemaDeclCXX.cpp", 17224
, __extension__ __PRETTY_FUNCTION__))
; 17225 17226 // Check for unexpanded parameter packs. 17227 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 17228 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 17229 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 17230 return nullptr; 17231 17232 // The context we found the declaration in, or in which we should 17233 // create the declaration. 17234 DeclContext *DC; 17235 Scope *DCScope = S; 17236 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 17237 ForExternalRedeclaration); 17238 17239 // There are five cases here. 17240 // - There's no scope specifier and we're in a local class. Only look 17241 // for functions declared in the immediately-enclosing block scope. 17242 // We recover from invalid scope qualifiers as if they just weren't there. 17243 FunctionDecl *FunctionContainingLocalClass = nullptr; 17244 if ((SS.isInvalid() || !SS.isSet()) && 17245 (FunctionContainingLocalClass = 17246 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 17247 // C++11 [class.friend]p11: 17248 // If a friend declaration appears in a local class and the name 17249 // specified is an unqualified name, a prior declaration is 17250 // looked up without considering scopes that are outside the 17251 // innermost enclosing non-class scope. For a friend function 17252 // declaration, if there is no prior declaration, the program is 17253 // ill-formed. 17254 17255 // Find the innermost enclosing non-class scope. This is the block 17256 // scope containing the local class definition (or for a nested class, 17257 // the outer local class). 17258 DCScope = S->getFnParent(); 17259 17260 // Look up the function name in the scope. 17261 Previous.clear(LookupLocalFriendName); 17262 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 17263 17264 if (!Previous.empty()) { 17265 // All possible previous declarations must have the same context: 17266 // either they were declared at block scope or they are members of 17267 // one of the enclosing local classes. 17268 DC = Previous.getRepresentativeDecl()->getDeclContext(); 17269 } else { 17270 // This is ill-formed, but provide the context that we would have 17271 // declared the function in, if we were permitted to, for error recovery. 17272 DC = FunctionContainingLocalClass; 17273 } 17274 adjustContextForLocalExternDecl(DC); 17275 17276 // C++ [class.friend]p6: 17277 // A function can be defined in a friend declaration of a class if and 17278 // only if the class is a non-local class (9.8), the function name is 17279 // unqualified, and the function has namespace scope. 17280 if (D.isFunctionDefinition()) { 17281 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 17282 } 17283 17284 // - There's no scope specifier, in which case we just go to the 17285 // appropriate scope and look for a function or function template 17286 // there as appropriate. 17287 } else if (SS.isInvalid() || !SS.isSet()) { 17288 // C++11 [namespace.memdef]p3: 17289 // If the name in a friend declaration is neither qualified nor 17290 // a template-id and the declaration is a function or an 17291 // elaborated-type-specifier, the lookup to determine whether 17292 // the entity has been previously declared shall not consider 17293 // any scopes outside the innermost enclosing namespace. 17294 bool isTemplateId = 17295 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 17296 17297 // Find the appropriate context according to the above. 17298 DC = CurContext; 17299 17300 // Skip class contexts. If someone can cite chapter and verse 17301 // for this behavior, that would be nice --- it's what GCC and 17302 // EDG do, and it seems like a reasonable intent, but the spec 17303 // really only says that checks for unqualified existing 17304 // declarations should stop at the nearest enclosing namespace, 17305 // not that they should only consider the nearest enclosing 17306 // namespace. 17307 while (DC->isRecord()) 17308 DC = DC->getParent(); 17309 17310 DeclContext *LookupDC = DC->getNonTransparentContext(); 17311 while (true) { 17312 LookupQualifiedName(Previous, LookupDC); 17313 17314 if (!Previous.empty()) { 17315 DC = LookupDC; 17316 break; 17317 } 17318 17319 if (isTemplateId) { 17320 if (isa<TranslationUnitDecl>(LookupDC)) break; 17321 } else { 17322 if (LookupDC->isFileContext()) break; 17323 } 17324 LookupDC = LookupDC->getParent(); 17325 } 17326 17327 DCScope = getScopeForDeclContext(S, DC); 17328 17329 // - There's a non-dependent scope specifier, in which case we 17330 // compute it and do a previous lookup there for a function 17331 // or function template. 17332 } else if (!SS.getScopeRep()->isDependent()) { 17333 DC = computeDeclContext(SS); 17334 if (!DC) return nullptr; 17335 17336 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 17337 17338 LookupQualifiedName(Previous, DC); 17339 17340 // C++ [class.friend]p1: A friend of a class is a function or 17341 // class that is not a member of the class . . . 17342 if (DC->Equals(CurContext)) 17343 Diag(DS.getFriendSpecLoc(), 17344 getLangOpts().CPlusPlus11 ? 17345 diag::warn_cxx98_compat_friend_is_member : 17346 diag::err_friend_is_member); 17347 17348 if (D.isFunctionDefinition()) { 17349 // C++ [class.friend]p6: 17350 // A function can be defined in a friend declaration of a class if and 17351 // only if the class is a non-local class (9.8), the function name is 17352 // unqualified, and the function has namespace scope. 17353 // 17354 // FIXME: We should only do this if the scope specifier names the 17355 // innermost enclosing namespace; otherwise the fixit changes the 17356 // meaning of the code. 17357 SemaDiagnosticBuilder DB 17358 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 17359 17360 DB << SS.getScopeRep(); 17361 if (DC->isFileContext()) 17362 DB << FixItHint::CreateRemoval(SS.getRange()); 17363 SS.clear(); 17364 } 17365 17366 // - There's a scope specifier that does not match any template 17367 // parameter lists, in which case we use some arbitrary context, 17368 // create a method or method template, and wait for instantiation. 17369 // - There's a scope specifier that does match some template 17370 // parameter lists, which we don't handle right now. 17371 } else { 17372 if (D.isFunctionDefinition()) { 17373 // C++ [class.friend]p6: 17374 // A function can be defined in a friend declaration of a class if and 17375 // only if the class is a non-local class (9.8), the function name is 17376 // unqualified, and the function has namespace scope. 17377 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 17378 << SS.getScopeRep(); 17379 } 17380 17381 DC = CurContext; 17382 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", 17382, __extension__ __PRETTY_FUNCTION__
))
; 17383 } 17384 17385 if (!DC->isRecord()) { 17386 int DiagArg = -1; 17387 switch (D.getName().getKind()) { 17388 case UnqualifiedIdKind::IK_ConstructorTemplateId: 17389 case UnqualifiedIdKind::IK_ConstructorName: 17390 DiagArg = 0; 17391 break; 17392 case UnqualifiedIdKind::IK_DestructorName: 17393 DiagArg = 1; 17394 break; 17395 case UnqualifiedIdKind::IK_ConversionFunctionId: 17396 DiagArg = 2; 17397 break; 17398 case UnqualifiedIdKind::IK_DeductionGuideName: 17399 DiagArg = 3; 17400 break; 17401 case UnqualifiedIdKind::IK_Identifier: 17402 case UnqualifiedIdKind::IK_ImplicitSelfParam: 17403 case UnqualifiedIdKind::IK_LiteralOperatorId: 17404 case UnqualifiedIdKind::IK_OperatorFunctionId: 17405 case UnqualifiedIdKind::IK_TemplateId: 17406 break; 17407 } 17408 // This implies that it has to be an operator or function. 17409 if (DiagArg >= 0) { 17410 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 17411 return nullptr; 17412 } 17413 } 17414 17415 // FIXME: This is an egregious hack to cope with cases where the scope stack 17416 // does not contain the declaration context, i.e., in an out-of-line 17417 // definition of a class. 17418 Scope FakeDCScope(S, Scope::DeclScope, Diags); 17419 if (!DCScope) { 17420 FakeDCScope.setEntity(DC); 17421 DCScope = &FakeDCScope; 17422 } 17423 17424 bool AddToScope = true; 17425 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 17426 TemplateParams, AddToScope); 17427 if (!ND) return nullptr; 17428 17429 assert(ND->getLexicalDeclContext() == CurContext)(static_cast <bool> (ND->getLexicalDeclContext() == CurContext
) ? void (0) : __assert_fail ("ND->getLexicalDeclContext() == CurContext"
, "clang/lib/Sema/SemaDeclCXX.cpp", 17429, __extension__ __PRETTY_FUNCTION__
))
; 17430 17431 // If we performed typo correction, we might have added a scope specifier 17432 // and changed the decl context. 17433 DC = ND->getDeclContext(); 17434 17435 // Add the function declaration to the appropriate lookup tables, 17436 // adjusting the redeclarations list as necessary. We don't 17437 // want to do this yet if the friending class is dependent. 17438 // 17439 // Also update the scope-based lookup if the target context's 17440 // lookup context is in lexical scope. 17441 if (!CurContext->isDependentContext()) { 17442 DC = DC->getRedeclContext(); 17443 DC->makeDeclVisibleInContext(ND); 17444 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 17445 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 17446 } 17447 17448 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 17449 D.getIdentifierLoc(), ND, 17450 DS.getFriendSpecLoc()); 17451 FrD->setAccess(AS_public); 17452 CurContext->addDecl(FrD); 17453 17454 if (ND->isInvalidDecl()) { 17455 FrD->setInvalidDecl(); 17456 } else { 17457 if (DC->isRecord()) CheckFriendAccess(ND); 17458 17459 FunctionDecl *FD; 17460 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 17461 FD = FTD->getTemplatedDecl(); 17462 else 17463 FD = cast<FunctionDecl>(ND); 17464 17465 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 17466 // default argument expression, that declaration shall be a definition 17467 // and shall be the only declaration of the function or function 17468 // template in the translation unit. 17469 if (functionDeclHasDefaultArgument(FD)) { 17470 // We can't look at FD->getPreviousDecl() because it may not have been set 17471 // if we're in a dependent context. If the function is known to be a 17472 // redeclaration, we will have narrowed Previous down to the right decl. 17473 if (D.isRedeclaration()) { 17474 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 17475 Diag(Previous.getRepresentativeDecl()->getLocation(), 17476 diag::note_previous_declaration); 17477 } else if (!D.isFunctionDefinition()) 17478 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 17479 } 17480 17481 // Mark templated-scope function declarations as unsupported. 17482 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 17483 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 17484 << SS.getScopeRep() << SS.getRange() 17485 << cast<CXXRecordDecl>(CurContext); 17486 FrD->setUnsupportedFriend(true); 17487 } 17488 } 17489 17490 warnOnReservedIdentifier(ND); 17491 17492 return ND; 17493} 17494 17495void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 17496 AdjustDeclIfTemplate(Dcl); 17497 17498 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 17499 if (!Fn) { 17500 Diag(DelLoc, diag::err_deleted_non_function); 17501 return; 17502 } 17503 17504 // Deleted function does not have a body. 17505 Fn->setWillHaveBody(false); 17506 17507 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 17508 // Don't consider the implicit declaration we generate for explicit 17509 // specializations. FIXME: Do not generate these implicit declarations. 17510 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 17511 Prev->getPreviousDecl()) && 17512 !Prev->isDefined()) { 17513 Diag(DelLoc, diag::err_deleted_decl_not_first); 17514 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 17515 Prev->isImplicit() ? diag::note_previous_implicit_declaration 17516 : diag::note_previous_declaration); 17517 // We can't recover from this; the declaration might have already 17518 // been used. 17519 Fn->setInvalidDecl(); 17520 return; 17521 } 17522 17523 // To maintain the invariant that functions are only deleted on their first 17524 // declaration, mark the implicitly-instantiated declaration of the 17525 // explicitly-specialized function as deleted instead of marking the 17526 // instantiated redeclaration. 17527 Fn = Fn->getCanonicalDecl(); 17528 } 17529 17530 // dllimport/dllexport cannot be deleted. 17531 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 17532 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 17533 Fn->setInvalidDecl(); 17534 } 17535 17536 // C++11 [basic.start.main]p3: 17537 // A program that defines main as deleted [...] is ill-formed. 17538 if (Fn->isMain()) 17539 Diag(DelLoc, diag::err_deleted_main); 17540 17541 // C++11 [dcl.fct.def.delete]p4: 17542 // A deleted function is implicitly inline. 17543 Fn->setImplicitlyInline(); 17544 Fn->setDeletedAsWritten(); 17545} 17546 17547void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 17548 if (!Dcl || Dcl->isInvalidDecl()) 17549 return; 17550 17551 auto *FD = dyn_cast<FunctionDecl>(Dcl); 17552 if (!FD) { 17553 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 17554 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 17555 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 17556 return; 17557 } 17558 } 17559 17560 Diag(DefaultLoc, diag::err_default_special_members) 17561 << getLangOpts().CPlusPlus20; 17562 return; 17563 } 17564 17565 // Reject if this can't possibly be a defaultable function. 17566 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 17567 if (!DefKind && 17568 // A dependent function that doesn't locally look defaultable can 17569 // still instantiate to a defaultable function if it's a constructor 17570 // or assignment operator. 17571 (!FD->isDependentContext() || 17572 (!isa<CXXConstructorDecl>(FD) && 17573 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 17574 Diag(DefaultLoc, diag::err_default_special_members) 17575 << getLangOpts().CPlusPlus20; 17576 return; 17577 } 17578 17579 // Issue compatibility warning. We already warned if the operator is 17580 // 'operator<=>' when parsing the '<=>' token. 17581 if (DefKind.isComparison() && 17582 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 17583 Diag(DefaultLoc, getLangOpts().CPlusPlus20 17584 ? diag::warn_cxx17_compat_defaulted_comparison 17585 : diag::ext_defaulted_comparison); 17586 } 17587 17588 FD->setDefaulted(); 17589 FD->setExplicitlyDefaulted(); 17590 FD->setDefaultLoc(DefaultLoc); 17591 17592 // Defer checking functions that are defaulted in a dependent context. 17593 if (FD->isDependentContext()) 17594 return; 17595 17596 // Unset that we will have a body for this function. We might not, 17597 // if it turns out to be trivial, and we don't need this marking now 17598 // that we've marked it as defaulted. 17599 FD->setWillHaveBody(false); 17600 17601 if (DefKind.isComparison()) { 17602 // If this comparison's defaulting occurs within the definition of its 17603 // lexical class context, we have to do the checking when complete. 17604 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext())) 17605 if (!RD->isCompleteDefinition()) 17606 return; 17607 } 17608 17609 // If this member fn was defaulted on its first declaration, we will have 17610 // already performed the checking in CheckCompletedCXXClass. Such a 17611 // declaration doesn't trigger an implicit definition. 17612 if (isa<CXXMethodDecl>(FD)) { 17613 const FunctionDecl *Primary = FD; 17614 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 17615 // Ask the template instantiation pattern that actually had the 17616 // '= default' on it. 17617 Primary = Pattern; 17618 if (Primary->getCanonicalDecl()->isDefaulted()) 17619 return; 17620 } 17621 17622 if (DefKind.isComparison()) { 17623 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison())) 17624 FD->setInvalidDecl(); 17625 else 17626 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison()); 17627 } else { 17628 auto *MD = cast<CXXMethodDecl>(FD); 17629 17630 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember(), 17631 DefaultLoc)) 17632 MD->setInvalidDecl(); 17633 else 17634 DefineDefaultedFunction(*this, MD, DefaultLoc); 17635 } 17636} 17637 17638static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 17639 for (Stmt *SubStmt : S->children()) { 17640 if (!SubStmt) 17641 continue; 17642 if (isa<ReturnStmt>(SubStmt)) 17643 Self.Diag(SubStmt->getBeginLoc(), 17644 diag::err_return_in_constructor_handler); 17645 if (!isa<Expr>(SubStmt)) 17646 SearchForReturnInStmt(Self, SubStmt); 17647 } 17648} 17649 17650void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 17651 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 17652 CXXCatchStmt *Handler = TryBlock->getHandler(I); 17653 SearchForReturnInStmt(*this, Handler); 17654 } 17655} 17656 17657void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, 17658 FnBodyKind BodyKind) { 17659 switch (BodyKind) { 17660 case FnBodyKind::Delete: 17661 SetDeclDeleted(D, Loc); 17662 break; 17663 case FnBodyKind::Default: 17664 SetDeclDefaulted(D, Loc); 17665 break; 17666 case FnBodyKind::Other: 17667 llvm_unreachable(::llvm::llvm_unreachable_internal("Parsed function body should be '= delete;' or '= default;'"
, "clang/lib/Sema/SemaDeclCXX.cpp", 17668)
17668 "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", 17668)
; 17669 } 17670} 17671 17672bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 17673 const CXXMethodDecl *Old) { 17674 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 17675 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 17676 17677 if (OldFT->hasExtParameterInfos()) { 17678 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 17679 // A parameter of the overriding method should be annotated with noescape 17680 // if the corresponding parameter of the overridden method is annotated. 17681 if (OldFT->getExtParameterInfo(I).isNoEscape() && 17682 !NewFT->getExtParameterInfo(I).isNoEscape()) { 17683 Diag(New->getParamDecl(I)->getLocation(), 17684 diag::warn_overriding_method_missing_noescape); 17685 Diag(Old->getParamDecl(I)->getLocation(), 17686 diag::note_overridden_marked_noescape); 17687 } 17688 } 17689 17690 // Virtual overrides must have the same code_seg. 17691 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 17692 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 17693 if ((NewCSA || OldCSA) && 17694 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 17695 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 17696 Diag(Old->getLocation(), diag::note_previous_declaration); 17697 return true; 17698 } 17699 17700 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 17701 17702 // If the calling conventions match, everything is fine 17703 if (NewCC == OldCC) 17704 return false; 17705 17706 // If the calling conventions mismatch because the new function is static, 17707 // suppress the calling convention mismatch error; the error about static 17708 // function override (err_static_overrides_virtual from 17709 // Sema::CheckFunctionDeclaration) is more clear. 17710 if (New->getStorageClass() == SC_Static) 17711 return false; 17712 17713 Diag(New->getLocation(), 17714 diag::err_conflicting_overriding_cc_attributes) 17715 << New->getDeclName() << New->getType() << Old->getType(); 17716 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 17717 return true; 17718} 17719 17720bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 17721 const CXXMethodDecl *Old) { 17722 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 17723 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 17724 17725 if (Context.hasSameType(NewTy, OldTy) || 17726 NewTy->isDependentType() || OldTy->isDependentType()) 17727 return false; 17728 17729 // Check if the return types are covariant 17730 QualType NewClassTy, OldClassTy; 17731 17732 /// Both types must be pointers or references to classes. 17733 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 17734 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 17735 NewClassTy = NewPT->getPointeeType(); 17736 OldClassTy = OldPT->getPointeeType(); 17737 } 17738 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 17739 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 17740 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 17741 NewClassTy = NewRT->getPointeeType(); 17742 OldClassTy = OldRT->getPointeeType(); 17743 } 17744 } 17745 } 17746 17747 // The return types aren't either both pointers or references to a class type. 17748 if (NewClassTy.isNull()) { 17749 Diag(New->getLocation(), 17750 diag::err_different_return_type_for_overriding_virtual_function) 17751 << New->getDeclName() << NewTy << OldTy 17752 << New->getReturnTypeSourceRange(); 17753 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17754 << Old->getReturnTypeSourceRange(); 17755 17756 return true; 17757 } 17758 17759 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 17760 // C++14 [class.virtual]p8: 17761 // If the class type in the covariant return type of D::f differs from 17762 // that of B::f, the class type in the return type of D::f shall be 17763 // complete at the point of declaration of D::f or shall be the class 17764 // type D. 17765 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 17766 if (!RT->isBeingDefined() && 17767 RequireCompleteType(New->getLocation(), NewClassTy, 17768 diag::err_covariant_return_incomplete, 17769 New->getDeclName())) 17770 return true; 17771 } 17772 17773 // Check if the new class derives from the old class. 17774 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 17775 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 17776 << New->getDeclName() << NewTy << OldTy 17777 << New->getReturnTypeSourceRange(); 17778 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17779 << Old->getReturnTypeSourceRange(); 17780 return true; 17781 } 17782 17783 // Check if we the conversion from derived to base is valid. 17784 if (CheckDerivedToBaseConversion( 17785 NewClassTy, OldClassTy, 17786 diag::err_covariant_return_inaccessible_base, 17787 diag::err_covariant_return_ambiguous_derived_to_base_conv, 17788 New->getLocation(), New->getReturnTypeSourceRange(), 17789 New->getDeclName(), nullptr)) { 17790 // FIXME: this note won't trigger for delayed access control 17791 // diagnostics, and it's impossible to get an undelayed error 17792 // here from access control during the original parse because 17793 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 17794 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17795 << Old->getReturnTypeSourceRange(); 17796 return true; 17797 } 17798 } 17799 17800 // The qualifiers of the return types must be the same. 17801 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 17802 Diag(New->getLocation(), 17803 diag::err_covariant_return_type_different_qualifications) 17804 << New->getDeclName() << NewTy << OldTy 17805 << New->getReturnTypeSourceRange(); 17806 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17807 << Old->getReturnTypeSourceRange(); 17808 return true; 17809 } 17810 17811 17812 // The new class type must have the same or less qualifiers as the old type. 17813 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 17814 Diag(New->getLocation(), 17815 diag::err_covariant_return_type_class_type_more_qualified) 17816 << New->getDeclName() << NewTy << OldTy 17817 << New->getReturnTypeSourceRange(); 17818 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17819 << Old->getReturnTypeSourceRange(); 17820 return true; 17821 } 17822 17823 return false; 17824} 17825 17826/// Mark the given method pure. 17827/// 17828/// \param Method the method to be marked pure. 17829/// 17830/// \param InitRange the source range that covers the "0" initializer. 17831bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 17832 SourceLocation EndLoc = InitRange.getEnd(); 17833 if (EndLoc.isValid()) 17834 Method->setRangeEnd(EndLoc); 17835 17836 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 17837 Method->setPure(); 17838 return false; 17839 } 17840 17841 if (!Method->isInvalidDecl()) 17842 Diag(Method->getLocation(), diag::err_non_virtual_pure) 17843 << Method->getDeclName() << InitRange; 17844 return true; 17845} 17846 17847void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17848 if (D->getFriendObjectKind()) 17849 Diag(D->getLocation(), diag::err_pure_friend); 17850 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17851 CheckPureMethod(M, ZeroLoc); 17852 else 17853 Diag(D->getLocation(), diag::err_illegal_initializer); 17854} 17855 17856/// Determine whether the given declaration is a global variable or 17857/// static data member. 17858static bool isNonlocalVariable(const Decl *D) { 17859 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17860 return Var->hasGlobalStorage(); 17861 17862 return false; 17863} 17864 17865/// Invoked when we are about to parse an initializer for the declaration 17866/// 'Dcl'. 17867/// 17868/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17869/// static data member of class X, names should be looked up in the scope of 17870/// class X. If the declaration had a scope specifier, a scope will have 17871/// been created and passed in for this purpose. Otherwise, S will be null. 17872void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17873 // If there is no declaration, there was an error parsing it. 17874 if (!D || D->isInvalidDecl()) 17875 return; 17876 17877 // We will always have a nested name specifier here, but this declaration 17878 // might not be out of line if the specifier names the current namespace: 17879 // extern int n; 17880 // int ::n = 0; 17881 if (S && D->isOutOfLine()) 17882 EnterDeclaratorContext(S, D->getDeclContext()); 17883 17884 // If we are parsing the initializer for a static data member, push a 17885 // new expression evaluation context that is associated with this static 17886 // data member. 17887 if (isNonlocalVariable(D)) 17888 PushExpressionEvaluationContext( 17889 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17890} 17891 17892/// Invoked after we are finished parsing an initializer for the declaration D. 17893void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17894 // If there is no declaration, there was an error parsing it. 17895 if (!D || D->isInvalidDecl()) 17896 return; 17897 17898 if (isNonlocalVariable(D)) 17899 PopExpressionEvaluationContext(); 17900 17901 if (S && D->isOutOfLine()) 17902 ExitDeclaratorContext(S); 17903} 17904 17905/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17906/// C++ if/switch/while/for statement. 17907/// e.g: "if (int x = f()) {...}" 17908DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17909 // C++ 6.4p2: 17910 // The declarator shall not specify a function or an array. 17911 // The type-specifier-seq shall not contain typedef and shall not declare a 17912 // new class or enumeration. 17913 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", 17914, __extension__ __PRETTY_FUNCTION__
))
17914 "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", 17914, __extension__ __PRETTY_FUNCTION__
))
; 17915 17916 Decl *Dcl = ActOnDeclarator(S, D); 17917 if (!Dcl) 17918 return true; 17919 17920 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17921 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17922 << D.getSourceRange(); 17923 return true; 17924 } 17925 17926 return Dcl; 17927} 17928 17929void Sema::LoadExternalVTableUses() { 17930 if (!ExternalSource) 17931 return; 17932 17933 SmallVector<ExternalVTableUse, 4> VTables; 17934 ExternalSource->ReadUsedVTables(VTables); 17935 SmallVector<VTableUse, 4> NewUses; 17936 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17937 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17938 = VTablesUsed.find(VTables[I].Record); 17939 // Even if a definition wasn't required before, it may be required now. 17940 if (Pos != VTablesUsed.end()) { 17941 if (!Pos->second && VTables[I].DefinitionRequired) 17942 Pos->second = true; 17943 continue; 17944 } 17945 17946 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17947 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17948 } 17949 17950 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17951} 17952 17953void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17954 bool DefinitionRequired) { 17955 // Ignore any vtable uses in unevaluated operands or for classes that do 17956 // not have a vtable. 17957 if (!Class->isDynamicClass() || Class->isDependentContext() || 17958 CurContext->isDependentContext() || isUnevaluatedContext()) 17959 return; 17960 // Do not mark as used if compiling for the device outside of the target 17961 // region. 17962 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17963 !isInOpenMPDeclareTargetContext() && 17964 !isInOpenMPTargetExecutionDirective()) { 17965 if (!DefinitionRequired) 17966 MarkVirtualMembersReferenced(Loc, Class); 17967 return; 17968 } 17969 17970 // Try to insert this class into the map. 17971 LoadExternalVTableUses(); 17972 Class = Class->getCanonicalDecl(); 17973 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17974 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17975 if (!Pos.second) { 17976 // If we already had an entry, check to see if we are promoting this vtable 17977 // to require a definition. If so, we need to reappend to the VTableUses 17978 // list, since we may have already processed the first entry. 17979 if (DefinitionRequired && !Pos.first->second) { 17980 Pos.first->second = true; 17981 } else { 17982 // Otherwise, we can early exit. 17983 return; 17984 } 17985 } else { 17986 // The Microsoft ABI requires that we perform the destructor body 17987 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17988 // the deleting destructor is emitted with the vtable, not with the 17989 // destructor definition as in the Itanium ABI. 17990 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17991 CXXDestructorDecl *DD = Class->getDestructor(); 17992 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17993 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17994 // If this is an out-of-line declaration, marking it referenced will 17995 // not do anything. Manually call CheckDestructor to look up operator 17996 // delete(). 17997 ContextRAII SavedContext(*this, DD); 17998 CheckDestructor(DD); 17999 } else { 18000 MarkFunctionReferenced(Loc, Class->getDestructor()); 18001 } 18002 } 18003 } 18004 } 18005 18006 // Local classes need to have their virtual members marked 18007 // immediately. For all other classes, we mark their virtual members 18008 // at the end of the translation unit. 18009 if (Class->isLocalClass()) 18010 MarkVirtualMembersReferenced(Loc, Class->getDefinition()); 18011 else 18012 VTableUses.push_back(std::make_pair(Class, Loc)); 18013} 18014 18015bool Sema::DefineUsedVTables() { 18016 LoadExternalVTableUses(); 18017 if (VTableUses.empty()) 18018 return false; 18019 18020 // Note: The VTableUses vector could grow as a result of marking 18021 // the members of a class as "used", so we check the size each 18022 // time through the loop and prefer indices (which are stable) to 18023 // iterators (which are not). 18024 bool DefinedAnything = false; 18025 for (unsigned I = 0; I != VTableUses.size(); ++I) { 18026 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 18027 if (!Class) 18028 continue; 18029 TemplateSpecializationKind ClassTSK = 18030 Class->getTemplateSpecializationKind(); 18031 18032 SourceLocation Loc = VTableUses[I].second; 18033 18034 bool DefineVTable = true; 18035 18036 // If this class has a key function, but that key function is 18037 // defined in another translation unit, we don't need to emit the 18038 // vtable even though we're using it. 18039 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 18040 if (KeyFunction && !KeyFunction->hasBody()) { 18041 // The key function is in another translation unit. 18042 DefineVTable = false; 18043 TemplateSpecializationKind TSK = 18044 KeyFunction->getTemplateSpecializationKind(); 18045 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", 18047, __extension__ __PRETTY_FUNCTION__
))
18046 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", 18047, __extension__ __PRETTY_FUNCTION__
))
18047 "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", 18047, __extension__ __PRETTY_FUNCTION__
))
; 18048 (void)TSK; 18049 } else if (!KeyFunction) { 18050 // If we have a class with no key function that is the subject 18051 // of an explicit instantiation declaration, suppress the 18052 // vtable; it will live with the explicit instantiation 18053 // definition. 18054 bool IsExplicitInstantiationDeclaration = 18055 ClassTSK == TSK_ExplicitInstantiationDeclaration; 18056 for (auto *R : Class->redecls()) { 18057 TemplateSpecializationKind TSK 18058 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 18059 if (TSK == TSK_ExplicitInstantiationDeclaration) 18060 IsExplicitInstantiationDeclaration = true; 18061 else if (TSK == TSK_ExplicitInstantiationDefinition) { 18062 IsExplicitInstantiationDeclaration = false; 18063 break; 18064 } 18065 } 18066 18067 if (IsExplicitInstantiationDeclaration) 18068 DefineVTable = false; 18069 } 18070 18071 // The exception specifications for all virtual members may be needed even 18072 // if we are not providing an authoritative form of the vtable in this TU. 18073 // We may choose to emit it available_externally anyway. 18074 if (!DefineVTable) { 18075 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 18076 continue; 18077 } 18078 18079 // Mark all of the virtual members of this class as referenced, so 18080 // that we can build a vtable. Then, tell the AST consumer that a 18081 // vtable for this class is required. 18082 DefinedAnything = true; 18083 MarkVirtualMembersReferenced(Loc, Class); 18084 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 18085 if (VTablesUsed[Canonical]) 18086 Consumer.HandleVTable(Class); 18087 18088 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 18089 // no key function or the key function is inlined. Don't warn in C++ ABIs 18090 // that lack key functions, since the user won't be able to make one. 18091 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 18092 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation && 18093 ClassTSK != TSK_ExplicitInstantiationDefinition) { 18094 const FunctionDecl *KeyFunctionDef = nullptr; 18095 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 18096 KeyFunctionDef->isInlined())) 18097 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; 18098 } 18099 } 18100 VTableUses.clear(); 18101 18102 return DefinedAnything; 18103} 18104 18105void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 18106 const CXXRecordDecl *RD) { 18107 for (const auto *I : RD->methods()) 18108 if (I->isVirtual() && !I->isPure()) 18109 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 18110} 18111 18112void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 18113 const CXXRecordDecl *RD, 18114 bool ConstexprOnly) { 18115 // Mark all functions which will appear in RD's vtable as used. 18116 CXXFinalOverriderMap FinalOverriders; 18117 RD->getFinalOverriders(FinalOverriders); 18118 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 18119 E = FinalOverriders.end(); 18120 I != E; ++I) { 18121 for (OverridingMethods::const_iterator OI = I->second.begin(), 18122 OE = I->second.end(); 18123 OI != OE; ++OI) { 18124 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", 18124, __extension__ __PRETTY_FUNCTION__
))
; 18125 CXXMethodDecl *Overrider = OI->second.front().Method; 18126 18127 // C++ [basic.def.odr]p2: 18128 // [...] A virtual member function is used if it is not pure. [...] 18129 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 18130 MarkFunctionReferenced(Loc, Overrider); 18131 } 18132 } 18133 18134 // Only classes that have virtual bases need a VTT. 18135 if (RD->getNumVBases() == 0) 18136 return; 18137 18138 for (const auto &I : RD->bases()) { 18139 const auto *Base = 18140 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 18141 if (Base->getNumVBases() == 0) 18142 continue; 18143 MarkVirtualMembersReferenced(Loc, Base); 18144 } 18145} 18146 18147/// SetIvarInitializers - This routine builds initialization ASTs for the 18148/// Objective-C implementation whose ivars need be initialized. 18149void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 18150 if (!getLangOpts().CPlusPlus) 18151 return; 18152 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 18153 SmallVector<ObjCIvarDecl*, 8> ivars; 18154 CollectIvarsToConstructOrDestruct(OID, ivars); 18155 if (ivars.empty()) 18156 return; 18157 SmallVector<CXXCtorInitializer*, 32> AllToInit; 18158 for (unsigned i = 0; i < ivars.size(); i++) { 18159 FieldDecl *Field = ivars[i]; 18160 if (Field->isInvalidDecl()) 18161 continue; 18162 18163 CXXCtorInitializer *Member; 18164 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 18165 InitializationKind InitKind = 18166 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 18167 18168 InitializationSequence InitSeq(*this, InitEntity, InitKind, std::nullopt); 18169 ExprResult MemberInit = 18170 InitSeq.Perform(*this, InitEntity, InitKind, std::nullopt); 18171 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 18172 // Note, MemberInit could actually come back empty if no initialization 18173 // is required (e.g., because it would call a trivial default constructor) 18174 if (!MemberInit.get() || MemberInit.isInvalid()) 18175 continue; 18176 18177 Member = 18178 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 18179 SourceLocation(), 18180 MemberInit.getAs<Expr>(), 18181 SourceLocation()); 18182 AllToInit.push_back(Member); 18183 18184 // Be sure that the destructor is accessible and is marked as referenced. 18185 if (const RecordType *RecordTy = 18186 Context.getBaseElementType(Field->getType()) 18187 ->getAs<RecordType>()) { 18188 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 18189 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 18190 MarkFunctionReferenced(Field->getLocation(), Destructor); 18191 CheckDestructorAccess(Field->getLocation(), Destructor, 18192 PDiag(diag::err_access_dtor_ivar) 18193 << Context.getBaseElementType(Field->getType())); 18194 } 18195 } 18196 } 18197 ObjCImplementation->setIvarInitializers(Context, 18198 AllToInit.data(), AllToInit.size()); 18199 } 18200} 18201 18202static 18203void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 18204 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 18205 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 18206 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 18207 Sema &S) { 18208 if (Ctor->isInvalidDecl()) 18209 return; 18210 18211 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 18212 18213 // Target may not be determinable yet, for instance if this is a dependent 18214 // call in an uninstantiated template. 18215 if (Target) { 18216 const FunctionDecl *FNTarget = nullptr; 18217 (void)Target->hasBody(FNTarget); 18218 Target = const_cast<CXXConstructorDecl*>( 18219 cast_or_null<CXXConstructorDecl>(FNTarget)); 18220 } 18221 18222 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 18223 // Avoid dereferencing a null pointer here. 18224 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 18225 18226 if (!Current.insert(Canonical).second) 18227 return; 18228 18229 // We know that beyond here, we aren't chaining into a cycle. 18230 if (!Target || !Target->isDelegatingConstructor() || 18231 Target->isInvalidDecl() || Valid.count(TCanonical)) { 18232 Valid.insert(Current.begin(), Current.end()); 18233 Current.clear(); 18234 // We've hit a cycle. 18235 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 18236 Current.count(TCanonical)) { 18237 // If we haven't diagnosed this cycle yet, do so now. 18238 if (!Invalid.count(TCanonical)) { 18239 S.Diag((*Ctor->init_begin())->getSourceLocation(), 18240 diag::warn_delegating_ctor_cycle) 18241 << Ctor; 18242 18243 // Don't add a note for a function delegating directly to itself. 18244 if (TCanonical != Canonical) 18245 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 18246 18247 CXXConstructorDecl *C = Target; 18248 while (C->getCanonicalDecl() != Canonical) { 18249 const FunctionDecl *FNTarget = nullptr; 18250 (void)C->getTargetConstructor()->hasBody(FNTarget); 18251 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", 18251, __extension__ __PRETTY_FUNCTION__
))
; 18252 18253 C = const_cast<CXXConstructorDecl*>( 18254 cast<CXXConstructorDecl>(FNTarget)); 18255 S.Diag(C->getLocation(), diag::note_which_delegates_to); 18256 } 18257 } 18258 18259 Invalid.insert(Current.begin(), Current.end()); 18260 Current.clear(); 18261 } else { 18262 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 18263 } 18264} 18265 18266 18267void Sema::CheckDelegatingCtorCycles() { 18268 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 18269 18270 for (DelegatingCtorDeclsType::iterator 18271 I = DelegatingCtorDecls.begin(ExternalSource.get()), 18272 E = DelegatingCtorDecls.end(); 18273 I != E; ++I) 18274 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 18275 18276 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 18277 (*CI)->setInvalidDecl(); 18278} 18279 18280namespace { 18281 /// AST visitor that finds references to the 'this' expression. 18282 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 18283 Sema &S; 18284 18285 public: 18286 explicit FindCXXThisExpr(Sema &S) : S(S) { } 18287 18288 bool VisitCXXThisExpr(CXXThisExpr *E) { 18289 S.Diag(E->getLocation(), diag::err_this_static_member_func) 18290 << E->isImplicit(); 18291 return false; 18292 } 18293 }; 18294} 18295 18296bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 18297 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 18298 if (!TSInfo) 18299 return false; 18300 18301 TypeLoc TL = TSInfo->getTypeLoc(); 18302 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 18303 if (!ProtoTL) 18304 return false; 18305 18306 // C++11 [expr.prim.general]p3: 18307 // [The expression this] shall not appear before the optional 18308 // cv-qualifier-seq and it shall not appear within the declaration of a 18309 // static member function (although its type and value category are defined 18310 // within a static member function as they are within a non-static member 18311 // function). [ Note: this is because declaration matching does not occur 18312 // until the complete declarator is known. - end note ] 18313 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 18314 FindCXXThisExpr Finder(*this); 18315 18316 // If the return type came after the cv-qualifier-seq, check it now. 18317 if (Proto->hasTrailingReturn() && 18318 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 18319 return true; 18320 18321 // Check the exception specification. 18322 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 18323 return true; 18324 18325 // Check the trailing requires clause 18326 if (Expr *E = Method->getTrailingRequiresClause()) 18327 if (!Finder.TraverseStmt(E)) 18328 return true; 18329 18330 return checkThisInStaticMemberFunctionAttributes(Method); 18331} 18332 18333bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 18334 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 18335 if (!TSInfo) 18336 return false; 18337 18338 TypeLoc TL = TSInfo->getTypeLoc(); 18339 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 18340 if (!ProtoTL) 18341 return false; 18342 18343 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 18344 FindCXXThisExpr Finder(*this); 18345 18346 switch (Proto->getExceptionSpecType()) { 18347 case EST_Unparsed: 18348 case EST_Uninstantiated: 18349 case EST_Unevaluated: 18350 case EST_BasicNoexcept: 18351 case EST_NoThrow: 18352 case EST_DynamicNone: 18353 case EST_MSAny: 18354 case EST_None: 18355 break; 18356 18357 case EST_DependentNoexcept: 18358 case EST_NoexceptFalse: 18359 case EST_NoexceptTrue: 18360 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 18361 return true; 18362 [[fallthrough]]; 18363 18364 case EST_Dynamic: 18365 for (const auto &E : Proto->exceptions()) { 18366 if (!Finder.TraverseType(E)) 18367 return true; 18368 } 18369 break; 18370 } 18371 18372 return false; 18373} 18374 18375bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 18376 FindCXXThisExpr Finder(*this); 18377 18378 // Check attributes. 18379 for (const auto *A : Method->attrs()) { 18380 // FIXME: This should be emitted by tblgen. 18381 Expr *Arg = nullptr; 18382 ArrayRef<Expr *> Args; 18383 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 18384 Arg = G->getArg(); 18385 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 18386 Arg = G->getArg(); 18387 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 18388 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size()); 18389 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 18390 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size()); 18391 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 18392 Arg = ETLF->getSuccessValue(); 18393 Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size()); 18394 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 18395 Arg = STLF->getSuccessValue(); 18396 Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size()); 18397 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 18398 Arg = LR->getArg(); 18399 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 18400 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size()); 18401 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 18402 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size()); 18403 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 18404 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size()); 18405 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 18406 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size()); 18407 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 18408 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size()); 18409 18410 if (Arg && !Finder.TraverseStmt(Arg)) 18411 return true; 18412 18413 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 18414 if (!Finder.TraverseStmt(Args[I])) 18415 return true; 18416 } 18417 } 18418 18419 return false; 18420} 18421 18422void Sema::checkExceptionSpecification( 18423 bool IsTopLevel, ExceptionSpecificationType EST, 18424 ArrayRef<ParsedType> DynamicExceptions, 18425 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 18426 SmallVectorImpl<QualType> &Exceptions, 18427 FunctionProtoType::ExceptionSpecInfo &ESI) { 18428 Exceptions.clear(); 18429 ESI.Type = EST; 18430 if (EST == EST_Dynamic) { 18431 Exceptions.reserve(DynamicExceptions.size()); 18432 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 18433 // FIXME: Preserve type source info. 18434 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 18435 18436 if (IsTopLevel) { 18437 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 18438 collectUnexpandedParameterPacks(ET, Unexpanded); 18439 if (!Unexpanded.empty()) { 18440 DiagnoseUnexpandedParameterPacks( 18441 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 18442 Unexpanded); 18443 continue; 18444 } 18445 } 18446 18447 // Check that the type is valid for an exception spec, and 18448 // drop it if not. 18449 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 18450 Exceptions.push_back(ET); 18451 } 18452 ESI.Exceptions = Exceptions; 18453 return; 18454 } 18455 18456 if (isComputedNoexcept(EST)) { 18457 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", 18460, __extension__ __PRETTY_FUNCTION__
))
18458 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", 18460, __extension__ __PRETTY_FUNCTION__
))
18459 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", 18460, __extension__ __PRETTY_FUNCTION__
))
18460 "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", 18460, __extension__ __PRETTY_FUNCTION__
))
; 18461 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 18462 ESI.Type = EST_BasicNoexcept; 18463 return; 18464 } 18465 18466 ESI.NoexceptExpr = NoexceptExpr; 18467 return; 18468 } 18469} 18470 18471void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 18472 ExceptionSpecificationType EST, 18473 SourceRange SpecificationRange, 18474 ArrayRef<ParsedType> DynamicExceptions, 18475 ArrayRef<SourceRange> DynamicExceptionRanges, 18476 Expr *NoexceptExpr) { 18477 if (!MethodD) 18478 return; 18479 18480 // Dig out the method we're referring to. 18481 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 18482 MethodD = FunTmpl->getTemplatedDecl(); 18483 18484 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 18485 if (!Method) 18486 return; 18487 18488 // Check the exception specification. 18489 llvm::SmallVector<QualType, 4> Exceptions; 18490 FunctionProtoType::ExceptionSpecInfo ESI; 18491 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 18492 DynamicExceptionRanges, NoexceptExpr, Exceptions, 18493 ESI); 18494 18495 // Update the exception specification on the function type. 18496 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 18497 18498 if (Method->isStatic()) 18499 checkThisInStaticMemberFunctionExceptionSpec(Method); 18500 18501 if (Method->isVirtual()) { 18502 // Check overrides, which we previously had to delay. 18503 for (const CXXMethodDecl *O : Method->overridden_methods()) 18504 CheckOverridingFunctionExceptionSpec(Method, O); 18505 } 18506} 18507 18508/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 18509/// 18510MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 18511 SourceLocation DeclStart, Declarator &D, 18512 Expr *BitWidth, 18513 InClassInitStyle InitStyle, 18514 AccessSpecifier AS, 18515 const ParsedAttr &MSPropertyAttr) { 18516 IdentifierInfo *II = D.getIdentifier(); 18517 if (!II) { 18518 Diag(DeclStart, diag::err_anonymous_property); 18519 return nullptr; 18520 } 18521 SourceLocation Loc = D.getIdentifierLoc(); 18522 18523 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 18524 QualType T = TInfo->getType(); 18525 if (getLangOpts().CPlusPlus) { 18526 CheckExtraCXXDefaultArguments(D); 18527 18528 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 18529 UPPC_DataMemberType)) { 18530 D.setInvalidType(); 18531 T = Context.IntTy; 18532 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 18533 } 18534 } 18535 18536 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 18537 18538 if (D.getDeclSpec().isInlineSpecified()) 18539 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 18540 << getLangOpts().CPlusPlus17; 18541 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 18542 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 18543 diag::err_invalid_thread) 18544 << DeclSpec::getSpecifierName(TSCS); 18545 18546 // Check to see if this name was declared as a member previously 18547 NamedDecl *PrevDecl = nullptr; 18548 LookupResult Previous(*this, II, Loc, LookupMemberName, 18549 ForVisibleRedeclaration); 18550 LookupName(Previous, S); 18551 switch (Previous.getResultKind()) { 18552 case LookupResult::Found: 18553 case LookupResult::FoundUnresolvedValue: 18554 PrevDecl = Previous.getAsSingle<NamedDecl>(); 18555 break; 18556 18557 case LookupResult::FoundOverloaded: 18558 PrevDecl = Previous.getRepresentativeDecl(); 18559 break; 18560 18561 case LookupResult::NotFound: 18562 case LookupResult::NotFoundInCurrentInstantiation: 18563 case LookupResult::Ambiguous: 18564 break; 18565 } 18566 18567 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18568 // Maybe we will complain about the shadowed template parameter. 18569 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 18570 // Just pretend that we didn't see the previous declaration. 18571 PrevDecl = nullptr; 18572 } 18573 18574 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 18575 PrevDecl = nullptr; 18576 18577 SourceLocation TSSL = D.getBeginLoc(); 18578 MSPropertyDecl *NewPD = 18579 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 18580 MSPropertyAttr.getPropertyDataGetter(), 18581 MSPropertyAttr.getPropertyDataSetter()); 18582 ProcessDeclAttributes(TUScope, NewPD, D); 18583 NewPD->setAccess(AS); 18584 18585 if (NewPD->isInvalidDecl()) 18586 Record->setInvalidDecl(); 18587 18588 if (D.getDeclSpec().isModulePrivateSpecified()) 18589 NewPD->setModulePrivate(); 18590 18591 if (NewPD->isInvalidDecl() && PrevDecl) { 18592 // Don't introduce NewFD into scope; there's already something 18593 // with the same name in the same scope. 18594 } else if (II) { 18595 PushOnScopeChains(NewPD, S); 18596 } else 18597 Record->addDecl(NewPD); 18598 18599 return NewPD; 18600} 18601 18602void Sema::ActOnStartFunctionDeclarationDeclarator( 18603 Declarator &Declarator, unsigned TemplateParameterDepth) { 18604 auto &Info = InventedParameterInfos.emplace_back(); 18605 TemplateParameterList *ExplicitParams = nullptr; 18606 ArrayRef<TemplateParameterList *> ExplicitLists = 18607 Declarator.getTemplateParameterLists(); 18608 if (!ExplicitLists.empty()) { 18609 bool IsMemberSpecialization, IsInvalid; 18610 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 18611 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 18612 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 18613 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 18614 /*SuppressDiagnostic=*/true); 18615 } 18616 if (ExplicitParams) { 18617 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 18618 llvm::append_range(Info.TemplateParams, *ExplicitParams); 18619 Info.NumExplicitTemplateParams = ExplicitParams->size(); 18620 } else { 18621 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 18622 Info.NumExplicitTemplateParams = 0; 18623 } 18624} 18625 18626void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 18627 auto &FSI = InventedParameterInfos.back(); 18628 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 18629 if (FSI.NumExplicitTemplateParams != 0) { 18630 TemplateParameterList *ExplicitParams = 18631 Declarator.getTemplateParameterLists().back(); 18632 Declarator.setInventedTemplateParameterList( 18633 TemplateParameterList::Create( 18634 Context, ExplicitParams->getTemplateLoc(), 18635 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 18636 ExplicitParams->getRAngleLoc(), 18637 ExplicitParams->getRequiresClause())); 18638 } else { 18639 Declarator.setInventedTemplateParameterList( 18640 TemplateParameterList::Create( 18641 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 18642 SourceLocation(), /*RequiresClause=*/nullptr)); 18643 } 18644 } 18645 InventedParameterInfos.pop_back(); 18646}