Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 7478, column 18
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/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/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/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -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/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -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-2022-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/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/DeclTemplate.h"
21#include "clang/AST/EvaluatedExprVisitor.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/RecordLayout.h"
24#include "clang/AST/RecursiveASTVisitor.h"
25#include "clang/AST/StmtVisitor.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/AST/TypeOrdering.h"
28#include "clang/Basic/AttributeCommonInfo.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/Specifiers.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Lex/LiteralSupport.h"
33#include "clang/Lex/Preprocessor.h"
34#include "clang/Sema/CXXFieldCollector.h"
35#include "clang/Sema/DeclSpec.h"
36#include "clang/Sema/Initialization.h"
37#include "clang/Sema/Lookup.h"
38#include "clang/Sema/ParsedTemplate.h"
39#include "clang/Sema/Scope.h"
40#include "clang/Sema/ScopeInfo.h"
41#include "clang/Sema/SemaInternal.h"
42#include "clang/Sema/Template.h"
43#include "llvm/ADT/ScopeExit.h"
44#include "llvm/ADT/SmallString.h"
45#include "llvm/ADT/STLExtras.h"
46#include "llvm/ADT/StringExtras.h"
47#include <map>
48#include <set>
49
50using namespace clang;
51
52//===----------------------------------------------------------------------===//
53// CheckDefaultArgumentVisitor
54//===----------------------------------------------------------------------===//
55
56namespace {
57/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
58/// the default argument of a parameter to determine whether it
59/// contains any ill-formed subexpressions. For example, this will
60/// diagnose the use of local variables or parameters within the
61/// default argument expression.
62class CheckDefaultArgumentVisitor
63 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
64 Sema &S;
65 const Expr *DefaultArg;
66
67public:
68 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
69 : S(S), DefaultArg(DefaultArg) {}
70
71 bool VisitExpr(const Expr *Node);
72 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
73 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
74 bool VisitLambdaExpr(const LambdaExpr *Lambda);
75 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
76};
77
78/// VisitExpr - Visit all of the children of this expression.
79bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
80 bool IsInvalid = false;
81 for (const Stmt *SubStmt : Node->children())
82 IsInvalid |= Visit(SubStmt);
83 return IsInvalid;
84}
85
86/// VisitDeclRefExpr - Visit a reference to a declaration, to
87/// determine whether this declaration can be used in the default
88/// argument expression.
89bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
90 const NamedDecl *Decl = DRE->getDecl();
91 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
92 // C++ [dcl.fct.default]p9:
93 // [...] parameters of a function shall not be used in default
94 // argument expressions, even if they are not evaluated. [...]
95 //
96 // C++17 [dcl.fct.default]p9 (by CWG 2082):
97 // [...] A parameter shall not appear as a potentially-evaluated
98 // expression in a default argument. [...]
99 //
100 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
101 return S.Diag(DRE->getBeginLoc(),
102 diag::err_param_default_argument_references_param)
103 << Param->getDeclName() << DefaultArg->getSourceRange();
104 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
105 // C++ [dcl.fct.default]p7:
106 // Local variables shall not be used in default argument
107 // expressions.
108 //
109 // C++17 [dcl.fct.default]p7 (by CWG 2082):
110 // A local variable shall not appear as a potentially-evaluated
111 // expression in a default argument.
112 //
113 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
114 // Note: A local variable cannot be odr-used (6.3) in a default argument.
115 //
116 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
117 return S.Diag(DRE->getBeginLoc(),
118 diag::err_param_default_argument_references_local)
119 << VDecl->getDeclName() << DefaultArg->getSourceRange();
120 }
121
122 return false;
123}
124
125/// VisitCXXThisExpr - Visit a C++ "this" expression.
126bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
127 // C++ [dcl.fct.default]p8:
128 // The keyword this shall not be used in a default argument of a
129 // member function.
130 return S.Diag(ThisE->getBeginLoc(),
131 diag::err_param_default_argument_references_this)
132 << ThisE->getSourceRange();
133}
134
135bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
136 const PseudoObjectExpr *POE) {
137 bool Invalid = false;
138 for (const Expr *E : POE->semantics()) {
139 // Look through bindings.
140 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
141 E = OVE->getSourceExpr();
142 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", 142, __extension__ __PRETTY_FUNCTION__
))
;
143 }
144
145 Invalid |= Visit(E);
146 }
147 return Invalid;
148}
149
150bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
151 // C++11 [expr.lambda.prim]p13:
152 // A lambda-expression appearing in a default argument shall not
153 // implicitly or explicitly capture any entity.
154 if (Lambda->capture_begin() == Lambda->capture_end())
155 return false;
156
157 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
158}
159} // namespace
160
161void
162Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
163 const CXXMethodDecl *Method) {
164 // If we have an MSAny spec already, don't bother.
165 if (!Method || ComputedEST == EST_MSAny)
166 return;
167
168 const FunctionProtoType *Proto
169 = Method->getType()->getAs<FunctionProtoType>();
170 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
171 if (!Proto)
172 return;
173
174 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
175
176 // If we have a throw-all spec at this point, ignore the function.
177 if (ComputedEST == EST_None)
178 return;
179
180 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
181 EST = EST_BasicNoexcept;
182
183 switch (EST) {
184 case EST_Unparsed:
185 case EST_Uninstantiated:
186 case EST_Unevaluated:
187 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", 187)
;
188
189 // If this function can throw any exceptions, make a note of that.
190 case EST_MSAny:
191 case EST_None:
192 // FIXME: Whichever we see last of MSAny and None determines our result.
193 // We should make a consistent, order-independent choice here.
194 ClearExceptions();
195 ComputedEST = EST;
196 return;
197 case EST_NoexceptFalse:
198 ClearExceptions();
199 ComputedEST = EST_None;
200 return;
201 // FIXME: If the call to this decl is using any of its default arguments, we
202 // need to search them for potentially-throwing calls.
203 // If this function has a basic noexcept, it doesn't affect the outcome.
204 case EST_BasicNoexcept:
205 case EST_NoexceptTrue:
206 case EST_NoThrow:
207 return;
208 // If we're still at noexcept(true) and there's a throw() callee,
209 // change to that specification.
210 case EST_DynamicNone:
211 if (ComputedEST == EST_BasicNoexcept)
212 ComputedEST = EST_DynamicNone;
213 return;
214 case EST_DependentNoexcept:
215 llvm_unreachable(::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "clang/lib/Sema/SemaDeclCXX.cpp", 216)
216 "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", 216)
;
217 case EST_Dynamic:
218 break;
219 }
220 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", 220, __extension__ __PRETTY_FUNCTION__
))
;
221 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", 222, __extension__ __PRETTY_FUNCTION__
))
222 "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", 222, __extension__ __PRETTY_FUNCTION__
))
;
223 ComputedEST = EST_Dynamic;
224 // Record the exceptions in this function's exception specification.
225 for (const auto &E : Proto->exceptions())
226 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
227 Exceptions.push_back(E);
228}
229
230void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
231 if (!S || ComputedEST == EST_MSAny)
232 return;
233
234 // FIXME:
235 //
236 // C++0x [except.spec]p14:
237 // [An] implicit exception-specification specifies the type-id T if and
238 // only if T is allowed by the exception-specification of a function directly
239 // invoked by f's implicit definition; f shall allow all exceptions if any
240 // function it directly invokes allows all exceptions, and f shall allow no
241 // exceptions if every function it directly invokes allows no exceptions.
242 //
243 // Note in particular that if an implicit exception-specification is generated
244 // for a function containing a throw-expression, that specification can still
245 // be noexcept(true).
246 //
247 // Note also that 'directly invoked' is not defined in the standard, and there
248 // is no indication that we should only consider potentially-evaluated calls.
249 //
250 // Ultimately we should implement the intent of the standard: the exception
251 // specification should be the set of exceptions which can be thrown by the
252 // implicit definition. For now, we assume that any non-nothrow expression can
253 // throw any exception.
254
255 if (Self->canThrow(S))
256 ComputedEST = EST_None;
257}
258
259ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
260 SourceLocation EqualLoc) {
261 if (RequireCompleteType(Param->getLocation(), Param->getType(),
262 diag::err_typecheck_decl_incomplete_type))
263 return true;
264
265 // C++ [dcl.fct.default]p5
266 // A default argument expression is implicitly converted (clause
267 // 4) to the parameter type. The default argument expression has
268 // the same semantic constraints as the initializer expression in
269 // a declaration of a variable of the parameter type, using the
270 // copy-initialization semantics (8.5).
271 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
272 Param);
273 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
274 EqualLoc);
275 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
276 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
277 if (Result.isInvalid())
278 return true;
279 Arg = Result.getAs<Expr>();
280
281 CheckCompletedExpr(Arg, EqualLoc);
282 Arg = MaybeCreateExprWithCleanups(Arg);
283
284 return Arg;
285}
286
287void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
288 SourceLocation EqualLoc) {
289 // Add the default argument to the parameter
290 Param->setDefaultArg(Arg);
291
292 // We have already instantiated this parameter; provide each of the
293 // instantiations with the uninstantiated default argument.
294 UnparsedDefaultArgInstantiationsMap::iterator InstPos
295 = UnparsedDefaultArgInstantiations.find(Param);
296 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
297 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
298 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
299
300 // We're done tracking this parameter's instantiations.
301 UnparsedDefaultArgInstantiations.erase(InstPos);
302 }
303}
304
305/// ActOnParamDefaultArgument - Check whether the default argument
306/// provided for a function parameter is well-formed. If so, attach it
307/// to the parameter declaration.
308void
309Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
310 Expr *DefaultArg) {
311 if (!param || !DefaultArg)
312 return;
313
314 ParmVarDecl *Param = cast<ParmVarDecl>(param);
315 UnparsedDefaultArgLocs.erase(Param);
316
317 auto Fail = [&] {
318 Param->setInvalidDecl();
319 Param->setDefaultArg(new (Context) OpaqueValueExpr(
320 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
321 };
322
323 // Default arguments are only permitted in C++
324 if (!getLangOpts().CPlusPlus) {
325 Diag(EqualLoc, diag::err_param_default_argument)
326 << DefaultArg->getSourceRange();
327 return Fail();
328 }
329
330 // Check for unexpanded parameter packs.
331 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
332 return Fail();
333 }
334
335 // C++11 [dcl.fct.default]p3
336 // A default argument expression [...] shall not be specified for a
337 // parameter pack.
338 if (Param->isParameterPack()) {
339 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
340 << DefaultArg->getSourceRange();
341 // Recover by discarding the default argument.
342 Param->setDefaultArg(nullptr);
343 return;
344 }
345
346 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
347 if (Result.isInvalid())
348 return Fail();
349
350 DefaultArg = Result.getAs<Expr>();
351
352 // Check that the default argument is well-formed
353 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
354 if (DefaultArgChecker.Visit(DefaultArg))
355 return Fail();
356
357 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
358}
359
360/// ActOnParamUnparsedDefaultArgument - We've seen a default
361/// argument for a function parameter, but we can't parse it yet
362/// because we're inside a class definition. Note that this default
363/// argument will be parsed later.
364void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
365 SourceLocation EqualLoc,
366 SourceLocation ArgLoc) {
367 if (!param)
368 return;
369
370 ParmVarDecl *Param = cast<ParmVarDecl>(param);
371 Param->setUnparsedDefaultArg();
372 UnparsedDefaultArgLocs[Param] = ArgLoc;
373}
374
375/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
376/// the default argument for the parameter param failed.
377void Sema::ActOnParamDefaultArgumentError(Decl *param,
378 SourceLocation EqualLoc) {
379 if (!param)
380 return;
381
382 ParmVarDecl *Param = cast<ParmVarDecl>(param);
383 Param->setInvalidDecl();
384 UnparsedDefaultArgLocs.erase(Param);
385 Param->setDefaultArg(new (Context) OpaqueValueExpr(
386 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
387}
388
389/// CheckExtraCXXDefaultArguments - Check for any extra default
390/// arguments in the declarator, which is not a function declaration
391/// or definition and therefore is not permitted to have default
392/// arguments. This routine should be invoked for every declarator
393/// that is not a function declaration or definition.
394void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
395 // C++ [dcl.fct.default]p3
396 // A default argument expression shall be specified only in the
397 // parameter-declaration-clause of a function declaration or in a
398 // template-parameter (14.1). It shall not be specified for a
399 // parameter pack. If it is specified in a
400 // parameter-declaration-clause, it shall not occur within a
401 // declarator or abstract-declarator of a parameter-declaration.
402 bool MightBeFunction = D.isFunctionDeclarationContext();
403 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
404 DeclaratorChunk &chunk = D.getTypeObject(i);
405 if (chunk.Kind == DeclaratorChunk::Function) {
406 if (MightBeFunction) {
407 // This is a function declaration. It can have default arguments, but
408 // keep looking in case its return type is a function type with default
409 // arguments.
410 MightBeFunction = false;
411 continue;
412 }
413 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
414 ++argIdx) {
415 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
416 if (Param->hasUnparsedDefaultArg()) {
417 std::unique_ptr<CachedTokens> Toks =
418 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
419 SourceRange SR;
420 if (Toks->size() > 1)
421 SR = SourceRange((*Toks)[1].getLocation(),
422 Toks->back().getLocation());
423 else
424 SR = UnparsedDefaultArgLocs[Param];
425 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
426 << SR;
427 } else if (Param->getDefaultArg()) {
428 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
429 << Param->getDefaultArg()->getSourceRange();
430 Param->setDefaultArg(nullptr);
431 }
432 }
433 } else if (chunk.Kind != DeclaratorChunk::Paren) {
434 MightBeFunction = false;
435 }
436 }
437}
438
439static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
440 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
441 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
442 });
443}
444
445/// MergeCXXFunctionDecl - Merge two declarations of the same C++
446/// function, once we already know that they have the same
447/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
448/// error, false otherwise.
449bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
450 Scope *S) {
451 bool Invalid = false;
452
453 // The declaration context corresponding to the scope is the semantic
454 // parent, unless this is a local function declaration, in which case
455 // it is that surrounding function.
456 DeclContext *ScopeDC = New->isLocalExternDecl()
457 ? New->getLexicalDeclContext()
458 : New->getDeclContext();
459
460 // Find the previous declaration for the purpose of default arguments.
461 FunctionDecl *PrevForDefaultArgs = Old;
462 for (/**/; PrevForDefaultArgs;
463 // Don't bother looking back past the latest decl if this is a local
464 // extern declaration; nothing else could work.
465 PrevForDefaultArgs = New->isLocalExternDecl()
466 ? nullptr
467 : PrevForDefaultArgs->getPreviousDecl()) {
468 // Ignore hidden declarations.
469 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
470 continue;
471
472 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
473 !New->isCXXClassMember()) {
474 // Ignore default arguments of old decl if they are not in
475 // the same scope and this is not an out-of-line definition of
476 // a member function.
477 continue;
478 }
479
480 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
481 // If only one of these is a local function declaration, then they are
482 // declared in different scopes, even though isDeclInScope may think
483 // they're in the same scope. (If both are local, the scope check is
484 // sufficient, and if neither is local, then they are in the same scope.)
485 continue;
486 }
487
488 // We found the right previous declaration.
489 break;
490 }
491
492 // C++ [dcl.fct.default]p4:
493 // For non-template functions, default arguments can be added in
494 // later declarations of a function in the same
495 // scope. Declarations in different scopes have completely
496 // distinct sets of default arguments. That is, declarations in
497 // inner scopes do not acquire default arguments from
498 // declarations in outer scopes, and vice versa. In a given
499 // function declaration, all parameters subsequent to a
500 // parameter with a default argument shall have default
501 // arguments supplied in this or previous declarations. A
502 // default argument shall not be redefined by a later
503 // declaration (not even to the same value).
504 //
505 // C++ [dcl.fct.default]p6:
506 // Except for member functions of class templates, the default arguments
507 // in a member function definition that appears outside of the class
508 // definition are added to the set of default arguments provided by the
509 // member function declaration in the class definition.
510 for (unsigned p = 0, NumParams = PrevForDefaultArgs
511 ? PrevForDefaultArgs->getNumParams()
512 : 0;
513 p < NumParams; ++p) {
514 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
515 ParmVarDecl *NewParam = New->getParamDecl(p);
516
517 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
518 bool NewParamHasDfl = NewParam->hasDefaultArg();
519
520 if (OldParamHasDfl && NewParamHasDfl) {
521 unsigned DiagDefaultParamID =
522 diag::err_param_default_argument_redefinition;
523
524 // MSVC accepts that default parameters be redefined for member functions
525 // of template class. The new default parameter's value is ignored.
526 Invalid = true;
527 if (getLangOpts().MicrosoftExt) {
528 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
529 if (MD && MD->getParent()->getDescribedClassTemplate()) {
530 // Merge the old default argument into the new parameter.
531 NewParam->setHasInheritedDefaultArg();
532 if (OldParam->hasUninstantiatedDefaultArg())
533 NewParam->setUninstantiatedDefaultArg(
534 OldParam->getUninstantiatedDefaultArg());
535 else
536 NewParam->setDefaultArg(OldParam->getInit());
537 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
538 Invalid = false;
539 }
540 }
541
542 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
543 // hint here. Alternatively, we could walk the type-source information
544 // for NewParam to find the last source location in the type... but it
545 // isn't worth the effort right now. This is the kind of test case that
546 // is hard to get right:
547 // int f(int);
548 // void g(int (*fp)(int) = f);
549 // void g(int (*fp)(int) = &f);
550 Diag(NewParam->getLocation(), DiagDefaultParamID)
551 << NewParam->getDefaultArgRange();
552
553 // Look for the function declaration where the default argument was
554 // actually written, which may be a declaration prior to Old.
555 for (auto Older = PrevForDefaultArgs;
556 OldParam->hasInheritedDefaultArg(); /**/) {
557 Older = Older->getPreviousDecl();
558 OldParam = Older->getParamDecl(p);
559 }
560
561 Diag(OldParam->getLocation(), diag::note_previous_definition)
562 << OldParam->getDefaultArgRange();
563 } else if (OldParamHasDfl) {
564 // Merge the old default argument into the new parameter unless the new
565 // function is a friend declaration in a template class. In the latter
566 // case the default arguments will be inherited when the friend
567 // declaration will be instantiated.
568 if (New->getFriendObjectKind() == Decl::FOK_None ||
569 !New->getLexicalDeclContext()->isDependentContext()) {
570 // It's important to use getInit() here; getDefaultArg()
571 // strips off any top-level ExprWithCleanups.
572 NewParam->setHasInheritedDefaultArg();
573 if (OldParam->hasUnparsedDefaultArg())
574 NewParam->setUnparsedDefaultArg();
575 else if (OldParam->hasUninstantiatedDefaultArg())
576 NewParam->setUninstantiatedDefaultArg(
577 OldParam->getUninstantiatedDefaultArg());
578 else
579 NewParam->setDefaultArg(OldParam->getInit());
580 }
581 } else if (NewParamHasDfl) {
582 if (New->getDescribedFunctionTemplate()) {
583 // Paragraph 4, quoted above, only applies to non-template functions.
584 Diag(NewParam->getLocation(),
585 diag::err_param_default_argument_template_redecl)
586 << NewParam->getDefaultArgRange();
587 Diag(PrevForDefaultArgs->getLocation(),
588 diag::note_template_prev_declaration)
589 << false;
590 } else if (New->getTemplateSpecializationKind()
591 != TSK_ImplicitInstantiation &&
592 New->getTemplateSpecializationKind() != TSK_Undeclared) {
593 // C++ [temp.expr.spec]p21:
594 // Default function arguments shall not be specified in a declaration
595 // or a definition for one of the following explicit specializations:
596 // - the explicit specialization of a function template;
597 // - the explicit specialization of a member function template;
598 // - the explicit specialization of a member function of a class
599 // template where the class template specialization to which the
600 // member function specialization belongs is implicitly
601 // instantiated.
602 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
603 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
604 << New->getDeclName()
605 << NewParam->getDefaultArgRange();
606 } else if (New->getDeclContext()->isDependentContext()) {
607 // C++ [dcl.fct.default]p6 (DR217):
608 // Default arguments for a member function of a class template shall
609 // be specified on the initial declaration of the member function
610 // within the class template.
611 //
612 // Reading the tea leaves a bit in DR217 and its reference to DR205
613 // leads me to the conclusion that one cannot add default function
614 // arguments for an out-of-line definition of a member function of a
615 // dependent type.
616 int WhichKind = 2;
617 if (CXXRecordDecl *Record
618 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
619 if (Record->getDescribedClassTemplate())
620 WhichKind = 0;
621 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
622 WhichKind = 1;
623 else
624 WhichKind = 2;
625 }
626
627 Diag(NewParam->getLocation(),
628 diag::err_param_default_argument_member_template_redecl)
629 << WhichKind
630 << NewParam->getDefaultArgRange();
631 }
632 }
633 }
634
635 // DR1344: If a default argument is added outside a class definition and that
636 // default argument makes the function a special member function, the program
637 // is ill-formed. This can only happen for constructors.
638 if (isa<CXXConstructorDecl>(New) &&
639 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
640 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
641 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
642 if (NewSM != OldSM) {
643 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
644 assert(NewParam->hasDefaultArg())(static_cast <bool> (NewParam->hasDefaultArg()) ? void
(0) : __assert_fail ("NewParam->hasDefaultArg()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 644, __extension__ __PRETTY_FUNCTION__))
;
645 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
646 << NewParam->getDefaultArgRange() << NewSM;
647 Diag(Old->getLocation(), diag::note_previous_declaration);
648 }
649 }
650
651 const FunctionDecl *Def;
652 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
653 // template has a constexpr specifier then all its declarations shall
654 // contain the constexpr specifier.
655 if (New->getConstexprKind() != Old->getConstexprKind()) {
656 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
657 << New << static_cast<int>(New->getConstexprKind())
658 << static_cast<int>(Old->getConstexprKind());
659 Diag(Old->getLocation(), diag::note_previous_declaration);
660 Invalid = true;
661 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
662 Old->isDefined(Def) &&
663 // If a friend function is inlined but does not have 'inline'
664 // specifier, it is a definition. Do not report attribute conflict
665 // in this case, redefinition will be diagnosed later.
666 (New->isInlineSpecified() ||
667 New->getFriendObjectKind() == Decl::FOK_None)) {
668 // C++11 [dcl.fcn.spec]p4:
669 // If the definition of a function appears in a translation unit before its
670 // first declaration as inline, the program is ill-formed.
671 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
672 Diag(Def->getLocation(), diag::note_previous_definition);
673 Invalid = true;
674 }
675
676 // C++17 [temp.deduct.guide]p3:
677 // Two deduction guide declarations in the same translation unit
678 // for the same class template shall not have equivalent
679 // parameter-declaration-clauses.
680 if (isa<CXXDeductionGuideDecl>(New) &&
681 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
682 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
683 Diag(Old->getLocation(), diag::note_previous_declaration);
684 }
685
686 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
687 // argument expression, that declaration shall be a definition and shall be
688 // the only declaration of the function or function template in the
689 // translation unit.
690 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
691 functionDeclHasDefaultArgument(Old)) {
692 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
693 Diag(Old->getLocation(), diag::note_previous_declaration);
694 Invalid = true;
695 }
696
697 // C++11 [temp.friend]p4 (DR329):
698 // When a function is defined in a friend function declaration in a class
699 // template, the function is instantiated when the function is odr-used.
700 // The same restrictions on multiple declarations and definitions that
701 // apply to non-template function declarations and definitions also apply
702 // to these implicit definitions.
703 const FunctionDecl *OldDefinition = nullptr;
704 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
705 Old->isDefined(OldDefinition, true))
706 CheckForFunctionRedefinition(New, OldDefinition);
707
708 return Invalid;
709}
710
711NamedDecl *
712Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
713 MultiTemplateParamsArg TemplateParamLists) {
714 assert(D.isDecompositionDeclarator())(static_cast <bool> (D.isDecompositionDeclarator()) ? void
(0) : __assert_fail ("D.isDecompositionDeclarator()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 714, __extension__ __PRETTY_FUNCTION__))
;
715 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
716
717 // The syntax only allows a decomposition declarator as a simple-declaration,
718 // a for-range-declaration, or a condition in Clang, but we parse it in more
719 // cases than that.
720 if (!D.mayHaveDecompositionDeclarator()) {
721 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
722 << Decomp.getSourceRange();
723 return nullptr;
724 }
725
726 if (!TemplateParamLists.empty()) {
727 // FIXME: There's no rule against this, but there are also no rules that
728 // would actually make it usable, so we reject it for now.
729 Diag(TemplateParamLists.front()->getTemplateLoc(),
730 diag::err_decomp_decl_template);
731 return nullptr;
732 }
733
734 Diag(Decomp.getLSquareLoc(),
735 !getLangOpts().CPlusPlus17
736 ? diag::ext_decomp_decl
737 : D.getContext() == DeclaratorContext::Condition
738 ? diag::ext_decomp_decl_cond
739 : diag::warn_cxx14_compat_decomp_decl)
740 << Decomp.getSourceRange();
741
742 // The semantic context is always just the current context.
743 DeclContext *const DC = CurContext;
744
745 // C++17 [dcl.dcl]/8:
746 // The decl-specifier-seq shall contain only the type-specifier auto
747 // and cv-qualifiers.
748 // C++2a [dcl.dcl]/8:
749 // If decl-specifier-seq contains any decl-specifier other than static,
750 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
751 auto &DS = D.getDeclSpec();
752 {
753 SmallVector<StringRef, 8> BadSpecifiers;
754 SmallVector<SourceLocation, 8> BadSpecifierLocs;
755 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
756 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
757 if (auto SCS = DS.getStorageClassSpec()) {
758 if (SCS == DeclSpec::SCS_static) {
759 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
760 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
761 } else {
762 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
763 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
764 }
765 }
766 if (auto TSCS = DS.getThreadStorageClassSpec()) {
767 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
768 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
769 }
770 if (DS.hasConstexprSpecifier()) {
771 BadSpecifiers.push_back(
772 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
773 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
774 }
775 if (DS.isInlineSpecified()) {
776 BadSpecifiers.push_back("inline");
777 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
778 }
779 if (!BadSpecifiers.empty()) {
780 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
781 Err << (int)BadSpecifiers.size()
782 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
783 // Don't add FixItHints to remove the specifiers; we do still respect
784 // them when building the underlying variable.
785 for (auto Loc : BadSpecifierLocs)
786 Err << SourceRange(Loc, Loc);
787 } else if (!CPlusPlus20Specifiers.empty()) {
788 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
789 getLangOpts().CPlusPlus20
790 ? diag::warn_cxx17_compat_decomp_decl_spec
791 : diag::ext_decomp_decl_spec);
792 Warn << (int)CPlusPlus20Specifiers.size()
793 << llvm::join(CPlusPlus20Specifiers.begin(),
794 CPlusPlus20Specifiers.end(), " ");
795 for (auto Loc : CPlusPlus20SpecifierLocs)
796 Warn << SourceRange(Loc, Loc);
797 }
798 // We can't recover from it being declared as a typedef.
799 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
800 return nullptr;
801 }
802
803 // C++2a [dcl.struct.bind]p1:
804 // A cv that includes volatile is deprecated
805 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
806 getLangOpts().CPlusPlus20)
807 Diag(DS.getVolatileSpecLoc(),
808 diag::warn_deprecated_volatile_structured_binding);
809
810 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
811 QualType R = TInfo->getType();
812
813 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
814 UPPC_DeclarationType))
815 D.setInvalidType();
816
817 // The syntax only allows a single ref-qualifier prior to the decomposition
818 // declarator. No other declarator chunks are permitted. Also check the type
819 // specifier here.
820 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
821 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
822 (D.getNumTypeObjects() == 1 &&
823 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
824 Diag(Decomp.getLSquareLoc(),
825 (D.hasGroupingParens() ||
826 (D.getNumTypeObjects() &&
827 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
828 ? diag::err_decomp_decl_parens
829 : diag::err_decomp_decl_type)
830 << R;
831
832 // In most cases, there's no actual problem with an explicitly-specified
833 // type, but a function type won't work here, and ActOnVariableDeclarator
834 // shouldn't be called for such a type.
835 if (R->isFunctionType())
836 D.setInvalidType();
837 }
838
839 // Build the BindingDecls.
840 SmallVector<BindingDecl*, 8> Bindings;
841
842 // Build the BindingDecls.
843 for (auto &B : D.getDecompositionDeclarator().bindings()) {
844 // Check for name conflicts.
845 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
846 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
847 ForVisibleRedeclaration);
848 LookupName(Previous, S,
849 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
850
851 // It's not permitted to shadow a template parameter name.
852 if (Previous.isSingleResult() &&
853 Previous.getFoundDecl()->isTemplateParameter()) {
854 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
855 Previous.getFoundDecl());
856 Previous.clear();
857 }
858
859 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
860
861 // Find the shadowed declaration before filtering for scope.
862 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
863 ? getShadowedDeclaration(BD, Previous)
864 : nullptr;
865
866 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
867 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
868 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
869 /*AllowInlineNamespace*/false);
870
871 if (!Previous.empty()) {
872 auto *Old = Previous.getRepresentativeDecl();
873 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
874 Diag(Old->getLocation(), diag::note_previous_definition);
875 } else if (ShadowedDecl && !D.isRedeclaration()) {
876 CheckShadow(BD, ShadowedDecl, Previous);
877 }
878 PushOnScopeChains(BD, S, true);
879 Bindings.push_back(BD);
880 ParsingInitForAutoVars.insert(BD);
881 }
882
883 // There are no prior lookup results for the variable itself, because it
884 // is unnamed.
885 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
886 Decomp.getLSquareLoc());
887 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
888 ForVisibleRedeclaration);
889
890 // Build the variable that holds the non-decomposed object.
891 bool AddToScope = true;
892 NamedDecl *New =
893 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
894 MultiTemplateParamsArg(), AddToScope, Bindings);
895 if (AddToScope) {
896 S->AddDecl(New);
897 CurContext->addHiddenDecl(New);
898 }
899
900 if (isInOpenMPDeclareTargetContext())
901 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
902
903 return New;
904}
905
906static bool checkSimpleDecomposition(
907 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
908 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
909 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
910 if ((int64_t)Bindings.size() != NumElems) {
911 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
912 << DecompType << (unsigned)Bindings.size()
913 << (unsigned)NumElems.getLimitedValue(UINT_MAX(2147483647 *2U +1U))
914 << toString(NumElems, 10) << (NumElems < Bindings.size());
915 return true;
916 }
917
918 unsigned I = 0;
919 for (auto *B : Bindings) {
920 SourceLocation Loc = B->getLocation();
921 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
922 if (E.isInvalid())
923 return true;
924 E = GetInit(Loc, E.get(), I++);
925 if (E.isInvalid())
926 return true;
927 B->setBinding(ElemType, E.get());
928 }
929
930 return false;
931}
932
933static bool checkArrayLikeDecomposition(Sema &S,
934 ArrayRef<BindingDecl *> Bindings,
935 ValueDecl *Src, QualType DecompType,
936 const llvm::APSInt &NumElems,
937 QualType ElemType) {
938 return checkSimpleDecomposition(
939 S, Bindings, Src, DecompType, NumElems, ElemType,
940 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
941 ExprResult E = S.ActOnIntegerConstant(Loc, I);
942 if (E.isInvalid())
943 return ExprError();
944 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
945 });
946}
947
948static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
949 ValueDecl *Src, QualType DecompType,
950 const ConstantArrayType *CAT) {
951 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
952 llvm::APSInt(CAT->getSize()),
953 CAT->getElementType());
954}
955
956static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
957 ValueDecl *Src, QualType DecompType,
958 const VectorType *VT) {
959 return checkArrayLikeDecomposition(
960 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
961 S.Context.getQualifiedType(VT->getElementType(),
962 DecompType.getQualifiers()));
963}
964
965static bool checkComplexDecomposition(Sema &S,
966 ArrayRef<BindingDecl *> Bindings,
967 ValueDecl *Src, QualType DecompType,
968 const ComplexType *CT) {
969 return checkSimpleDecomposition(
970 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
971 S.Context.getQualifiedType(CT->getElementType(),
972 DecompType.getQualifiers()),
973 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
974 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
975 });
976}
977
978static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
979 TemplateArgumentListInfo &Args,
980 const TemplateParameterList *Params) {
981 SmallString<128> SS;
982 llvm::raw_svector_ostream OS(SS);
983 bool First = true;
984 unsigned I = 0;
985 for (auto &Arg : Args.arguments()) {
986 if (!First)
987 OS << ", ";
988 Arg.getArgument().print(PrintingPolicy, OS,
989 TemplateParameterList::shouldIncludeTypeForArgument(
990 PrintingPolicy, Params, I));
991 First = false;
992 I++;
993 }
994 return std::string(OS.str());
995}
996
997static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
998 SourceLocation Loc, StringRef Trait,
999 TemplateArgumentListInfo &Args,
1000 unsigned DiagID) {
1001 auto DiagnoseMissing = [&] {
1002 if (DiagID)
1003 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1004 Args, /*Params*/ nullptr);
1005 return true;
1006 };
1007
1008 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1009 NamespaceDecl *Std = S.getStdNamespace();
1010 if (!Std)
1011 return DiagnoseMissing();
1012
1013 // Look up the trait itself, within namespace std. We can diagnose various
1014 // problems with this lookup even if we've been asked to not diagnose a
1015 // missing specialization, because this can only fail if the user has been
1016 // declaring their own names in namespace std or we don't support the
1017 // standard library implementation in use.
1018 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1019 Loc, Sema::LookupOrdinaryName);
1020 if (!S.LookupQualifiedName(Result, Std))
1021 return DiagnoseMissing();
1022 if (Result.isAmbiguous())
1023 return true;
1024
1025 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1026 if (!TraitTD) {
1027 Result.suppressDiagnostics();
1028 NamedDecl *Found = *Result.begin();
1029 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1030 S.Diag(Found->getLocation(), diag::note_declared_at);
1031 return true;
1032 }
1033
1034 // Build the template-id.
1035 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1036 if (TraitTy.isNull())
1037 return true;
1038 if (!S.isCompleteType(Loc, TraitTy)) {
1039 if (DiagID)
1040 S.RequireCompleteType(
1041 Loc, TraitTy, DiagID,
1042 printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1043 TraitTD->getTemplateParameters()));
1044 return true;
1045 }
1046
1047 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1048 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", 1048, __extension__ __PRETTY_FUNCTION__
))
;
1049
1050 // Look up the member of the trait type.
1051 S.LookupQualifiedName(TraitMemberLookup, RD);
1052 return TraitMemberLookup.isAmbiguous();
1053}
1054
1055static TemplateArgumentLoc
1056getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1057 uint64_t I) {
1058 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1059 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1060}
1061
1062static TemplateArgumentLoc
1063getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1064 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1065}
1066
1067namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1068
1069static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1070 llvm::APSInt &Size) {
1071 EnterExpressionEvaluationContext ContextRAII(
1072 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1073
1074 DeclarationName Value = S.PP.getIdentifierInfo("value");
1075 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1076
1077 // Form template argument list for tuple_size<T>.
1078 TemplateArgumentListInfo Args(Loc, Loc);
1079 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1080
1081 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1082 // it's not tuple-like.
1083 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1084 R.empty())
1085 return IsTupleLike::NotTupleLike;
1086
1087 // If we get this far, we've committed to the tuple interpretation, but
1088 // we can still fail if there actually isn't a usable ::value.
1089
1090 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1091 LookupResult &R;
1092 TemplateArgumentListInfo &Args;
1093 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1094 : R(R), Args(Args) {}
1095 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1096 SourceLocation Loc) override {
1097 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1098 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1099 /*Params*/ nullptr);
1100 }
1101 } Diagnoser(R, Args);
1102
1103 ExprResult E =
1104 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1105 if (E.isInvalid())
1106 return IsTupleLike::Error;
1107
1108 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1109 if (E.isInvalid())
1110 return IsTupleLike::Error;
1111
1112 return IsTupleLike::TupleLike;
1113}
1114
1115/// \return std::tuple_element<I, T>::type.
1116static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1117 unsigned I, QualType T) {
1118 // Form template argument list for tuple_element<I, T>.
1119 TemplateArgumentListInfo Args(Loc, Loc);
1120 Args.addArgument(
1121 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1122 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1123
1124 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1125 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1126 if (lookupStdTypeTraitMember(
1127 S, R, Loc, "tuple_element", Args,
1128 diag::err_decomp_decl_std_tuple_element_not_specialized))
1129 return QualType();
1130
1131 auto *TD = R.getAsSingle<TypeDecl>();
1132 if (!TD) {
1133 R.suppressDiagnostics();
1134 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1135 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1136 /*Params*/ nullptr);
1137 if (!R.empty())
1138 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1139 return QualType();
1140 }
1141
1142 return S.Context.getTypeDeclType(TD);
1143}
1144
1145namespace {
1146struct InitializingBinding {
1147 Sema &S;
1148 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1149 Sema::CodeSynthesisContext Ctx;
1150 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1151 Ctx.PointOfInstantiation = BD->getLocation();
1152 Ctx.Entity = BD;
1153 S.pushCodeSynthesisContext(Ctx);
1154 }
1155 ~InitializingBinding() {
1156 S.popCodeSynthesisContext();
1157 }
1158};
1159}
1160
1161static bool checkTupleLikeDecomposition(Sema &S,
1162 ArrayRef<BindingDecl *> Bindings,
1163 VarDecl *Src, QualType DecompType,
1164 const llvm::APSInt &TupleSize) {
1165 if ((int64_t)Bindings.size() != TupleSize) {
1166 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1167 << DecompType << (unsigned)Bindings.size()
1168 << (unsigned)TupleSize.getLimitedValue(UINT_MAX(2147483647 *2U +1U))
1169 << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1170 return true;
1171 }
1172
1173 if (Bindings.empty())
1174 return false;
1175
1176 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1177
1178 // [dcl.decomp]p3:
1179 // The unqualified-id get is looked up in the scope of E by class member
1180 // access lookup ...
1181 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1182 bool UseMemberGet = false;
1183 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1184 if (auto *RD = DecompType->getAsCXXRecordDecl())
1185 S.LookupQualifiedName(MemberGet, RD);
1186 if (MemberGet.isAmbiguous())
1187 return true;
1188 // ... and if that finds at least one declaration that is a function
1189 // template whose first template parameter is a non-type parameter ...
1190 for (NamedDecl *D : MemberGet) {
1191 if (FunctionTemplateDecl *FTD =
1192 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1193 TemplateParameterList *TPL = FTD->getTemplateParameters();
1194 if (TPL->size() != 0 &&
1195 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1196 // ... the initializer is e.get<i>().
1197 UseMemberGet = true;
1198 break;
1199 }
1200 }
1201 }
1202 }
1203
1204 unsigned I = 0;
1205 for (auto *B : Bindings) {
1206 InitializingBinding InitContext(S, B);
1207 SourceLocation Loc = B->getLocation();
1208
1209 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1210 if (E.isInvalid())
1211 return true;
1212
1213 // e is an lvalue if the type of the entity is an lvalue reference and
1214 // an xvalue otherwise
1215 if (!Src->getType()->isLValueReferenceType())
1216 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1217 E.get(), nullptr, VK_XValue,
1218 FPOptionsOverride());
1219
1220 TemplateArgumentListInfo Args(Loc, Loc);
1221 Args.addArgument(
1222 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1223
1224 if (UseMemberGet) {
1225 // if [lookup of member get] finds at least one declaration, the
1226 // initializer is e.get<i-1>().
1227 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1228 CXXScopeSpec(), SourceLocation(), nullptr,
1229 MemberGet, &Args, nullptr);
1230 if (E.isInvalid())
1231 return true;
1232
1233 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1234 } else {
1235 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1236 // in the associated namespaces.
1237 Expr *Get = UnresolvedLookupExpr::Create(
1238 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1239 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1240 UnresolvedSetIterator(), UnresolvedSetIterator());
1241
1242 Expr *Arg = E.get();
1243 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1244 }
1245 if (E.isInvalid())
1246 return true;
1247 Expr *Init = E.get();
1248
1249 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1250 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1251 if (T.isNull())
1252 return true;
1253
1254 // each vi is a variable of type "reference to T" initialized with the
1255 // initializer, where the reference is an lvalue reference if the
1256 // initializer is an lvalue and an rvalue reference otherwise
1257 QualType RefType =
1258 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1259 if (RefType.isNull())
1260 return true;
1261 auto *RefVD = VarDecl::Create(
1262 S.Context, Src->getDeclContext(), Loc, Loc,
1263 B->getDeclName().getAsIdentifierInfo(), RefType,
1264 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1265 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1266 RefVD->setTSCSpec(Src->getTSCSpec());
1267 RefVD->setImplicit();
1268 if (Src->isInlineSpecified())
1269 RefVD->setInlineSpecified();
1270 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1271
1272 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1273 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1274 InitializationSequence Seq(S, Entity, Kind, Init);
1275 E = Seq.Perform(S, Entity, Kind, Init);
1276 if (E.isInvalid())
1277 return true;
1278 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1279 if (E.isInvalid())
1280 return true;
1281 RefVD->setInit(E.get());
1282 S.CheckCompleteVariableDeclaration(RefVD);
1283
1284 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1285 DeclarationNameInfo(B->getDeclName(), Loc),
1286 RefVD);
1287 if (E.isInvalid())
1288 return true;
1289
1290 B->setBinding(T, E.get());
1291 I++;
1292 }
1293
1294 return false;
1295}
1296
1297/// Find the base class to decompose in a built-in decomposition of a class type.
1298/// This base class search is, unfortunately, not quite like any other that we
1299/// perform anywhere else in C++.
1300static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1301 const CXXRecordDecl *RD,
1302 CXXCastPath &BasePath) {
1303 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1304 CXXBasePath &Path) {
1305 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1306 };
1307
1308 const CXXRecordDecl *ClassWithFields = nullptr;
1309 AccessSpecifier AS = AS_public;
1310 if (RD->hasDirectFields())
1311 // [dcl.decomp]p4:
1312 // Otherwise, all of E's non-static data members shall be public direct
1313 // members of E ...
1314 ClassWithFields = RD;
1315 else {
1316 // ... or of ...
1317 CXXBasePaths Paths;
1318 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1319 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1320 // If no classes have fields, just decompose RD itself. (This will work
1321 // if and only if zero bindings were provided.)
1322 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1323 }
1324
1325 CXXBasePath *BestPath = nullptr;
1326 for (auto &P : Paths) {
1327 if (!BestPath)
1328 BestPath = &P;
1329 else if (!S.Context.hasSameType(P.back().Base->getType(),
1330 BestPath->back().Base->getType())) {
1331 // ... the same ...
1332 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1333 << false << RD << BestPath->back().Base->getType()
1334 << P.back().Base->getType();
1335 return DeclAccessPair();
1336 } else if (P.Access < BestPath->Access) {
1337 BestPath = &P;
1338 }
1339 }
1340
1341 // ... unambiguous ...
1342 QualType BaseType = BestPath->back().Base->getType();
1343 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1344 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1345 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1346 return DeclAccessPair();
1347 }
1348
1349 // ... [accessible, implied by other rules] base class of E.
1350 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1351 *BestPath, diag::err_decomp_decl_inaccessible_base);
1352 AS = BestPath->Access;
1353
1354 ClassWithFields = BaseType->getAsCXXRecordDecl();
1355 S.BuildBasePathArray(Paths, BasePath);
1356 }
1357
1358 // The above search did not check whether the selected class itself has base
1359 // classes with fields, so check that now.
1360 CXXBasePaths Paths;
1361 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1362 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1363 << (ClassWithFields == RD) << RD << ClassWithFields
1364 << Paths.front().back().Base->getType();
1365 return DeclAccessPair();
1366 }
1367
1368 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1369}
1370
1371static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1372 ValueDecl *Src, QualType DecompType,
1373 const CXXRecordDecl *OrigRD) {
1374 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1375 diag::err_incomplete_type))
1376 return true;
1377
1378 CXXCastPath BasePath;
1379 DeclAccessPair BasePair =
1380 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1381 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1382 if (!RD)
1383 return true;
1384 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1385 DecompType.getQualifiers());
1386
1387 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1388 unsigned NumFields = llvm::count_if(
1389 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1390 assert(Bindings.size() != NumFields)(static_cast <bool> (Bindings.size() != NumFields) ? void
(0) : __assert_fail ("Bindings.size() != NumFields", "clang/lib/Sema/SemaDeclCXX.cpp"
, 1390, __extension__ __PRETTY_FUNCTION__))
;
1391 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1392 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1393 << (NumFields < Bindings.size());
1394 return true;
1395 };
1396
1397 // all of E's non-static data members shall be [...] well-formed
1398 // when named as e.name in the context of the structured binding,
1399 // E shall not have an anonymous union member, ...
1400 unsigned I = 0;
1401 for (auto *FD : RD->fields()) {
1402 if (FD->isUnnamedBitfield())
1403 continue;
1404
1405 // All the non-static data members are required to be nameable, so they
1406 // must all have names.
1407 if (!FD->getDeclName()) {
1408 if (RD->isLambda()) {
1409 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1410 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1411 return true;
1412 }
1413
1414 if (FD->isAnonymousStructOrUnion()) {
1415 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1416 << DecompType << FD->getType()->isUnionType();
1417 S.Diag(FD->getLocation(), diag::note_declared_at);
1418 return true;
1419 }
1420
1421 // FIXME: Are there any other ways we could have an anonymous member?
1422 }
1423
1424 // We have a real field to bind.
1425 if (I >= Bindings.size())
1426 return DiagnoseBadNumberOfBindings();
1427 auto *B = Bindings[I++];
1428 SourceLocation Loc = B->getLocation();
1429
1430 // The field must be accessible in the context of the structured binding.
1431 // We already checked that the base class is accessible.
1432 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1433 // const_cast here.
1434 S.CheckStructuredBindingMemberAccess(
1435 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1436 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1437 BasePair.getAccess(), FD->getAccess())));
1438
1439 // Initialize the binding to Src.FD.
1440 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1441 if (E.isInvalid())
1442 return true;
1443 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1444 VK_LValue, &BasePath);
1445 if (E.isInvalid())
1446 return true;
1447 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1448 CXXScopeSpec(), FD,
1449 DeclAccessPair::make(FD, FD->getAccess()),
1450 DeclarationNameInfo(FD->getDeclName(), Loc));
1451 if (E.isInvalid())
1452 return true;
1453
1454 // If the type of the member is T, the referenced type is cv T, where cv is
1455 // the cv-qualification of the decomposition expression.
1456 //
1457 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1458 // 'const' to the type of the field.
1459 Qualifiers Q = DecompType.getQualifiers();
1460 if (FD->isMutable())
1461 Q.removeConst();
1462 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1463 }
1464
1465 if (I != Bindings.size())
1466 return DiagnoseBadNumberOfBindings();
1467
1468 return false;
1469}
1470
1471void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1472 QualType DecompType = DD->getType();
1473
1474 // If the type of the decomposition is dependent, then so is the type of
1475 // each binding.
1476 if (DecompType->isDependentType()) {
1477 for (auto *B : DD->bindings())
1478 B->setType(Context.DependentTy);
1479 return;
1480 }
1481
1482 DecompType = DecompType.getNonReferenceType();
1483 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1484
1485 // C++1z [dcl.decomp]/2:
1486 // If E is an array type [...]
1487 // As an extension, we also support decomposition of built-in complex and
1488 // vector types.
1489 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1490 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1491 DD->setInvalidDecl();
1492 return;
1493 }
1494 if (auto *VT = DecompType->getAs<VectorType>()) {
1495 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1496 DD->setInvalidDecl();
1497 return;
1498 }
1499 if (auto *CT = DecompType->getAs<ComplexType>()) {
1500 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1501 DD->setInvalidDecl();
1502 return;
1503 }
1504
1505 // C++1z [dcl.decomp]/3:
1506 // if the expression std::tuple_size<E>::value is a well-formed integral
1507 // constant expression, [...]
1508 llvm::APSInt TupleSize(32);
1509 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1510 case IsTupleLike::Error:
1511 DD->setInvalidDecl();
1512 return;
1513
1514 case IsTupleLike::TupleLike:
1515 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1516 DD->setInvalidDecl();
1517 return;
1518
1519 case IsTupleLike::NotTupleLike:
1520 break;
1521 }
1522
1523 // C++1z [dcl.dcl]/8:
1524 // [E shall be of array or non-union class type]
1525 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1526 if (!RD || RD->isUnion()) {
1527 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1528 << DD << !RD << DecompType;
1529 DD->setInvalidDecl();
1530 return;
1531 }
1532
1533 // C++1z [dcl.decomp]/4:
1534 // all of E's non-static data members shall be [...] direct members of
1535 // E or of the same unambiguous public base class of E, ...
1536 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1537 DD->setInvalidDecl();
1538}
1539
1540/// Merge the exception specifications of two variable declarations.
1541///
1542/// This is called when there's a redeclaration of a VarDecl. The function
1543/// checks if the redeclaration might have an exception specification and
1544/// validates compatibility and merges the specs if necessary.
1545void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1546 // Shortcut if exceptions are disabled.
1547 if (!getLangOpts().CXXExceptions)
1548 return;
1549
1550 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", 1551, __extension__ __PRETTY_FUNCTION__
))
1551 "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", 1551, __extension__ __PRETTY_FUNCTION__
))
;
1552
1553 QualType NewType = New->getType();
1554 QualType OldType = Old->getType();
1555
1556 // We're only interested in pointers and references to functions, as well
1557 // as pointers to member functions.
1558 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1559 NewType = R->getPointeeType();
1560 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1561 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1562 NewType = P->getPointeeType();
1563 OldType = OldType->castAs<PointerType>()->getPointeeType();
1564 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1565 NewType = M->getPointeeType();
1566 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1567 }
1568
1569 if (!NewType->isFunctionProtoType())
1570 return;
1571
1572 // There's lots of special cases for functions. For function pointers, system
1573 // libraries are hopefully not as broken so that we don't need these
1574 // workarounds.
1575 if (CheckEquivalentExceptionSpec(
1576 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1577 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1578 New->setInvalidDecl();
1579 }
1580}
1581
1582/// CheckCXXDefaultArguments - Verify that the default arguments for a
1583/// function declaration are well-formed according to C++
1584/// [dcl.fct.default].
1585void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1586 unsigned NumParams = FD->getNumParams();
1587 unsigned ParamIdx = 0;
1588
1589 // This checking doesn't make sense for explicit specializations; their
1590 // default arguments are determined by the declaration we're specializing,
1591 // not by FD.
1592 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1593 return;
1594 if (auto *FTD = FD->getDescribedFunctionTemplate())
1595 if (FTD->isMemberSpecialization())
1596 return;
1597
1598 // Find first parameter with a default argument
1599 for (; ParamIdx < NumParams; ++ParamIdx) {
1600 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1601 if (Param->hasDefaultArg())
1602 break;
1603 }
1604
1605 // C++20 [dcl.fct.default]p4:
1606 // In a given function declaration, each parameter subsequent to a parameter
1607 // with a default argument shall have a default argument supplied in this or
1608 // a previous declaration, unless the parameter was expanded from a
1609 // parameter pack, or shall be a function parameter pack.
1610 for (; ParamIdx < NumParams; ++ParamIdx) {
1611 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1612 if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1613 !(CurrentInstantiationScope &&
1614 CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1615 if (Param->isInvalidDecl())
1616 /* We already complained about this parameter. */;
1617 else if (Param->getIdentifier())
1618 Diag(Param->getLocation(),
1619 diag::err_param_default_argument_missing_name)
1620 << Param->getIdentifier();
1621 else
1622 Diag(Param->getLocation(),
1623 diag::err_param_default_argument_missing);
1624 }
1625 }
1626}
1627
1628/// Check that the given type is a literal type. Issue a diagnostic if not,
1629/// if Kind is Diagnose.
1630/// \return \c true if a problem has been found (and optionally diagnosed).
1631template <typename... Ts>
1632static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1633 SourceLocation Loc, QualType T, unsigned DiagID,
1634 Ts &&...DiagArgs) {
1635 if (T->isDependentType())
1636 return false;
1637
1638 switch (Kind) {
1639 case Sema::CheckConstexprKind::Diagnose:
1640 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1641 std::forward<Ts>(DiagArgs)...);
1642
1643 case Sema::CheckConstexprKind::CheckValid:
1644 return !T->isLiteralType(SemaRef.Context);
1645 }
1646
1647 llvm_unreachable("unknown CheckConstexprKind")::llvm::llvm_unreachable_internal("unknown CheckConstexprKind"
, "clang/lib/Sema/SemaDeclCXX.cpp", 1647)
;
1648}
1649
1650/// Determine whether a destructor cannot be constexpr due to
1651static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1652 const CXXDestructorDecl *DD,
1653 Sema::CheckConstexprKind Kind) {
1654 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1655 const CXXRecordDecl *RD =
1656 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1657 if (!RD || RD->hasConstexprDestructor())
1658 return true;
1659
1660 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1661 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1662 << static_cast<int>(DD->getConstexprKind()) << !FD
1663 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1664 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1665 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1666 }
1667 return false;
1668 };
1669
1670 const CXXRecordDecl *RD = DD->getParent();
1671 for (const CXXBaseSpecifier &B : RD->bases())
1672 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1673 return false;
1674 for (const FieldDecl *FD : RD->fields())
1675 if (!Check(FD->getLocation(), FD->getType(), FD))
1676 return false;
1677 return true;
1678}
1679
1680/// Check whether a function's parameter types are all literal types. If so,
1681/// return true. If not, produce a suitable diagnostic and return false.
1682static bool CheckConstexprParameterTypes(Sema &SemaRef,
1683 const FunctionDecl *FD,
1684 Sema::CheckConstexprKind Kind) {
1685 unsigned ArgIndex = 0;
1686 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1687 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1688 e = FT->param_type_end();
1689 i != e; ++i, ++ArgIndex) {
1690 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1691 SourceLocation ParamLoc = PD->getLocation();
1692 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1693 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1694 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1695 FD->isConsteval()))
1696 return false;
1697 }
1698 return true;
1699}
1700
1701/// Check whether a function's return type is a literal type. If so, return
1702/// true. If not, produce a suitable diagnostic and return false.
1703static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1704 Sema::CheckConstexprKind Kind) {
1705 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1706 diag::err_constexpr_non_literal_return,
1707 FD->isConsteval()))
1708 return false;
1709 return true;
1710}
1711
1712/// Get diagnostic %select index for tag kind for
1713/// record diagnostic message.
1714/// WARNING: Indexes apply to particular diagnostics only!
1715///
1716/// \returns diagnostic %select index.
1717static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1718 switch (Tag) {
1719 case TTK_Struct: return 0;
1720 case TTK_Interface: return 1;
1721 case TTK_Class: return 2;
1722 default: llvm_unreachable("Invalid tag kind for record diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for record diagnostic!"
, "clang/lib/Sema/SemaDeclCXX.cpp", 1722)
;
1723 }
1724}
1725
1726static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1727 Stmt *Body,
1728 Sema::CheckConstexprKind Kind);
1729
1730// Check whether a function declaration satisfies the requirements of a
1731// constexpr function definition or a constexpr constructor definition. If so,
1732// return true. If not, produce appropriate diagnostics (unless asked not to by
1733// Kind) and return false.
1734//
1735// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1736bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1737 CheckConstexprKind Kind) {
1738 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1739 if (MD && MD->isInstance()) {
1740 // C++11 [dcl.constexpr]p4:
1741 // The definition of a constexpr constructor shall satisfy the following
1742 // constraints:
1743 // - the class shall not have any virtual base classes;
1744 //
1745 // FIXME: This only applies to constructors and destructors, not arbitrary
1746 // member functions.
1747 const CXXRecordDecl *RD = MD->getParent();
1748 if (RD->getNumVBases()) {
1749 if (Kind == CheckConstexprKind::CheckValid)
1750 return false;
1751
1752 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1753 << isa<CXXConstructorDecl>(NewFD)
1754 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1755 for (const auto &I : RD->vbases())
1756 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1757 << I.getSourceRange();
1758 return false;
1759 }
1760 }
1761
1762 if (!isa<CXXConstructorDecl>(NewFD)) {
1763 // C++11 [dcl.constexpr]p3:
1764 // The definition of a constexpr function shall satisfy the following
1765 // constraints:
1766 // - it shall not be virtual; (removed in C++20)
1767 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1768 if (Method && Method->isVirtual()) {
1769 if (getLangOpts().CPlusPlus20) {
1770 if (Kind == CheckConstexprKind::Diagnose)
1771 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1772 } else {
1773 if (Kind == CheckConstexprKind::CheckValid)
1774 return false;
1775
1776 Method = Method->getCanonicalDecl();
1777 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1778
1779 // If it's not obvious why this function is virtual, find an overridden
1780 // function which uses the 'virtual' keyword.
1781 const CXXMethodDecl *WrittenVirtual = Method;
1782 while (!WrittenVirtual->isVirtualAsWritten())
1783 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1784 if (WrittenVirtual != Method)
1785 Diag(WrittenVirtual->getLocation(),
1786 diag::note_overridden_virtual_function);
1787 return false;
1788 }
1789 }
1790
1791 // - its return type shall be a literal type;
1792 if (!CheckConstexprReturnType(*this, NewFD, Kind))
1793 return false;
1794 }
1795
1796 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1797 // A destructor can be constexpr only if the defaulted destructor could be;
1798 // we don't need to check the members and bases if we already know they all
1799 // have constexpr destructors.
1800 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1801 if (Kind == CheckConstexprKind::CheckValid)
1802 return false;
1803 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1804 return false;
1805 }
1806 }
1807
1808 // - each of its parameter types shall be a literal type;
1809 if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1810 return false;
1811
1812 Stmt *Body = NewFD->getBody();
1813 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", 1814, __extension__ __PRETTY_FUNCTION__
))
1814 "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", 1814, __extension__ __PRETTY_FUNCTION__
))
;
1815 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1816}
1817
1818/// Check the given declaration statement is legal within a constexpr function
1819/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1820///
1821/// \return true if the body is OK (maybe only as an extension), false if we
1822/// have diagnosed a problem.
1823static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1824 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1825 Sema::CheckConstexprKind Kind) {
1826 // C++11 [dcl.constexpr]p3 and p4:
1827 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1828 // contain only
1829 for (const auto *DclIt : DS->decls()) {
1830 switch (DclIt->getKind()) {
1831 case Decl::StaticAssert:
1832 case Decl::Using:
1833 case Decl::UsingShadow:
1834 case Decl::UsingDirective:
1835 case Decl::UnresolvedUsingTypename:
1836 case Decl::UnresolvedUsingValue:
1837 case Decl::UsingEnum:
1838 // - static_assert-declarations
1839 // - using-declarations,
1840 // - using-directives,
1841 // - using-enum-declaration
1842 continue;
1843
1844 case Decl::Typedef:
1845 case Decl::TypeAlias: {
1846 // - typedef declarations and alias-declarations that do not define
1847 // classes or enumerations,
1848 const auto *TN = cast<TypedefNameDecl>(DclIt);
1849 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1850 // Don't allow variably-modified types in constexpr functions.
1851 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1852 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1853 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1854 << TL.getSourceRange() << TL.getType()
1855 << isa<CXXConstructorDecl>(Dcl);
1856 }
1857 return false;
1858 }
1859 continue;
1860 }
1861
1862 case Decl::Enum:
1863 case Decl::CXXRecord:
1864 // C++1y allows types to be defined, not just declared.
1865 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1866 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1867 SemaRef.Diag(DS->getBeginLoc(),
1868 SemaRef.getLangOpts().CPlusPlus14
1869 ? diag::warn_cxx11_compat_constexpr_type_definition
1870 : diag::ext_constexpr_type_definition)
1871 << isa<CXXConstructorDecl>(Dcl);
1872 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1873 return false;
1874 }
1875 }
1876 continue;
1877
1878 case Decl::EnumConstant:
1879 case Decl::IndirectField:
1880 case Decl::ParmVar:
1881 // These can only appear with other declarations which are banned in
1882 // C++11 and permitted in C++1y, so ignore them.
1883 continue;
1884
1885 case Decl::Var:
1886 case Decl::Decomposition: {
1887 // C++1y [dcl.constexpr]p3 allows anything except:
1888 // a definition of a variable of non-literal type or of static or
1889 // thread storage duration or [before C++2a] for which no
1890 // initialization is performed.
1891 const auto *VD = cast<VarDecl>(DclIt);
1892 if (VD->isThisDeclarationADefinition()) {
1893 if (VD->isStaticLocal()) {
1894 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1895 SemaRef.Diag(VD->getLocation(),
1896 SemaRef.getLangOpts().CPlusPlus2b
1897 ? diag::warn_cxx20_compat_constexpr_var
1898 : diag::ext_constexpr_static_var)
1899 << isa<CXXConstructorDecl>(Dcl)
1900 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1901 } else if (!SemaRef.getLangOpts().CPlusPlus2b) {
1902 return false;
1903 }
1904 }
1905 if (SemaRef.LangOpts.CPlusPlus2b) {
1906 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1907 diag::warn_cxx20_compat_constexpr_var,
1908 isa<CXXConstructorDecl>(Dcl),
1909 /*variable of non-literal type*/ 2);
1910 } else if (CheckLiteralType(
1911 SemaRef, Kind, VD->getLocation(), VD->getType(),
1912 diag::err_constexpr_local_var_non_literal_type,
1913 isa<CXXConstructorDecl>(Dcl))) {
1914 return false;
1915 }
1916 if (!VD->getType()->isDependentType() &&
1917 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1918 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1919 SemaRef.Diag(
1920 VD->getLocation(),
1921 SemaRef.getLangOpts().CPlusPlus20
1922 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1923 : diag::ext_constexpr_local_var_no_init)
1924 << isa<CXXConstructorDecl>(Dcl);
1925 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1926 return false;
1927 }
1928 continue;
1929 }
1930 }
1931 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1932 SemaRef.Diag(VD->getLocation(),
1933 SemaRef.getLangOpts().CPlusPlus14
1934 ? diag::warn_cxx11_compat_constexpr_local_var
1935 : diag::ext_constexpr_local_var)
1936 << isa<CXXConstructorDecl>(Dcl);
1937 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1938 return false;
1939 }
1940 continue;
1941 }
1942
1943 case Decl::NamespaceAlias:
1944 case Decl::Function:
1945 // These are disallowed in C++11 and permitted in C++1y. Allow them
1946 // everywhere as an extension.
1947 if (!Cxx1yLoc.isValid())
1948 Cxx1yLoc = DS->getBeginLoc();
1949 continue;
1950
1951 default:
1952 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1953 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1954 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1955 }
1956 return false;
1957 }
1958 }
1959
1960 return true;
1961}
1962
1963/// Check that the given field is initialized within a constexpr constructor.
1964///
1965/// \param Dcl The constexpr constructor being checked.
1966/// \param Field The field being checked. This may be a member of an anonymous
1967/// struct or union nested within the class being checked.
1968/// \param Inits All declarations, including anonymous struct/union members and
1969/// indirect members, for which any initialization was provided.
1970/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1971/// multiple notes for different members to the same error.
1972/// \param Kind Whether we're diagnosing a constructor as written or determining
1973/// whether the formal requirements are satisfied.
1974/// \return \c false if we're checking for validity and the constructor does
1975/// not satisfy the requirements on a constexpr constructor.
1976static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1977 const FunctionDecl *Dcl,
1978 FieldDecl *Field,
1979 llvm::SmallSet<Decl*, 16> &Inits,
1980 bool &Diagnosed,
1981 Sema::CheckConstexprKind Kind) {
1982 // In C++20 onwards, there's nothing to check for validity.
1983 if (Kind == Sema::CheckConstexprKind::CheckValid &&
1984 SemaRef.getLangOpts().CPlusPlus20)
1985 return true;
1986
1987 if (Field->isInvalidDecl())
1988 return true;
1989
1990 if (Field->isUnnamedBitfield())
1991 return true;
1992
1993 // Anonymous unions with no variant members and empty anonymous structs do not
1994 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1995 // indirect fields don't need initializing.
1996 if (Field->isAnonymousStructOrUnion() &&
1997 (Field->getType()->isUnionType()
1998 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1999 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2000 return true;
2001
2002 if (!Inits.count(Field)) {
2003 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2004 if (!Diagnosed) {
2005 SemaRef.Diag(Dcl->getLocation(),
2006 SemaRef.getLangOpts().CPlusPlus20
2007 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2008 : diag::ext_constexpr_ctor_missing_init);
2009 Diagnosed = true;
2010 }
2011 SemaRef.Diag(Field->getLocation(),
2012 diag::note_constexpr_ctor_missing_init);
2013 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2014 return false;
2015 }
2016 } else if (Field->isAnonymousStructOrUnion()) {
2017 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2018 for (auto *I : RD->fields())
2019 // If an anonymous union contains an anonymous struct of which any member
2020 // is initialized, all members must be initialized.
2021 if (!RD->isUnion() || Inits.count(I))
2022 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2023 Kind))
2024 return false;
2025 }
2026 return true;
2027}
2028
2029/// Check the provided statement is allowed in a constexpr function
2030/// definition.
2031static bool
2032CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2033 SmallVectorImpl<SourceLocation> &ReturnStmts,
2034 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2035 SourceLocation &Cxx2bLoc,
2036 Sema::CheckConstexprKind Kind) {
2037 // - its function-body shall be [...] a compound-statement that contains only
2038 switch (S->getStmtClass()) {
2039 case Stmt::NullStmtClass:
2040 // - null statements,
2041 return true;
2042
2043 case Stmt::DeclStmtClass:
2044 // - static_assert-declarations
2045 // - using-declarations,
2046 // - using-directives,
2047 // - typedef declarations and alias-declarations that do not define
2048 // classes or enumerations,
2049 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2050 return false;
2051 return true;
2052
2053 case Stmt::ReturnStmtClass:
2054 // - and exactly one return statement;
2055 if (isa<CXXConstructorDecl>(Dcl)) {
2056 // C++1y allows return statements in constexpr constructors.
2057 if (!Cxx1yLoc.isValid())
2058 Cxx1yLoc = S->getBeginLoc();
2059 return true;
2060 }
2061
2062 ReturnStmts.push_back(S->getBeginLoc());
2063 return true;
2064
2065 case Stmt::AttributedStmtClass:
2066 // Attributes on a statement don't affect its formal kind and hence don't
2067 // affect its validity in a constexpr function.
2068 return CheckConstexprFunctionStmt(
2069 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2070 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2071
2072 case Stmt::CompoundStmtClass: {
2073 // C++1y allows compound-statements.
2074 if (!Cxx1yLoc.isValid())
2075 Cxx1yLoc = S->getBeginLoc();
2076
2077 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2078 for (auto *BodyIt : CompStmt->body()) {
2079 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2080 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2081 return false;
2082 }
2083 return true;
2084 }
2085
2086 case Stmt::IfStmtClass: {
2087 // C++1y allows if-statements.
2088 if (!Cxx1yLoc.isValid())
2089 Cxx1yLoc = S->getBeginLoc();
2090
2091 IfStmt *If = cast<IfStmt>(S);
2092 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2093 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2094 return false;
2095 if (If->getElse() &&
2096 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2097 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2098 return false;
2099 return true;
2100 }
2101
2102 case Stmt::WhileStmtClass:
2103 case Stmt::DoStmtClass:
2104 case Stmt::ForStmtClass:
2105 case Stmt::CXXForRangeStmtClass:
2106 case Stmt::ContinueStmtClass:
2107 // C++1y allows all of these. We don't allow them as extensions in C++11,
2108 // because they don't make sense without variable mutation.
2109 if (!SemaRef.getLangOpts().CPlusPlus14)
2110 break;
2111 if (!Cxx1yLoc.isValid())
2112 Cxx1yLoc = S->getBeginLoc();
2113 for (Stmt *SubStmt : S->children()) {
2114 if (SubStmt &&
2115 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2116 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2117 return false;
2118 }
2119 return true;
2120
2121 case Stmt::SwitchStmtClass:
2122 case Stmt::CaseStmtClass:
2123 case Stmt::DefaultStmtClass:
2124 case Stmt::BreakStmtClass:
2125 // C++1y allows switch-statements, and since they don't need variable
2126 // mutation, we can reasonably allow them in C++11 as an extension.
2127 if (!Cxx1yLoc.isValid())
2128 Cxx1yLoc = S->getBeginLoc();
2129 for (Stmt *SubStmt : S->children()) {
2130 if (SubStmt &&
2131 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2132 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2133 return false;
2134 }
2135 return true;
2136
2137 case Stmt::LabelStmtClass:
2138 case Stmt::GotoStmtClass:
2139 if (Cxx2bLoc.isInvalid())
2140 Cxx2bLoc = S->getBeginLoc();
2141 for (Stmt *SubStmt : S->children()) {
2142 if (SubStmt &&
2143 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2144 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2145 return false;
2146 }
2147 return true;
2148
2149 case Stmt::GCCAsmStmtClass:
2150 case Stmt::MSAsmStmtClass:
2151 // C++2a allows inline assembly statements.
2152 case Stmt::CXXTryStmtClass:
2153 if (Cxx2aLoc.isInvalid())
2154 Cxx2aLoc = S->getBeginLoc();
2155 for (Stmt *SubStmt : S->children()) {
2156 if (SubStmt &&
2157 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2158 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2159 return false;
2160 }
2161 return true;
2162
2163 case Stmt::CXXCatchStmtClass:
2164 // Do not bother checking the language mode (already covered by the
2165 // try block check).
2166 if (!CheckConstexprFunctionStmt(
2167 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2168 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2169 return false;
2170 return true;
2171
2172 default:
2173 if (!isa<Expr>(S))
2174 break;
2175
2176 // C++1y allows expression-statements.
2177 if (!Cxx1yLoc.isValid())
2178 Cxx1yLoc = S->getBeginLoc();
2179 return true;
2180 }
2181
2182 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2183 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2184 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2185 }
2186 return false;
2187}
2188
2189/// Check the body for the given constexpr function declaration only contains
2190/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2191///
2192/// \return true if the body is OK, false if we have found or diagnosed a
2193/// problem.
2194static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2195 Stmt *Body,
2196 Sema::CheckConstexprKind Kind) {
2197 SmallVector<SourceLocation, 4> ReturnStmts;
2198
2199 if (isa<CXXTryStmt>(Body)) {
2200 // C++11 [dcl.constexpr]p3:
2201 // The definition of a constexpr function shall satisfy the following
2202 // constraints: [...]
2203 // - its function-body shall be = delete, = default, or a
2204 // compound-statement
2205 //
2206 // C++11 [dcl.constexpr]p4:
2207 // In the definition of a constexpr constructor, [...]
2208 // - its function-body shall not be a function-try-block;
2209 //
2210 // This restriction is lifted in C++2a, as long as inner statements also
2211 // apply the general constexpr rules.
2212 switch (Kind) {
2213 case Sema::CheckConstexprKind::CheckValid:
2214 if (!SemaRef.getLangOpts().CPlusPlus20)
2215 return false;
2216 break;
2217
2218 case Sema::CheckConstexprKind::Diagnose:
2219 SemaRef.Diag(Body->getBeginLoc(),
2220 !SemaRef.getLangOpts().CPlusPlus20
2221 ? diag::ext_constexpr_function_try_block_cxx20
2222 : diag::warn_cxx17_compat_constexpr_function_try_block)
2223 << isa<CXXConstructorDecl>(Dcl);
2224 break;
2225 }
2226 }
2227
2228 // - its function-body shall be [...] a compound-statement that contains only
2229 // [... list of cases ...]
2230 //
2231 // Note that walking the children here is enough to properly check for
2232 // CompoundStmt and CXXTryStmt body.
2233 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2234 for (Stmt *SubStmt : Body->children()) {
2235 if (SubStmt &&
2236 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2237 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2238 return false;
2239 }
2240
2241 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2242 // If this is only valid as an extension, report that we don't satisfy the
2243 // constraints of the current language.
2244 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2b) ||
2245 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2246 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2247 return false;
2248 } else if (Cxx2bLoc.isValid()) {
2249 SemaRef.Diag(Cxx2bLoc,
2250 SemaRef.getLangOpts().CPlusPlus2b
2251 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2252 : diag::ext_constexpr_body_invalid_stmt_cxx2b)
2253 << isa<CXXConstructorDecl>(Dcl);
2254 } else if (Cxx2aLoc.isValid()) {
2255 SemaRef.Diag(Cxx2aLoc,
2256 SemaRef.getLangOpts().CPlusPlus20
2257 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2258 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2259 << isa<CXXConstructorDecl>(Dcl);
2260 } else if (Cxx1yLoc.isValid()) {
2261 SemaRef.Diag(Cxx1yLoc,
2262 SemaRef.getLangOpts().CPlusPlus14
2263 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2264 : diag::ext_constexpr_body_invalid_stmt)
2265 << isa<CXXConstructorDecl>(Dcl);
2266 }
2267
2268 if (const CXXConstructorDecl *Constructor
2269 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2270 const CXXRecordDecl *RD = Constructor->getParent();
2271 // DR1359:
2272 // - every non-variant non-static data member and base class sub-object
2273 // shall be initialized;
2274 // DR1460:
2275 // - if the class is a union having variant members, exactly one of them
2276 // shall be initialized;
2277 if (RD->isUnion()) {
2278 if (Constructor->getNumCtorInitializers() == 0 &&
2279 RD->hasVariantMembers()) {
2280 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2281 SemaRef.Diag(
2282 Dcl->getLocation(),
2283 SemaRef.getLangOpts().CPlusPlus20
2284 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2285 : diag::ext_constexpr_union_ctor_no_init);
2286 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2287 return false;
2288 }
2289 }
2290 } else if (!Constructor->isDependentContext() &&
2291 !Constructor->isDelegatingConstructor()) {
2292 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", 2292, __extension__ __PRETTY_FUNCTION__
))
;
2293
2294 // Skip detailed checking if we have enough initializers, and we would
2295 // allow at most one initializer per member.
2296 bool AnyAnonStructUnionMembers = false;
2297 unsigned Fields = 0;
2298 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2299 E = RD->field_end(); I != E; ++I, ++Fields) {
2300 if (I->isAnonymousStructOrUnion()) {
2301 AnyAnonStructUnionMembers = true;
2302 break;
2303 }
2304 }
2305 // DR1460:
2306 // - if the class is a union-like class, but is not a union, for each of
2307 // its anonymous union members having variant members, exactly one of
2308 // them shall be initialized;
2309 if (AnyAnonStructUnionMembers ||
2310 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2311 // Check initialization of non-static data members. Base classes are
2312 // always initialized so do not need to be checked. Dependent bases
2313 // might not have initializers in the member initializer list.
2314 llvm::SmallSet<Decl*, 16> Inits;
2315 for (const auto *I: Constructor->inits()) {
2316 if (FieldDecl *FD = I->getMember())
2317 Inits.insert(FD);
2318 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2319 Inits.insert(ID->chain_begin(), ID->chain_end());
2320 }
2321
2322 bool Diagnosed = false;
2323 for (auto *I : RD->fields())
2324 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2325 Kind))
2326 return false;
2327 }
2328 }
2329 } else {
2330 if (ReturnStmts.empty()) {
2331 // C++1y doesn't require constexpr functions to contain a 'return'
2332 // statement. We still do, unless the return type might be void, because
2333 // otherwise if there's no return statement, the function cannot
2334 // be used in a core constant expression.
2335 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2336 (Dcl->getReturnType()->isVoidType() ||
2337 Dcl->getReturnType()->isDependentType());
2338 switch (Kind) {
2339 case Sema::CheckConstexprKind::Diagnose:
2340 SemaRef.Diag(Dcl->getLocation(),
2341 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2342 : diag::err_constexpr_body_no_return)
2343 << Dcl->isConsteval();
2344 if (!OK)
2345 return false;
2346 break;
2347
2348 case Sema::CheckConstexprKind::CheckValid:
2349 // The formal requirements don't include this rule in C++14, even
2350 // though the "must be able to produce a constant expression" rules
2351 // still imply it in some cases.
2352 if (!SemaRef.getLangOpts().CPlusPlus14)
2353 return false;
2354 break;
2355 }
2356 } else if (ReturnStmts.size() > 1) {
2357 switch (Kind) {
2358 case Sema::CheckConstexprKind::Diagnose:
2359 SemaRef.Diag(
2360 ReturnStmts.back(),
2361 SemaRef.getLangOpts().CPlusPlus14
2362 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2363 : diag::ext_constexpr_body_multiple_return);
2364 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2365 SemaRef.Diag(ReturnStmts[I],
2366 diag::note_constexpr_body_previous_return);
2367 break;
2368
2369 case Sema::CheckConstexprKind::CheckValid:
2370 if (!SemaRef.getLangOpts().CPlusPlus14)
2371 return false;
2372 break;
2373 }
2374 }
2375 }
2376
2377 // C++11 [dcl.constexpr]p5:
2378 // if no function argument values exist such that the function invocation
2379 // substitution would produce a constant expression, the program is
2380 // ill-formed; no diagnostic required.
2381 // C++11 [dcl.constexpr]p3:
2382 // - every constructor call and implicit conversion used in initializing the
2383 // return value shall be one of those allowed in a constant expression.
2384 // C++11 [dcl.constexpr]p4:
2385 // - every constructor involved in initializing non-static data members and
2386 // base class sub-objects shall be a constexpr constructor.
2387 //
2388 // Note that this rule is distinct from the "requirements for a constexpr
2389 // function", so is not checked in CheckValid mode.
2390 SmallVector<PartialDiagnosticAt, 8> Diags;
2391 if (Kind == Sema::CheckConstexprKind::Diagnose &&
2392 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2393 SemaRef.Diag(Dcl->getLocation(),
2394 diag::ext_constexpr_function_never_constant_expr)
2395 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2396 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2397 SemaRef.Diag(Diags[I].first, Diags[I].second);
2398 // Don't return false here: we allow this for compatibility in
2399 // system headers.
2400 }
2401
2402 return true;
2403}
2404
2405/// Get the class that is directly named by the current context. This is the
2406/// class for which an unqualified-id in this scope could name a constructor
2407/// or destructor.
2408///
2409/// If the scope specifier denotes a class, this will be that class.
2410/// If the scope specifier is empty, this will be the class whose
2411/// member-specification we are currently within. Otherwise, there
2412/// is no such class.
2413CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2414 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", 2414, __extension__ __PRETTY_FUNCTION__
))
;
2415
2416 if (SS && SS->isInvalid())
2417 return nullptr;
2418
2419 if (SS && SS->isNotEmpty()) {
2420 DeclContext *DC = computeDeclContext(*SS, true);
2421 return dyn_cast_or_null<CXXRecordDecl>(DC);
2422 }
2423
2424 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2425}
2426
2427/// isCurrentClassName - Determine whether the identifier II is the
2428/// name of the class type currently being defined. In the case of
2429/// nested classes, this will only return true if II is the name of
2430/// the innermost class.
2431bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2432 const CXXScopeSpec *SS) {
2433 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2434 return CurDecl && &II == CurDecl->getIdentifier();
2435}
2436
2437/// Determine whether the identifier II is a typo for the name of
2438/// the class type currently being defined. If so, update it to the identifier
2439/// that should have been used.
2440bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2441 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", 2441, __extension__ __PRETTY_FUNCTION__
))
;
2442
2443 if (!getLangOpts().SpellChecking)
2444 return false;
2445
2446 CXXRecordDecl *CurDecl;
2447 if (SS && SS->isSet() && !SS->isInvalid()) {
2448 DeclContext *DC = computeDeclContext(*SS, true);
2449 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2450 } else
2451 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2452
2453 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2454 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2455 < II->getLength()) {
2456 II = CurDecl->getIdentifier();
2457 return true;
2458 }
2459
2460 return false;
2461}
2462
2463/// Determine whether the given class is a base class of the given
2464/// class, including looking at dependent bases.
2465static bool findCircularInheritance(const CXXRecordDecl *Class,
2466 const CXXRecordDecl *Current) {
2467 SmallVector<const CXXRecordDecl*, 8> Queue;
2468
2469 Class = Class->getCanonicalDecl();
2470 while (true) {
2471 for (const auto &I : Current->bases()) {
2472 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2473 if (!Base)
2474 continue;
2475
2476 Base = Base->getDefinition();
2477 if (!Base)
2478 continue;
2479
2480 if (Base->getCanonicalDecl() == Class)
2481 return true;
2482
2483 Queue.push_back(Base);
2484 }
2485
2486 if (Queue.empty())
2487 return false;
2488
2489 Current = Queue.pop_back_val();
2490 }
2491
2492 return false;
2493}
2494
2495/// Check the validity of a C++ base class specifier.
2496///
2497/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2498/// and returns NULL otherwise.
2499CXXBaseSpecifier *
2500Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2501 SourceRange SpecifierRange,
2502 bool Virtual, AccessSpecifier Access,
2503 TypeSourceInfo *TInfo,
2504 SourceLocation EllipsisLoc) {
2505 // In HLSL, unspecified class access is public rather than private.
2506 if (getLangOpts().HLSL && Class->getTagKind() == TTK_Class &&
2507 Access == AS_none)
2508 Access = AS_public;
2509
2510 QualType BaseType = TInfo->getType();
2511 if (BaseType->containsErrors()) {
2512 // Already emitted a diagnostic when parsing the error type.
2513 return nullptr;
2514 }
2515 // C++ [class.union]p1:
2516 // A union shall not have base classes.
2517 if (Class->isUnion()) {
2518 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2519 << SpecifierRange;
2520 return nullptr;
2521 }
2522
2523 if (EllipsisLoc.isValid() &&
2524 !TInfo->getType()->containsUnexpandedParameterPack()) {
2525 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2526 << TInfo->getTypeLoc().getSourceRange();
2527 EllipsisLoc = SourceLocation();
2528 }
2529
2530 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2531
2532 if (BaseType->isDependentType()) {
2533 // Make sure that we don't have circular inheritance among our dependent
2534 // bases. For non-dependent bases, the check for completeness below handles
2535 // this.
2536 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2537 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2538 ((BaseDecl = BaseDecl->getDefinition()) &&
2539 findCircularInheritance(Class, BaseDecl))) {
2540 Diag(BaseLoc, diag::err_circular_inheritance)
2541 << BaseType << Context.getTypeDeclType(Class);
2542
2543 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2544 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2545 << BaseType;
2546
2547 return nullptr;
2548 }
2549 }
2550
2551 // Make sure that we don't make an ill-formed AST where the type of the
2552 // Class is non-dependent and its attached base class specifier is an
2553 // dependent type, which violates invariants in many clang code paths (e.g.
2554 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2555 // explicitly mark the Class decl invalid. The diagnostic was already
2556 // emitted.
2557 if (!Class->getTypeForDecl()->isDependentType())
2558 Class->setInvalidDecl();
2559 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2560 Class->getTagKind() == TTK_Class,
2561 Access, TInfo, EllipsisLoc);
2562 }
2563
2564 // Base specifiers must be record types.
2565 if (!BaseType->isRecordType()) {
2566 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2567 return nullptr;
2568 }
2569
2570 // C++ [class.union]p1:
2571 // A union shall not be used as a base class.
2572 if (BaseType->isUnionType()) {
2573 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2574 return nullptr;
2575 }
2576
2577 // For the MS ABI, propagate DLL attributes to base class templates.
2578 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2579 if (Attr *ClassAttr = getDLLAttr(Class)) {
2580 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2581 BaseType->getAsCXXRecordDecl())) {
2582 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2583 BaseLoc);
2584 }
2585 }
2586 }
2587
2588 // C++ [class.derived]p2:
2589 // The class-name in a base-specifier shall not be an incompletely
2590 // defined class.
2591 if (RequireCompleteType(BaseLoc, BaseType,
2592 diag::err_incomplete_base_class, SpecifierRange)) {
2593 Class->setInvalidDecl();
2594 return nullptr;
2595 }
2596
2597 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2598 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2599 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", 2599, __extension__ __PRETTY_FUNCTION__
))
;
2600 BaseDecl = BaseDecl->getDefinition();
2601 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", 2601, __extension__ __PRETTY_FUNCTION__
))
;
2602 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2603 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", 2603, __extension__ __PRETTY_FUNCTION__
))
;
2604
2605 // Microsoft docs say:
2606 // "If a base-class has a code_seg attribute, derived classes must have the
2607 // same attribute."
2608 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2609 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2610 if ((DerivedCSA || BaseCSA) &&
2611 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2612 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2613 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2614 << CXXBaseDecl;
2615 return nullptr;
2616 }
2617
2618 // A class which contains a flexible array member is not suitable for use as a
2619 // base class:
2620 // - If the layout determines that a base comes before another base,
2621 // the flexible array member would index into the subsequent base.
2622 // - If the layout determines that base comes before the derived class,
2623 // the flexible array member would index into the derived class.
2624 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2625 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2626 << CXXBaseDecl->getDeclName();
2627 return nullptr;
2628 }
2629
2630 // C++ [class]p3:
2631 // If a class is marked final and it appears as a base-type-specifier in
2632 // base-clause, the program is ill-formed.
2633 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2634 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2635 << CXXBaseDecl->getDeclName()
2636 << FA->isSpelledAsSealed();
2637 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2638 << CXXBaseDecl->getDeclName() << FA->getRange();
2639 return nullptr;
2640 }
2641
2642 if (BaseDecl->isInvalidDecl())
2643 Class->setInvalidDecl();
2644
2645 // Create the base specifier.
2646 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2647 Class->getTagKind() == TTK_Class,
2648 Access, TInfo, EllipsisLoc);
2649}
2650
2651/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2652/// one entry in the base class list of a class specifier, for
2653/// example:
2654/// class foo : public bar, virtual private baz {
2655/// 'public bar' and 'virtual private baz' are each base-specifiers.
2656BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2657 const ParsedAttributesView &Attributes,
2658 bool Virtual, AccessSpecifier Access,
2659 ParsedType basetype, SourceLocation BaseLoc,
2660 SourceLocation EllipsisLoc) {
2661 if (!classdecl)
2662 return true;
2663
2664 AdjustDeclIfTemplate(classdecl);
2665 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2666 if (!Class)
2667 return true;
2668
2669 // We haven't yet attached the base specifiers.
2670 Class->setIsParsingBaseSpecifiers();
2671
2672 // We do not support any C++11 attributes on base-specifiers yet.
2673 // Diagnose any attributes we see.
2674 for (const ParsedAttr &AL : Attributes) {
2675 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2676 continue;
2677 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2678 ? (unsigned)diag::warn_unknown_attribute_ignored
2679 : (unsigned)diag::err_base_specifier_attribute)
2680 << AL << AL.getRange();
2681 }
2682
2683 TypeSourceInfo *TInfo = nullptr;
2684 GetTypeFromParser(basetype, &TInfo);
2685
2686 if (EllipsisLoc.isInvalid() &&
2687 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2688 UPPC_BaseType))
2689 return true;
2690
2691 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2692 Virtual, Access, TInfo,
2693 EllipsisLoc))
2694 return BaseSpec;
2695 else
2696 Class->setInvalidDecl();
2697
2698 return true;
2699}
2700
2701/// Use small set to collect indirect bases. As this is only used
2702/// locally, there's no need to abstract the small size parameter.
2703typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2704
2705/// Recursively add the bases of Type. Don't add Type itself.
2706static void
2707NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2708 const QualType &Type)
2709{
2710 // Even though the incoming type is a base, it might not be
2711 // a class -- it could be a template parm, for instance.
2712 if (auto Rec = Type->getAs<RecordType>()) {
2713 auto Decl = Rec->getAsCXXRecordDecl();
2714
2715 // Iterate over its bases.
2716 for (const auto &BaseSpec : Decl->bases()) {
2717 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2718 .getUnqualifiedType();
2719 if (Set.insert(Base).second)
2720 // If we've not already seen it, recurse.
2721 NoteIndirectBases(Context, Set, Base);
2722 }
2723 }
2724}
2725
2726/// Performs the actual work of attaching the given base class
2727/// specifiers to a C++ class.
2728bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2729 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2730 if (Bases.empty())
2731 return false;
2732
2733 // Used to keep track of which base types we have already seen, so
2734 // that we can properly diagnose redundant direct base types. Note
2735 // that the key is always the unqualified canonical type of the base
2736 // class.
2737 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2738
2739 // Used to track indirect bases so we can see if a direct base is
2740 // ambiguous.
2741 IndirectBaseSet IndirectBaseTypes;
2742
2743 // Copy non-redundant base specifiers into permanent storage.
2744 unsigned NumGoodBases = 0;
2745 bool Invalid = false;
2746 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2747 QualType NewBaseType
2748 = Context.getCanonicalType(Bases[idx]->getType());
2749 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2750
2751 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2752 if (KnownBase) {
2753 // C++ [class.mi]p3:
2754 // A class shall not be specified as a direct base class of a
2755 // derived class more than once.
2756 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2757 << KnownBase->getType() << Bases[idx]->getSourceRange();
2758
2759 // Delete the duplicate base class specifier; we're going to
2760 // overwrite its pointer later.
2761 Context.Deallocate(Bases[idx]);
2762
2763 Invalid = true;
2764 } else {
2765 // Okay, add this new base class.
2766 KnownBase = Bases[idx];
2767 Bases[NumGoodBases++] = Bases[idx];
2768
2769 if (NewBaseType->isDependentType())
2770 continue;
2771 // Note this base's direct & indirect bases, if there could be ambiguity.
2772 if (Bases.size() > 1)
2773 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2774
2775 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2776 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2777 if (Class->isInterface() &&
2778 (!RD->isInterfaceLike() ||
2779 KnownBase->getAccessSpecifier() != AS_public)) {
2780 // The Microsoft extension __interface does not permit bases that
2781 // are not themselves public interfaces.
2782 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2783 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2784 << RD->getSourceRange();
2785 Invalid = true;
2786 }
2787 if (RD->hasAttr<WeakAttr>())
2788 Class->addAttr(WeakAttr::CreateImplicit(Context));
2789 }
2790 }
2791 }
2792
2793 // Attach the remaining base class specifiers to the derived class.
2794 Class->setBases(Bases.data(), NumGoodBases);
2795
2796 // Check that the only base classes that are duplicate are virtual.
2797 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2798 // Check whether this direct base is inaccessible due to ambiguity.
2799 QualType BaseType = Bases[idx]->getType();
2800
2801 // Skip all dependent types in templates being used as base specifiers.
2802 // Checks below assume that the base specifier is a CXXRecord.
2803 if (BaseType->isDependentType())
2804 continue;
2805
2806 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2807 .getUnqualifiedType();
2808
2809 if (IndirectBaseTypes.count(CanonicalBase)) {
2810 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2811 /*DetectVirtual=*/true);
2812 bool found
2813 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2814 assert(found)(static_cast <bool> (found) ? void (0) : __assert_fail (
"found", "clang/lib/Sema/SemaDeclCXX.cpp", 2814, __extension__
__PRETTY_FUNCTION__))
;
2815 (void)found;
2816
2817 if (Paths.isAmbiguous(CanonicalBase))
2818 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2819 << BaseType << getAmbiguousPathsDisplayString(Paths)
2820 << Bases[idx]->getSourceRange();
2821 else
2822 assert(Bases[idx]->isVirtual())(static_cast <bool> (Bases[idx]->isVirtual()) ? void
(0) : __assert_fail ("Bases[idx]->isVirtual()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 2822, __extension__ __PRETTY_FUNCTION__))
;
2823 }
2824
2825 // Delete the base class specifier, since its data has been copied
2826 // into the CXXRecordDecl.
2827 Context.Deallocate(Bases[idx]);
2828 }
2829
2830 return Invalid;
2831}
2832
2833/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2834/// class, after checking whether there are any duplicate base
2835/// classes.
2836void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2837 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2838 if (!ClassDecl || Bases.empty())
2839 return;
2840
2841 AdjustDeclIfTemplate(ClassDecl);
2842 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2843}
2844
2845/// Determine whether the type \p Derived is a C++ class that is
2846/// derived from the type \p Base.
2847bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2848 if (!getLangOpts().CPlusPlus)
2849 return false;
2850
2851 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2852 if (!DerivedRD)
2853 return false;
2854
2855 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2856 if (!BaseRD)
2857 return false;
2858
2859 // If either the base or the derived type is invalid, don't try to
2860 // check whether one is derived from the other.
2861 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2862 return false;
2863
2864 // FIXME: In a modules build, do we need the entire path to be visible for us
2865 // to be able to use the inheritance relationship?
2866 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2867 return false;
2868
2869 return DerivedRD->isDerivedFrom(BaseRD);
2870}
2871
2872/// Determine whether the type \p Derived is a C++ class that is
2873/// derived from the type \p Base.
2874bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2875 CXXBasePaths &Paths) {
2876 if (!getLangOpts().CPlusPlus)
2877 return false;
2878
2879 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2880 if (!DerivedRD)
2881 return false;
2882
2883 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2884 if (!BaseRD)
2885 return false;
2886
2887 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2888 return false;
2889
2890 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2891}
2892
2893static void BuildBasePathArray(const CXXBasePath &Path,
2894 CXXCastPath &BasePathArray) {
2895 // We first go backward and check if we have a virtual base.
2896 // FIXME: It would be better if CXXBasePath had the base specifier for
2897 // the nearest virtual base.
2898 unsigned Start = 0;
2899 for (unsigned I = Path.size(); I != 0; --I) {
2900 if (Path[I - 1].Base->isVirtual()) {
2901 Start = I - 1;
2902 break;
2903 }
2904 }
2905
2906 // Now add all bases.
2907 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2908 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2909}
2910
2911
2912void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2913 CXXCastPath &BasePathArray) {
2914 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", 2914, __extension__ __PRETTY_FUNCTION__
))
;
2915 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", 2915, __extension__ __PRETTY_FUNCTION__
))
;
2916 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2917}
2918/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2919/// conversion (where Derived and Base are class types) is
2920/// well-formed, meaning that the conversion is unambiguous (and
2921/// that all of the base classes are accessible). Returns true
2922/// and emits a diagnostic if the code is ill-formed, returns false
2923/// otherwise. Loc is the location where this routine should point to
2924/// if there is an error, and Range is the source range to highlight
2925/// if there is an error.
2926///
2927/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2928/// diagnostic for the respective type of error will be suppressed, but the
2929/// check for ill-formed code will still be performed.
2930bool
2931Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2932 unsigned InaccessibleBaseID,
2933 unsigned AmbiguousBaseConvID,
2934 SourceLocation Loc, SourceRange Range,
2935 DeclarationName Name,
2936 CXXCastPath *BasePath,
2937 bool IgnoreAccess) {
2938 // First, determine whether the path from Derived to Base is
2939 // ambiguous. This is slightly more expensive than checking whether
2940 // the Derived to Base conversion exists, because here we need to
2941 // explore multiple paths to determine if there is an ambiguity.
2942 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2943 /*DetectVirtual=*/false);
2944 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2945 if (!DerivationOkay)
2946 return true;
2947
2948 const CXXBasePath *Path = nullptr;
2949 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2950 Path = &Paths.front();
2951
2952 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2953 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2954 // user to access such bases.
2955 if (!Path && getLangOpts().MSVCCompat) {
2956 for (const CXXBasePath &PossiblePath : Paths) {
2957 if (PossiblePath.size() == 1) {
2958 Path = &PossiblePath;
2959 if (AmbiguousBaseConvID)
2960 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2961 << Base << Derived << Range;
2962 break;
2963 }
2964 }
2965 }
2966
2967 if (Path) {
2968 if (!IgnoreAccess) {
2969 // Check that the base class can be accessed.
2970 switch (
2971 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2972 case AR_inaccessible:
2973 return true;
2974 case AR_accessible:
2975 case AR_dependent:
2976 case AR_delayed:
2977 break;
2978 }
2979 }
2980
2981 // Build a base path if necessary.
2982 if (BasePath)
2983 ::BuildBasePathArray(*Path, *BasePath);
2984 return false;
2985 }
2986
2987 if (AmbiguousBaseConvID) {
2988 // We know that the derived-to-base conversion is ambiguous, and
2989 // we're going to produce a diagnostic. Perform the derived-to-base
2990 // search just one more time to compute all of the possible paths so
2991 // that we can print them out. This is more expensive than any of
2992 // the previous derived-to-base checks we've done, but at this point
2993 // performance isn't as much of an issue.
2994 Paths.clear();
2995 Paths.setRecordingPaths(true);
2996 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2997 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", 2997, __extension__ __PRETTY_FUNCTION__
))
;
2998 (void)StillOkay;
2999
3000 // Build up a textual representation of the ambiguous paths, e.g.,
3001 // D -> B -> A, that will be used to illustrate the ambiguous
3002 // conversions in the diagnostic. We only print one of the paths
3003 // to each base class subobject.
3004 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3005
3006 Diag(Loc, AmbiguousBaseConvID)
3007 << Derived << Base << PathDisplayStr << Range << Name;
3008 }
3009 return true;
3010}
3011
3012bool
3013Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3014 SourceLocation Loc, SourceRange Range,
3015 CXXCastPath *BasePath,
3016 bool IgnoreAccess) {
3017 return CheckDerivedToBaseConversion(
3018 Derived, Base, diag::err_upcast_to_inaccessible_base,
3019 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3020 BasePath, IgnoreAccess);
3021}
3022
3023
3024/// Builds a string representing ambiguous paths from a
3025/// specific derived class to different subobjects of the same base
3026/// class.
3027///
3028/// This function builds a string that can be used in error messages
3029/// to show the different paths that one can take through the
3030/// inheritance hierarchy to go from the derived class to different
3031/// subobjects of a base class. The result looks something like this:
3032/// @code
3033/// struct D -> struct B -> struct A
3034/// struct D -> struct C -> struct A
3035/// @endcode
3036std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3037 std::string PathDisplayStr;
3038 std::set<unsigned> DisplayedPaths;
3039 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3040 Path != Paths.end(); ++Path) {
3041 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3042 // We haven't displayed a path to this particular base
3043 // class subobject yet.
3044 PathDisplayStr += "\n ";
3045 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3046 for (CXXBasePath::const_iterator Element = Path->begin();
3047 Element != Path->end(); ++Element)
3048 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3049 }
3050 }
3051
3052 return PathDisplayStr;
3053}
3054
3055//===----------------------------------------------------------------------===//
3056// C++ class member Handling
3057//===----------------------------------------------------------------------===//
3058
3059/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3060bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3061 SourceLocation ColonLoc,
3062 const ParsedAttributesView &Attrs) {
3063 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", 3063, __extension__ __PRETTY_FUNCTION__
))
;
3064 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3065 ASLoc, ColonLoc);
3066 CurContext->addHiddenDecl(ASDecl);
3067 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3068}
3069
3070/// CheckOverrideControl - Check C++11 override control semantics.
3071void Sema::CheckOverrideControl(NamedDecl *D) {
3072 if (D->isInvalidDecl())
3073 return;
3074
3075 // We only care about "override" and "final" declarations.
3076 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3077 return;
3078
3079 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3080
3081 // We can't check dependent instance methods.
3082 if (MD && MD->isInstance() &&
3083 (MD->getParent()->hasAnyDependentBases() ||
3084 MD->getType()->isDependentType()))
3085 return;
3086
3087 if (MD && !MD->isVirtual()) {
3088 // If we have a non-virtual method, check if if hides a virtual method.
3089 // (In that case, it's most likely the method has the wrong type.)
3090 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3091 FindHiddenVirtualMethods(MD, OverloadedMethods);
3092
3093 if (!OverloadedMethods.empty()) {
3094 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3095 Diag(OA->getLocation(),
3096 diag::override_keyword_hides_virtual_member_function)
3097 << "override" << (OverloadedMethods.size() > 1);
3098 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3099 Diag(FA->getLocation(),
3100 diag::override_keyword_hides_virtual_member_function)
3101 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3102 << (OverloadedMethods.size() > 1);
3103 }
3104 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3105 MD->setInvalidDecl();
3106 return;
3107 }
3108 // Fall through into the general case diagnostic.
3109 // FIXME: We might want to attempt typo correction here.
3110 }
3111
3112 if (!MD || !MD->isVirtual()) {
3113 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3114 Diag(OA->getLocation(),
3115 diag::override_keyword_only_allowed_on_virtual_member_functions)
3116 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3117 D->dropAttr<OverrideAttr>();
3118 }
3119 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3120 Diag(FA->getLocation(),
3121 diag::override_keyword_only_allowed_on_virtual_member_functions)
3122 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3123 << FixItHint::CreateRemoval(FA->getLocation());
3124 D->dropAttr<FinalAttr>();
3125 }
3126 return;
3127 }
3128
3129 // C++11 [class.virtual]p5:
3130 // If a function is marked with the virt-specifier override and
3131 // does not override a member function of a base class, the program is
3132 // ill-formed.
3133 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3134 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3135 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3136 << MD->getDeclName();
3137}
3138
3139void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3140 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3141 return;
3142 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3143 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3144 return;
3145
3146 SourceLocation Loc = MD->getLocation();
3147 SourceLocation SpellingLoc = Loc;
3148 if (getSourceManager().isMacroArgExpansion(Loc))
3149 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3150 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3151 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3152 return;
3153
3154 if (MD->size_overridden_methods() > 0) {
3155 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3156 unsigned DiagID =
3157 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3158 ? DiagInconsistent
3159 : DiagSuggest;
3160 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3161 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3162 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3163 };
3164 if (isa<CXXDestructorDecl>(MD))
3165 EmitDiag(
3166 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3167 diag::warn_suggest_destructor_marked_not_override_overriding);
3168 else
3169 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3170 diag::warn_suggest_function_marked_not_override_overriding);
3171 }
3172}
3173
3174/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3175/// function overrides a virtual member function marked 'final', according to
3176/// C++11 [class.virtual]p4.
3177bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3178 const CXXMethodDecl *Old) {
3179 FinalAttr *FA = Old->getAttr<FinalAttr>();
3180 if (!FA)
3181 return false;
3182
3183 Diag(New->getLocation(), diag::err_final_function_overridden)
3184 << New->getDeclName()
3185 << FA->isSpelledAsSealed();
3186 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3187 return true;
3188}
3189
3190static bool InitializationHasSideEffects(const FieldDecl &FD) {
3191 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3192 // FIXME: Destruction of ObjC lifetime types has side-effects.
3193 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3194 return !RD->isCompleteDefinition() ||
3195 !RD->hasTrivialDefaultConstructor() ||
3196 !RD->hasTrivialDestructor();
3197 return false;
3198}
3199
3200static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3201 ParsedAttributesView::const_iterator Itr =
3202 llvm::find_if(list, [](const ParsedAttr &AL) {
3203 return AL.isDeclspecPropertyAttribute();
3204 });
3205 if (Itr != list.end())
3206 return &*Itr;
3207 return nullptr;
3208}
3209
3210// Check if there is a field shadowing.
3211void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3212 DeclarationName FieldName,
3213 const CXXRecordDecl *RD,
3214 bool DeclIsField) {
3215 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3216 return;
3217
3218 // To record a shadowed field in a base
3219 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3220 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3221 CXXBasePath &Path) {
3222 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3223 // Record an ambiguous path directly
3224 if (Bases.find(Base) != Bases.end())
3225 return true;
3226 for (const auto Field : Base->lookup(FieldName)) {
3227 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3228 Field->getAccess() != AS_private) {
3229 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", 3229, __extension__ __PRETTY_FUNCTION__
))
;
3230 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", 3230, __extension__ __PRETTY_FUNCTION__
))
;
3231 Bases[Base] = Field;
3232 return true;
3233 }
3234 }
3235 return false;
3236 };
3237
3238 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3239 /*DetectVirtual=*/true);
3240 if (!RD->lookupInBases(FieldShadowed, Paths))
3241 return;
3242
3243 for (const auto &P : Paths) {
3244 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3245 auto It = Bases.find(Base);
3246 // Skip duplicated bases
3247 if (It == Bases.end())
3248 continue;
3249 auto BaseField = It->second;
3250 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", 3250, __extension__ __PRETTY_FUNCTION__
))
;
3251 if (AS_none !=
3252 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3253 Diag(Loc, diag::warn_shadow_field)
3254 << FieldName << RD << Base << DeclIsField;
3255 Diag(BaseField->getLocation(), diag::note_shadow_field);
3256 Bases.erase(It);
3257 }
3258 }
3259}
3260
3261/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3262/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3263/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3264/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3265/// present (but parsing it has been deferred).
3266NamedDecl *
3267Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3268 MultiTemplateParamsArg TemplateParameterLists,
3269 Expr *BW, const VirtSpecifiers &VS,
3270 InClassInitStyle InitStyle) {
3271 const DeclSpec &DS = D.getDeclSpec();
3272 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3273 DeclarationName Name = NameInfo.getName();
3274 SourceLocation Loc = NameInfo.getLoc();
3275
3276 // For anonymous bitfields, the location should point to the type.
3277 if (Loc.isInvalid())
3278 Loc = D.getBeginLoc();
3279
3280 Expr *BitWidth = static_cast<Expr*>(BW);
3281
3282 assert(isa<CXXRecordDecl>(CurContext))(static_cast <bool> (isa<CXXRecordDecl>(CurContext
)) ? void (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)"
, "clang/lib/Sema/SemaDeclCXX.cpp", 3282, __extension__ __PRETTY_FUNCTION__
))
;
3283 assert(!DS.isFriendSpecified())(static_cast <bool> (!DS.isFriendSpecified()) ? void (0
) : __assert_fail ("!DS.isFriendSpecified()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 3283, __extension__ __PRETTY_FUNCTION__))
;
3284
3285 bool isFunc = D.isDeclarationOfFunction();
3286 const ParsedAttr *MSPropertyAttr =
3287 getMSPropertyAttr(D.getDeclSpec().getAttributes());
3288
3289 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3290 // The Microsoft extension __interface only permits public member functions
3291 // and prohibits constructors, destructors, operators, non-public member
3292 // functions, static methods and data members.
3293 unsigned InvalidDecl;
3294 bool ShowDeclName = true;
3295 if (!isFunc &&
3296 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3297 InvalidDecl = 0;
3298 else if (!isFunc)
3299 InvalidDecl = 1;
3300 else if (AS != AS_public)
3301 InvalidDecl = 2;
3302 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3303 InvalidDecl = 3;
3304 else switch (Name.getNameKind()) {
3305 case DeclarationName::CXXConstructorName:
3306 InvalidDecl = 4;
3307 ShowDeclName = false;
3308 break;
3309
3310 case DeclarationName::CXXDestructorName:
3311 InvalidDecl = 5;
3312 ShowDeclName = false;
3313 break;
3314
3315 case DeclarationName::CXXOperatorName:
3316 case DeclarationName::CXXConversionFunctionName:
3317 InvalidDecl = 6;
3318 break;
3319
3320 default:
3321 InvalidDecl = 0;
3322 break;
3323 }
3324
3325 if (InvalidDecl) {
3326 if (ShowDeclName)
3327 Diag(Loc, diag::err_invalid_member_in_interface)
3328 << (InvalidDecl-1) << Name;
3329 else
3330 Diag(Loc, diag::err_invalid_member_in_interface)
3331 << (InvalidDecl-1) << "";
3332 return nullptr;
3333 }
3334 }
3335
3336 // C++ 9.2p6: A member shall not be declared to have automatic storage
3337 // duration (auto, register) or with the extern storage-class-specifier.
3338 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3339 // data members and cannot be applied to names declared const or static,
3340 // and cannot be applied to reference members.
3341 switch (DS.getStorageClassSpec()) {
3342 case DeclSpec::SCS_unspecified:
3343 case DeclSpec::SCS_typedef:
3344 case DeclSpec::SCS_static:
3345 break;
3346 case DeclSpec::SCS_mutable:
3347 if (isFunc) {
3348 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3349
3350 // FIXME: It would be nicer if the keyword was ignored only for this
3351 // declarator. Otherwise we could get follow-up errors.
3352 D.getMutableDeclSpec().ClearStorageClassSpecs();
3353 }
3354 break;
3355 default:
3356 Diag(DS.getStorageClassSpecLoc(),
3357 diag::err_storageclass_invalid_for_member);
3358 D.getMutableDeclSpec().ClearStorageClassSpecs();
3359 break;
3360 }
3361
3362 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3363 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3364 !isFunc);
3365
3366 if (DS.hasConstexprSpecifier() && isInstField) {
3367 SemaDiagnosticBuilder B =
3368 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3369 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3370 if (InitStyle == ICIS_NoInit) {
3371 B << 0 << 0;
3372 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3373 B << FixItHint::CreateRemoval(ConstexprLoc);
3374 else {
3375 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3376 D.getMutableDeclSpec().ClearConstexprSpec();
3377 const char *PrevSpec;
3378 unsigned DiagID;
3379 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3380 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3381 (void)Failed;
3382 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", 3382, __extension__ __PRETTY_FUNCTION__
))
;
3383 }
3384 } else {
3385 B << 1;
3386 const char *PrevSpec;
3387 unsigned DiagID;
3388 if (D.getMutableDeclSpec().SetStorageClassSpec(
3389 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3390 Context.getPrintingPolicy())) {
3391 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", 3392, __extension__ __PRETTY_FUNCTION__
))
3392 "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", 3392, __extension__ __PRETTY_FUNCTION__
))
;
3393 B << 1;
3394 } else {
3395 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3396 isInstField = false;
3397 }
3398 }
3399 }
3400
3401 NamedDecl *Member;
3402 if (isInstField) {
3403 CXXScopeSpec &SS = D.getCXXScopeSpec();
3404
3405 // Data members must have identifiers for names.
3406 if (!Name.isIdentifier()) {
3407 Diag(Loc, diag::err_bad_variable_name)
3408 << Name;
3409 return nullptr;
3410 }
3411
3412 IdentifierInfo *II = Name.getAsIdentifierInfo();
3413
3414 // Member field could not be with "template" keyword.
3415 // So TemplateParameterLists should be empty in this case.
3416 if (TemplateParameterLists.size()) {
3417 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3418 if (TemplateParams->size()) {
3419 // There is no such thing as a member field template.
3420 Diag(D.getIdentifierLoc(), diag::err_template_member)
3421 << II
3422 << SourceRange(TemplateParams->getTemplateLoc(),
3423 TemplateParams->getRAngleLoc());
3424 } else {
3425 // There is an extraneous 'template<>' for this member.
3426 Diag(TemplateParams->getTemplateLoc(),
3427 diag::err_template_member_noparams)
3428 << II
3429 << SourceRange(TemplateParams->getTemplateLoc(),
3430 TemplateParams->getRAngleLoc());
3431 }
3432 return nullptr;
3433 }
3434
3435 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3436 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3437 << II
3438 << SourceRange(D.getName().TemplateId->LAngleLoc,
3439 D.getName().TemplateId->RAngleLoc)
3440 << D.getName().TemplateId->LAngleLoc;
3441 D.SetIdentifier(II, Loc);
3442 }
3443
3444 if (SS.isSet() && !SS.isInvalid()) {
3445 // The user provided a superfluous scope specifier inside a class
3446 // definition:
3447 //
3448 // class X {
3449 // int X::member;
3450 // };
3451 if (DeclContext *DC = computeDeclContext(SS, false))
3452 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3453 D.getName().getKind() ==
3454 UnqualifiedIdKind::IK_TemplateId);
3455 else
3456 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3457 << Name << SS.getRange();
3458
3459 SS.clear();
3460 }
3461
3462 if (MSPropertyAttr) {
3463 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3464 BitWidth, InitStyle, AS, *MSPropertyAttr);
3465 if (!Member)
3466 return nullptr;
3467 isInstField = false;
3468 } else {
3469 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3470 BitWidth, InitStyle, AS);
3471 if (!Member)
3472 return nullptr;
3473 }
3474
3475 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3476 } else {
3477 Member = HandleDeclarator(S, D, TemplateParameterLists);
3478 if (!Member)
3479 return nullptr;
3480
3481 // Non-instance-fields can't have a bitfield.
3482 if (BitWidth) {
3483 if (Member->isInvalidDecl()) {
3484 // don't emit another diagnostic.
3485 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3486 // C++ 9.6p3: A bit-field shall not be a static member.
3487 // "static member 'A' cannot be a bit-field"
3488 Diag(Loc, diag::err_static_not_bitfield)
3489 << Name << BitWidth->getSourceRange();
3490 } else if (isa<TypedefDecl>(Member)) {
3491 // "typedef member 'x' cannot be a bit-field"
3492 Diag(Loc, diag::err_typedef_not_bitfield)
3493 << Name << BitWidth->getSourceRange();
3494 } else {
3495 // A function typedef ("typedef int f(); f a;").
3496 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3497 Diag(Loc, diag::err_not_integral_type_bitfield)
3498 << Name << cast<ValueDecl>(Member)->getType()
3499 << BitWidth->getSourceRange();
3500 }
3501
3502 BitWidth = nullptr;
3503 Member->setInvalidDecl();
3504 }
3505
3506 NamedDecl *NonTemplateMember = Member;
3507 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3508 NonTemplateMember = FunTmpl->getTemplatedDecl();
3509 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3510 NonTemplateMember = VarTmpl->getTemplatedDecl();
3511
3512 Member->setAccess(AS);
3513
3514 // If we have declared a member function template or static data member
3515 // template, set the access of the templated declaration as well.
3516 if (NonTemplateMember != Member)
3517 NonTemplateMember->setAccess(AS);
3518
3519 // C++ [temp.deduct.guide]p3:
3520 // A deduction guide [...] for a member class template [shall be
3521 // declared] with the same access [as the template].
3522 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3523 auto *TD = DG->getDeducedTemplate();
3524 // Access specifiers are only meaningful if both the template and the
3525 // deduction guide are from the same scope.
3526 if (AS != TD->getAccess() &&
3527 TD->getDeclContext()->getRedeclContext()->Equals(
3528 DG->getDeclContext()->getRedeclContext())) {
3529 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3530 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3531 << TD->getAccess();
3532 const AccessSpecDecl *LastAccessSpec = nullptr;
3533 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3534 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3535 LastAccessSpec = AccessSpec;
3536 }
3537 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", 3537, __extension__ __PRETTY_FUNCTION__
))
;
3538 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3539 << AS;
3540 }
3541 }
3542 }
3543
3544 if (VS.isOverrideSpecified())
3545 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3546 AttributeCommonInfo::AS_Keyword));
3547 if (VS.isFinalSpecified())
3548 Member->addAttr(FinalAttr::Create(
3549 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3550 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3551
3552 if (VS.getLastLocation().isValid()) {
3553 // Update the end location of a method that has a virt-specifiers.
3554 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3555 MD->setRangeEnd(VS.getLastLocation());
3556 }
3557
3558 CheckOverrideControl(Member);
3559
3560 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", 3560, __extension__ __PRETTY_FUNCTION__
))
;
3561
3562 if (isInstField) {
3563 FieldDecl *FD = cast<FieldDecl>(Member);
3564 FieldCollector->Add(FD);
3565
3566 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3567 // Remember all explicit private FieldDecls that have a name, no side
3568 // effects and are not part of a dependent type declaration.
3569 if (!FD->isImplicit() && FD->getDeclName() &&
3570 FD->getAccess() == AS_private &&
3571 !FD->hasAttr<UnusedAttr>() &&
3572 !FD->getParent()->isDependentContext() &&
3573 !InitializationHasSideEffects(*FD))
3574 UnusedPrivateFields.insert(FD);
3575 }
3576 }
3577
3578 return Member;
3579}
3580
3581namespace {
3582 class UninitializedFieldVisitor
3583 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3584 Sema &S;
3585 // List of Decls to generate a warning on. Also remove Decls that become
3586 // initialized.
3587 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3588 // List of base classes of the record. Classes are removed after their
3589 // initializers.
3590 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3591 // Vector of decls to be removed from the Decl set prior to visiting the
3592 // nodes. These Decls may have been initialized in the prior initializer.
3593 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3594 // If non-null, add a note to the warning pointing back to the constructor.
3595 const CXXConstructorDecl *Constructor;
3596 // Variables to hold state when processing an initializer list. When
3597 // InitList is true, special case initialization of FieldDecls matching
3598 // InitListFieldDecl.
3599 bool InitList;
3600 FieldDecl *InitListFieldDecl;
3601 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3602
3603 public:
3604 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3605 UninitializedFieldVisitor(Sema &S,
3606 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3607 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3608 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3609 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3610
3611 // Returns true if the use of ME is not an uninitialized use.
3612 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3613 bool CheckReferenceOnly) {
3614 llvm::SmallVector<FieldDecl*, 4> Fields;
3615 bool ReferenceField = false;
3616 while (ME) {
3617 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3618 if (!FD)
3619 return false;
3620 Fields.push_back(FD);
3621 if (FD->getType()->isReferenceType())
3622 ReferenceField = true;
3623 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3624 }
3625
3626 // Binding a reference to an uninitialized field is not an
3627 // uninitialized use.
3628 if (CheckReferenceOnly && !ReferenceField)
3629 return true;
3630
3631 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3632 // Discard the first field since it is the field decl that is being
3633 // initialized.
3634 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3635 UsedFieldIndex.push_back(FD->getFieldIndex());
3636
3637 for (auto UsedIter = UsedFieldIndex.begin(),
3638 UsedEnd = UsedFieldIndex.end(),
3639 OrigIter = InitFieldIndex.begin(),
3640 OrigEnd = InitFieldIndex.end();
3641 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3642 if (*UsedIter < *OrigIter)
3643 return true;
3644 if (*UsedIter > *OrigIter)
3645 break;
3646 }
3647
3648 return false;
3649 }
3650
3651 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3652 bool AddressOf) {
3653 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3654 return;
3655
3656 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3657 // or union.
3658 MemberExpr *FieldME = ME;
3659
3660 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3661
3662 Expr *Base = ME;
3663 while (MemberExpr *SubME =
3664 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3665
3666 if (isa<VarDecl>(SubME->getMemberDecl()))
3667 return;
3668
3669 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3670 if (!FD->isAnonymousStructOrUnion())
3671 FieldME = SubME;
3672
3673 if (!FieldME->getType().isPODType(S.Context))
3674 AllPODFields = false;
3675
3676 Base = SubME->getBase();
3677 }
3678
3679 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3680 Visit(Base);
3681 return;
3682 }
3683
3684 if (AddressOf && AllPODFields)
3685 return;
3686
3687 ValueDecl* FoundVD = FieldME->getMemberDecl();
3688
3689 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3690 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3691 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3692 }
3693
3694 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3695 QualType T = BaseCast->getType();
3696 if (T->isPointerType() &&
3697 BaseClasses.count(T->getPointeeType())) {
3698 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3699 << T->getPointeeType() << FoundVD;
3700 }
3701 }
3702 }
3703
3704 if (!Decls.count(FoundVD))
3705 return;
3706
3707 const bool IsReference = FoundVD->getType()->isReferenceType();
3708
3709 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3710 // Special checking for initializer lists.
3711 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3712 return;
3713 }
3714 } else {
3715 // Prevent double warnings on use of unbounded references.
3716 if (CheckReferenceOnly && !IsReference)
3717 return;
3718 }
3719
3720 unsigned diag = IsReference
3721 ? diag::warn_reference_field_is_uninit
3722 : diag::warn_field_is_uninit;
3723 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3724 if (Constructor)
3725 S.Diag(Constructor->getLocation(),
3726 diag::note_uninit_in_this_constructor)
3727 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3728
3729 }
3730
3731 void HandleValue(Expr *E, bool AddressOf) {
3732 E = E->IgnoreParens();
3733
3734 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3735 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3736 AddressOf /*AddressOf*/);
3737 return;
3738 }
3739
3740 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3741 Visit(CO->getCond());
3742 HandleValue(CO->getTrueExpr(), AddressOf);
3743 HandleValue(CO->getFalseExpr(), AddressOf);
3744 return;
3745 }
3746
3747 if (BinaryConditionalOperator *BCO =
3748 dyn_cast<BinaryConditionalOperator>(E)) {
3749 Visit(BCO->getCond());
3750 HandleValue(BCO->getFalseExpr(), AddressOf);
3751 return;
3752 }
3753
3754 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3755 HandleValue(OVE->getSourceExpr(), AddressOf);
3756 return;
3757 }
3758
3759 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3760 switch (BO->getOpcode()) {
3761 default:
3762 break;
3763 case(BO_PtrMemD):
3764 case(BO_PtrMemI):
3765 HandleValue(BO->getLHS(), AddressOf);
3766 Visit(BO->getRHS());
3767 return;
3768 case(BO_Comma):
3769 Visit(BO->getLHS());
3770 HandleValue(BO->getRHS(), AddressOf);
3771 return;
3772 }
3773 }
3774
3775 Visit(E);
3776 }
3777
3778 void CheckInitListExpr(InitListExpr *ILE) {
3779 InitFieldIndex.push_back(0);
3780 for (auto *Child : ILE->children()) {
3781 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3782 CheckInitListExpr(SubList);
3783 } else {
3784 Visit(Child);
3785 }
3786 ++InitFieldIndex.back();
3787 }
3788 InitFieldIndex.pop_back();
3789 }
3790
3791 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3792 FieldDecl *Field, const Type *BaseClass) {
3793 // Remove Decls that may have been initialized in the previous
3794 // initializer.
3795 for (ValueDecl* VD : DeclsToRemove)
3796 Decls.erase(VD);
3797 DeclsToRemove.clear();
3798
3799 Constructor = FieldConstructor;
3800 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3801
3802 if (ILE && Field) {
3803 InitList = true;
3804 InitListFieldDecl = Field;
3805 InitFieldIndex.clear();
3806 CheckInitListExpr(ILE);
3807 } else {
3808 InitList = false;
3809 Visit(E);
3810 }
3811
3812 if (Field)
3813 Decls.erase(Field);
3814 if (BaseClass)
3815 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3816 }
3817
3818 void VisitMemberExpr(MemberExpr *ME) {
3819 // All uses of unbounded reference fields will warn.
3820 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3821 }
3822
3823 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3824 if (E->getCastKind() == CK_LValueToRValue) {
3825 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3826 return;
3827 }
3828
3829 Inherited::VisitImplicitCastExpr(E);
3830 }
3831
3832 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3833 if (E->getConstructor()->isCopyConstructor()) {
3834 Expr *ArgExpr = E->getArg(0);
3835 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3836 if (ILE->getNumInits() == 1)
3837 ArgExpr = ILE->getInit(0);
3838 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3839 if (ICE->getCastKind() == CK_NoOp)
3840 ArgExpr = ICE->getSubExpr();
3841 HandleValue(ArgExpr, false /*AddressOf*/);
3842 return;
3843 }
3844 Inherited::VisitCXXConstructExpr(E);
3845 }
3846
3847 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3848 Expr *Callee = E->getCallee();
3849 if (isa<MemberExpr>(Callee)) {
3850 HandleValue(Callee, false /*AddressOf*/);
3851 for (auto *Arg : E->arguments())
3852 Visit(Arg);
3853 return;
3854 }
3855
3856 Inherited::VisitCXXMemberCallExpr(E);
3857 }
3858
3859 void VisitCallExpr(CallExpr *E) {
3860 // Treat std::move as a use.
3861 if (E->isCallToStdMove()) {
3862 HandleValue(E->getArg(0), /*AddressOf=*/false);
3863 return;
3864 }
3865
3866 Inherited::VisitCallExpr(E);
3867 }
3868
3869 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3870 Expr *Callee = E->getCallee();
3871
3872 if (isa<UnresolvedLookupExpr>(Callee))
3873 return Inherited::VisitCXXOperatorCallExpr(E);
3874
3875 Visit(Callee);
3876 for (auto *Arg : E->arguments())
3877 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3878 }
3879
3880 void VisitBinaryOperator(BinaryOperator *E) {
3881 // If a field assignment is detected, remove the field from the
3882 // uninitiailized field set.
3883 if (E->getOpcode() == BO_Assign)
3884 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3885 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3886 if (!FD->getType()->isReferenceType())
3887 DeclsToRemove.push_back(FD);
3888
3889 if (E->isCompoundAssignmentOp()) {
3890 HandleValue(E->getLHS(), false /*AddressOf*/);
3891 Visit(E->getRHS());
3892 return;
3893 }
3894
3895 Inherited::VisitBinaryOperator(E);
3896 }
3897
3898 void VisitUnaryOperator(UnaryOperator *E) {
3899 if (E->isIncrementDecrementOp()) {
3900 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3901 return;
3902 }
3903 if (E->getOpcode() == UO_AddrOf) {
3904 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3905 HandleValue(ME->getBase(), true /*AddressOf*/);
3906 return;
3907 }
3908 }
3909
3910 Inherited::VisitUnaryOperator(E);
3911 }
3912 };
3913
3914 // Diagnose value-uses of fields to initialize themselves, e.g.
3915 // foo(foo)
3916 // where foo is not also a parameter to the constructor.
3917 // Also diagnose across field uninitialized use such as
3918 // x(y), y(x)
3919 // TODO: implement -Wuninitialized and fold this into that framework.
3920 static void DiagnoseUninitializedFields(
3921 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3922
3923 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3924 Constructor->getLocation())) {
3925 return;
3926 }
3927
3928 if (Constructor->isInvalidDecl())
3929 return;
3930
3931 const CXXRecordDecl *RD = Constructor->getParent();
3932
3933 if (RD->isDependentContext())
3934 return;
3935
3936 // Holds fields that are uninitialized.
3937 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3938
3939 // At the beginning, all fields are uninitialized.
3940 for (auto *I : RD->decls()) {
3941 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3942 UninitializedFields.insert(FD);
3943 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3944 UninitializedFields.insert(IFD->getAnonField());
3945 }
3946 }
3947
3948 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3949 for (auto I : RD->bases())
3950 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3951
3952 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3953 return;
3954
3955 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3956 UninitializedFields,
3957 UninitializedBaseClasses);
3958
3959 for (const auto *FieldInit : Constructor->inits()) {
3960 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3961 break;
3962
3963 Expr *InitExpr = FieldInit->getInit();
3964 if (!InitExpr)
3965 continue;
3966
3967 if (CXXDefaultInitExpr *Default =
3968 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3969 InitExpr = Default->getExpr();
3970 if (!InitExpr)
3971 continue;
3972 // In class initializers will point to the constructor.
3973 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3974 FieldInit->getAnyMember(),
3975 FieldInit->getBaseClass());
3976 } else {
3977 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3978 FieldInit->getAnyMember(),
3979 FieldInit->getBaseClass());
3980 }
3981 }
3982 }
3983} // namespace
3984
3985/// Enter a new C++ default initializer scope. After calling this, the
3986/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3987/// parsing or instantiating the initializer failed.
3988void Sema::ActOnStartCXXInClassMemberInitializer() {
3989 // Create a synthetic function scope to represent the call to the constructor
3990 // that notionally surrounds a use of this initializer.
3991 PushFunctionScope();
3992}
3993
3994void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3995 if (!D.isFunctionDeclarator())
3996 return;
3997 auto &FTI = D.getFunctionTypeInfo();
3998 if (!FTI.Params)
3999 return;
4000 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4001 FTI.NumParams)) {
4002 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4003 if (ParamDecl->getDeclName())
4004 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4005 }
4006}
4007
4008ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4009 return ActOnRequiresClause(ConstraintExpr);
4010}
4011
4012ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4013 if (ConstraintExpr.isInvalid())
4014 return ExprError();
4015
4016 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4017 if (ConstraintExpr.isInvalid())
4018 return ExprError();
4019
4020 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4021 UPPC_RequiresClause))
4022 return ExprError();
4023
4024 return ConstraintExpr;
4025}
4026
4027/// This is invoked after parsing an in-class initializer for a
4028/// non-static C++ class member, and after instantiating an in-class initializer
4029/// in a class template. Such actions are deferred until the class is complete.
4030void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4031 SourceLocation InitLoc,
4032 Expr *InitExpr) {
4033 // Pop the notional constructor scope we created earlier.
4034 PopFunctionScopeInfo(nullptr, D);
4035
4036 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4037 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", 4038, __extension__ __PRETTY_FUNCTION__
))
4038 "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", 4038, __extension__ __PRETTY_FUNCTION__
))
;
4039
4040 if (!InitExpr) {
4041 D->setInvalidDecl();
4042 if (FD)
4043 FD->removeInClassInitializer();
4044 return;
4045 }
4046
4047 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
4048 FD->setInvalidDecl();
4049 FD->removeInClassInitializer();
4050 return;
4051 }
4052
4053 ExprResult Init = InitExpr;
4054 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
4055 InitializedEntity Entity =
4056 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4057 InitializationKind Kind =
4058 FD->getInClassInitStyle() == ICIS_ListInit
4059 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4060 InitExpr->getBeginLoc(),
4061 InitExpr->getEndLoc())
4062 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4063 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4064 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4065 if (Init.isInvalid()) {
4066 FD->setInvalidDecl();
4067 return;
4068 }
4069 }
4070
4071 // C++11 [class.base.init]p7:
4072 // The initialization of each base and member constitutes a
4073 // full-expression.
4074 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4075 if (Init.isInvalid()) {
4076 FD->setInvalidDecl();
4077 return;
4078 }
4079
4080 InitExpr = Init.get();
4081
4082 FD->setInClassInitializer(InitExpr);
4083}
4084
4085/// Find the direct and/or virtual base specifiers that
4086/// correspond to the given base type, for use in base initialization
4087/// within a constructor.
4088static bool FindBaseInitializer(Sema &SemaRef,
4089 CXXRecordDecl *ClassDecl,
4090 QualType BaseType,
4091 const CXXBaseSpecifier *&DirectBaseSpec,
4092 const CXXBaseSpecifier *&VirtualBaseSpec) {
4093 // First, check for a direct base class.
4094 DirectBaseSpec = nullptr;
4095 for (const auto &Base : ClassDecl->bases()) {
4096 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4097 // We found a direct base of this type. That's what we're
4098 // initializing.
4099 DirectBaseSpec = &Base;
4100 break;
4101 }
4102 }
4103
4104 // Check for a virtual base class.
4105 // FIXME: We might be able to short-circuit this if we know in advance that
4106 // there are no virtual bases.
4107 VirtualBaseSpec = nullptr;
4108 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4109 // We haven't found a base yet; search the class hierarchy for a
4110 // virtual base class.
4111 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4112 /*DetectVirtual=*/false);
4113 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4114 SemaRef.Context.getTypeDeclType(ClassDecl),
4115 BaseType, Paths)) {
4116 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4117 Path != Paths.end(); ++Path) {
4118 if (Path->back().Base->isVirtual()) {
4119 VirtualBaseSpec = Path->back().Base;
4120 break;
4121 }
4122 }
4123 }
4124 }
4125
4126 return DirectBaseSpec || VirtualBaseSpec;
4127}
4128
4129/// Handle a C++ member initializer using braced-init-list syntax.
4130MemInitResult
4131Sema::ActOnMemInitializer(Decl *ConstructorD,
4132 Scope *S,
4133 CXXScopeSpec &SS,
4134 IdentifierInfo *MemberOrBase,
4135 ParsedType TemplateTypeTy,
4136 const DeclSpec &DS,
4137 SourceLocation IdLoc,
4138 Expr *InitList,
4139 SourceLocation EllipsisLoc) {
4140 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4141 DS, IdLoc, InitList,
4142 EllipsisLoc);
4143}
4144
4145/// Handle a C++ member initializer using parentheses syntax.
4146MemInitResult
4147Sema::ActOnMemInitializer(Decl *ConstructorD,
4148 Scope *S,
4149 CXXScopeSpec &SS,
4150 IdentifierInfo *MemberOrBase,
4151 ParsedType TemplateTypeTy,
4152 const DeclSpec &DS,
4153 SourceLocation IdLoc,
4154 SourceLocation LParenLoc,
4155 ArrayRef<Expr *> Args,
4156 SourceLocation RParenLoc,
4157 SourceLocation EllipsisLoc) {
4158 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4159 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4160 DS, IdLoc, List, EllipsisLoc);
4161}
4162
4163namespace {
4164
4165// Callback to only accept typo corrections that can be a valid C++ member
4166// initializer: either a non-static field member or a base class.
4167class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4168public:
4169 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4170 : ClassDecl(ClassDecl) {}
4171
4172 bool ValidateCandidate(const TypoCorrection &candidate) override {
4173 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4174 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4175 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4176 return isa<TypeDecl>(ND);
4177 }
4178 return false;
4179 }
4180
4181 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4182 return std::make_unique<MemInitializerValidatorCCC>(*this);
4183 }
4184
4185private:
4186 CXXRecordDecl *ClassDecl;
4187};
4188
4189}
4190
4191ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4192 CXXScopeSpec &SS,
4193 ParsedType TemplateTypeTy,
4194 IdentifierInfo *MemberOrBase) {
4195 if (SS.getScopeRep() || TemplateTypeTy)
4196 return nullptr;
4197 for (auto *D : ClassDecl->lookup(MemberOrBase))
4198 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4199 return cast<ValueDecl>(D);
4200 return nullptr;
4201}
4202
4203/// Handle a C++ member initializer.
4204MemInitResult
4205Sema::BuildMemInitializer(Decl *ConstructorD,
4206 Scope *S,
4207 CXXScopeSpec &SS,
4208 IdentifierInfo *MemberOrBase,
4209 ParsedType TemplateTypeTy,
4210 const DeclSpec &DS,
4211 SourceLocation IdLoc,
4212 Expr *Init,
4213 SourceLocation EllipsisLoc) {
4214 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4215 /*RecoverUncorrectedTypos=*/true);
4216 if (!Res.isUsable())
4217 return true;
4218 Init = Res.get();
4219
4220 if (!ConstructorD)
4221 return true;
4222
4223 AdjustDeclIfTemplate(ConstructorD);
4224
4225 CXXConstructorDecl *Constructor
4226 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4227 if (!Constructor) {
4228 // The user wrote a constructor initializer on a function that is
4229 // not a C++ constructor. Ignore the error for now, because we may
4230 // have more member initializers coming; we'll diagnose it just
4231 // once in ActOnMemInitializers.
4232 return true;
4233 }
4234
4235 CXXRecordDecl *ClassDecl = Constructor->getParent();
4236
4237 // C++ [class.base.init]p2:
4238 // Names in a mem-initializer-id are looked up in the scope of the
4239 // constructor's class and, if not found in that scope, are looked
4240 // up in the scope containing the constructor's definition.
4241 // [Note: if the constructor's class contains a member with the
4242 // same name as a direct or virtual base class of the class, a
4243 // mem-initializer-id naming the member or base class and composed
4244 // of a single identifier refers to the class member. A
4245 // mem-initializer-id for the hidden base class may be specified
4246 // using a qualified name. ]
4247
4248 // Look for a member, first.
4249 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4250 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4251 if (EllipsisLoc.isValid())
4252 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4253 << MemberOrBase
4254 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4255
4256 return BuildMemberInitializer(Member, Init, IdLoc);
4257 }
4258 // It didn't name a member, so see if it names a class.
4259 QualType BaseType;
4260 TypeSourceInfo *TInfo = nullptr;
4261
4262 if (TemplateTypeTy) {
4263 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4264 if (BaseType.isNull())
4265 return true;
4266 } else if (DS.getTypeSpecType() == TST_decltype) {
4267 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4268 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4269 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4270 return true;
4271 } else {
4272 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4273 LookupParsedName(R, S, &SS);
4274
4275 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4276 if (!TyD) {
4277 if (R.isAmbiguous()) return true;
4278
4279 // We don't want access-control diagnostics here.
4280 R.suppressDiagnostics();
4281
4282 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4283 bool NotUnknownSpecialization = false;
4284 DeclContext *DC = computeDeclContext(SS, false);
4285 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4286 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4287
4288 if (!NotUnknownSpecialization) {
4289 // When the scope specifier can refer to a member of an unknown
4290 // specialization, we take it as a type name.
4291 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4292 SS.getWithLocInContext(Context),
4293 *MemberOrBase, IdLoc);
4294 if (BaseType.isNull())
4295 return true;
4296
4297 TInfo = Context.CreateTypeSourceInfo(BaseType);
4298 DependentNameTypeLoc TL =
4299 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4300 if (!TL.isNull()) {
4301 TL.setNameLoc(IdLoc);
4302 TL.setElaboratedKeywordLoc(SourceLocation());
4303 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4304 }
4305
4306 R.clear();
4307 R.setLookupName(MemberOrBase);
4308 }
4309 }
4310
4311 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4312 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4313 auto *TempSpec = cast<TemplateSpecializationType>(
4314 UnqualifiedBase->getInjectedClassNameSpecialization());
4315 TemplateName TN = TempSpec->getTemplateName();
4316 for (auto const &Base : ClassDecl->bases()) {
4317 auto BaseTemplate =
4318 Base.getType()->getAs<TemplateSpecializationType>();
4319 if (BaseTemplate && Context.hasSameTemplateName(
4320 BaseTemplate->getTemplateName(), TN)) {
4321 Diag(IdLoc, diag::ext_unqualified_base_class)
4322 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4323 BaseType = Base.getType();
4324 break;
4325 }
4326 }
4327 }
4328 }
4329
4330 // If no results were found, try to correct typos.
4331 TypoCorrection Corr;
4332 MemInitializerValidatorCCC CCC(ClassDecl);
4333 if (R.empty() && BaseType.isNull() &&
4334 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4335 CCC, CTK_ErrorRecovery, ClassDecl))) {
4336 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4337 // We have found a non-static data member with a similar
4338 // name to what was typed; complain and initialize that
4339 // member.
4340 diagnoseTypo(Corr,
4341 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4342 << MemberOrBase << true);
4343 return BuildMemberInitializer(Member, Init, IdLoc);
4344 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4345 const CXXBaseSpecifier *DirectBaseSpec;
4346 const CXXBaseSpecifier *VirtualBaseSpec;
4347 if (FindBaseInitializer(*this, ClassDecl,
4348 Context.getTypeDeclType(Type),
4349 DirectBaseSpec, VirtualBaseSpec)) {
4350 // We have found a direct or virtual base class with a
4351 // similar name to what was typed; complain and initialize
4352 // that base class.
4353 diagnoseTypo(Corr,
4354 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4355 << MemberOrBase << false,
4356 PDiag() /*Suppress note, we provide our own.*/);
4357
4358 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4359 : VirtualBaseSpec;
4360 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4361 << BaseSpec->getType() << BaseSpec->getSourceRange();
4362
4363 TyD = Type;
4364 }
4365 }
4366 }
4367
4368 if (!TyD && BaseType.isNull()) {
4369 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4370 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4371 return true;
4372 }
4373 }
4374
4375 if (BaseType.isNull()) {
4376 BaseType = getElaboratedType(ETK_None, SS, Context.getTypeDeclType(TyD));
4377 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4378 TInfo = Context.CreateTypeSourceInfo(BaseType);
4379 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4380 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4381 TL.setElaboratedKeywordLoc(SourceLocation());
4382 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4383 }
4384 }
4385
4386 if (!TInfo)
4387 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4388
4389 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4390}
4391
4392MemInitResult
4393Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4394 SourceLocation IdLoc) {
4395 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4396 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4397 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", 4398, __extension__ __PRETTY_FUNCTION__
))
4398 "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", 4398, __extension__ __PRETTY_FUNCTION__
))
;
4399
4400 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4401 return true;
4402
4403 if (Member->isInvalidDecl())
4404 return true;
4405
4406 MultiExprArg Args;
4407 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4408 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4409 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4410 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4411 } else {
4412 // Template instantiation doesn't reconstruct ParenListExprs for us.
4413 Args = Init;
4414 }
4415
4416 SourceRange InitRange = Init->getSourceRange();
4417
4418 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4419 // Can't check initialization for a member of dependent type or when
4420 // any of the arguments are type-dependent expressions.
4421 DiscardCleanupsInEvaluationContext();
4422 } else {
4423 bool InitList = false;
4424 if (isa<InitListExpr>(Init)) {
4425 InitList = true;
4426 Args = Init;
4427 }
4428
4429 // Initialize the member.
4430 InitializedEntity MemberEntity =
4431 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4432 : InitializedEntity::InitializeMember(IndirectMember,
4433 nullptr);
4434 InitializationKind Kind =
4435 InitList ? InitializationKind::CreateDirectList(
4436 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4437 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4438 InitRange.getEnd());
4439
4440 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4441 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4442 nullptr);
4443 if (!MemberInit.isInvalid()) {
4444 // C++11 [class.base.init]p7:
4445 // The initialization of each base and member constitutes a
4446 // full-expression.
4447 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4448 /*DiscardedValue*/ false);
4449 }
4450
4451 if (MemberInit.isInvalid()) {
4452 // Args were sensible expressions but we couldn't initialize the member
4453 // from them. Preserve them in a RecoveryExpr instead.
4454 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4455 Member->getType())
4456 .get();
4457 if (!Init)
4458 return true;
4459 } else {
4460 Init = MemberInit.get();
4461 }
4462 }
4463
4464 if (DirectMember) {
4465 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4466 InitRange.getBegin(), Init,
4467 InitRange.getEnd());
4468 } else {
4469 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4470 InitRange.getBegin(), Init,
4471 InitRange.getEnd());
4472 }
4473}
4474
4475MemInitResult
4476Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4477 CXXRecordDecl *ClassDecl) {
4478 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4479 if (!LangOpts.CPlusPlus11)
4480 return Diag(NameLoc, diag::err_delegating_ctor)
4481 << TInfo->getTypeLoc().getSourceRange();
4482 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4483
4484 bool InitList = true;
4485 MultiExprArg Args = Init;
4486 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4487 InitList = false;
4488 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4489 }
4490
4491 SourceRange InitRange = Init->getSourceRange();
4492 // Initialize the object.
4493 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4494 QualType(ClassDecl->getTypeForDecl(), 0));
4495 InitializationKind Kind =
4496 InitList ? InitializationKind::CreateDirectList(
4497 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4498 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4499 InitRange.getEnd());
4500 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4501 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4502 Args, nullptr);
4503 if (!DelegationInit.isInvalid()) {
4504 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", 4506, __extension__ __PRETTY_FUNCTION__
))
4505 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", 4506, __extension__ __PRETTY_FUNCTION__
))
4506 "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", 4506, __extension__ __PRETTY_FUNCTION__
))
;
4507
4508 // C++11 [class.base.init]p7:
4509 // The initialization of each base and member constitutes a
4510 // full-expression.
4511 DelegationInit = ActOnFinishFullExpr(
4512 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4513 }
4514
4515 if (DelegationInit.isInvalid()) {
4516 DelegationInit =
4517 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4518 QualType(ClassDecl->getTypeForDecl(), 0));
4519 if (DelegationInit.isInvalid())
4520 return true;
4521 } else {
4522 // If we are in a dependent context, template instantiation will
4523 // perform this type-checking again. Just save the arguments that we
4524 // received in a ParenListExpr.
4525 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4526 // of the information that we have about the base
4527 // initializer. However, deconstructing the ASTs is a dicey process,
4528 // and this approach is far more likely to get the corner cases right.
4529 if (CurContext->isDependentContext())
4530 DelegationInit = Init;
4531 }
4532
4533 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4534 DelegationInit.getAs<Expr>(),
4535 InitRange.getEnd());
4536}
4537
4538MemInitResult
4539Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4540 Expr *Init, CXXRecordDecl *ClassDecl,
4541 SourceLocation EllipsisLoc) {
4542 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4543
4544 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4545 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4546 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4547
4548 // C++ [class.base.init]p2:
4549 // [...] Unless the mem-initializer-id names a nonstatic data
4550 // member of the constructor's class or a direct or virtual base
4551 // of that class, the mem-initializer is ill-formed. A
4552 // mem-initializer-list can initialize a base class using any
4553 // name that denotes that base class type.
4554
4555 // We can store the initializers in "as-written" form and delay analysis until
4556 // instantiation if the constructor is dependent. But not for dependent
4557 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4558 bool Dependent = CurContext->isDependentContext() &&
4559 (BaseType->isDependentType() || Init->isTypeDependent());
4560
4561 SourceRange InitRange = Init->getSourceRange();
4562 if (EllipsisLoc.isValid()) {
4563 // This is a pack expansion.
4564 if (!BaseType->containsUnexpandedParameterPack()) {
4565 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4566 << SourceRange(BaseLoc, InitRange.getEnd());
4567
4568 EllipsisLoc = SourceLocation();
4569 }
4570 } else {
4571 // Check for any unexpanded parameter packs.
4572 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4573 return true;
4574
4575 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4576 return true;
4577 }
4578
4579 // Check for direct and virtual base classes.
4580 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4581 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4582 if (!Dependent) {
4583 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4584 BaseType))
4585 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4586
4587 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4588 VirtualBaseSpec);
4589
4590 // C++ [base.class.init]p2:
4591 // Unless the mem-initializer-id names a nonstatic data member of the
4592 // constructor's class or a direct or virtual base of that class, the
4593 // mem-initializer is ill-formed.
4594 if (!DirectBaseSpec && !VirtualBaseSpec) {
4595 // If the class has any dependent bases, then it's possible that
4596 // one of those types will resolve to the same type as
4597 // BaseType. Therefore, just treat this as a dependent base
4598 // class initialization. FIXME: Should we try to check the
4599 // initialization anyway? It seems odd.
4600 if (ClassDecl->hasAnyDependentBases())
4601 Dependent = true;
4602 else
4603 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4604 << BaseType << Context.getTypeDeclType(ClassDecl)
4605 << BaseTInfo->getTypeLoc().getSourceRange();
4606 }
4607 }
4608
4609 if (Dependent) {
4610 DiscardCleanupsInEvaluationContext();
4611
4612 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4613 /*IsVirtual=*/false,
4614 InitRange.getBegin(), Init,
4615 InitRange.getEnd(), EllipsisLoc);
4616 }
4617
4618 // C++ [base.class.init]p2:
4619 // If a mem-initializer-id is ambiguous because it designates both
4620 // a direct non-virtual base class and an inherited virtual base
4621 // class, the mem-initializer is ill-formed.
4622 if (DirectBaseSpec && VirtualBaseSpec)
4623 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4624 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4625
4626 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4627 if (!BaseSpec)
4628 BaseSpec = VirtualBaseSpec;
4629
4630 // Initialize the base.
4631 bool InitList = true;
4632 MultiExprArg Args = Init;
4633 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4634 InitList = false;
4635 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4636 }
4637
4638 InitializedEntity BaseEntity =
4639 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4640 InitializationKind Kind =
4641 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4642 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4643 InitRange.getEnd());
4644 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4645 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4646 if (!BaseInit.isInvalid()) {
4647 // C++11 [class.base.init]p7:
4648 // The initialization of each base and member constitutes a
4649 // full-expression.
4650 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4651 /*DiscardedValue*/ false);
4652 }
4653
4654 if (BaseInit.isInvalid()) {
4655 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4656 Args, BaseType);
4657 if (BaseInit.isInvalid())
4658 return true;
4659 } else {
4660 // If we are in a dependent context, template instantiation will
4661 // perform this type-checking again. Just save the arguments that we
4662 // received in a ParenListExpr.
4663 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4664 // of the information that we have about the base
4665 // initializer. However, deconstructing the ASTs is a dicey process,
4666 // and this approach is far more likely to get the corner cases right.
4667 if (CurContext->isDependentContext())
4668 BaseInit = Init;
4669 }
4670
4671 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4672 BaseSpec->isVirtual(),
4673 InitRange.getBegin(),
4674 BaseInit.getAs<Expr>(),
4675 InitRange.getEnd(), EllipsisLoc);
4676}
4677
4678// Create a static_cast\<T&&>(expr).
4679static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4680 if (T.isNull()) T = E->getType();
4681 QualType TargetType = SemaRef.BuildReferenceType(
4682 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4683 SourceLocation ExprLoc = E->getBeginLoc();
4684 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4685 TargetType, ExprLoc);
4686
4687 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4688 SourceRange(ExprLoc, ExprLoc),
4689 E->getSourceRange()).get();
4690}
4691
4692/// ImplicitInitializerKind - How an implicit base or member initializer should
4693/// initialize its base or member.
4694enum ImplicitInitializerKind {
4695 IIK_Default,
4696 IIK_Copy,
4697 IIK_Move,
4698 IIK_Inherit
4699};
4700
4701static bool
4702BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4703 ImplicitInitializerKind ImplicitInitKind,
4704 CXXBaseSpecifier *BaseSpec,
4705 bool IsInheritedVirtualBase,
4706 CXXCtorInitializer *&CXXBaseInit) {
4707 InitializedEntity InitEntity
4708 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4709 IsInheritedVirtualBase);
4710
4711 ExprResult BaseInit;
4712
4713 switch (ImplicitInitKind) {
4714 case IIK_Inherit:
4715 case IIK_Default: {
4716 InitializationKind InitKind
4717 = InitializationKind::CreateDefault(Constructor->getLocation());
4718 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4719 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4720 break;
4721 }
4722
4723 case IIK_Move:
4724 case IIK_Copy: {
4725 bool Moving = ImplicitInitKind == IIK_Move;
4726 ParmVarDecl *Param = Constructor->getParamDecl(0);
4727 QualType ParamType = Param->getType().getNonReferenceType();
4728
4729 Expr *CopyCtorArg =
4730 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4731 SourceLocation(), Param, false,
4732 Constructor->getLocation(), ParamType,
4733 VK_LValue, nullptr);
4734
4735 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4736
4737 // Cast to the base class to avoid ambiguities.
4738 QualType ArgTy =
4739 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4740 ParamType.getQualifiers());
4741
4742 if (Moving) {
4743 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4744 }
4745
4746 CXXCastPath BasePath;
4747 BasePath.push_back(BaseSpec);
4748 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4749 CK_UncheckedDerivedToBase,
4750 Moving ? VK_XValue : VK_LValue,
4751 &BasePath).get();
4752
4753 InitializationKind InitKind
4754 = InitializationKind::CreateDirect(Constructor->getLocation(),
4755 SourceLocation(), SourceLocation());
4756 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4757 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4758 break;
4759 }
4760 }
4761
4762 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4763 if (BaseInit.isInvalid())
4764 return true;
4765
4766 CXXBaseInit =
4767 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4768 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4769 SourceLocation()),
4770 BaseSpec->isVirtual(),
4771 SourceLocation(),
4772 BaseInit.getAs<Expr>(),
4773 SourceLocation(),
4774 SourceLocation());
4775
4776 return false;
4777}
4778
4779static bool RefersToRValueRef(Expr *MemRef) {
4780 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4781 return Referenced->getType()->isRValueReferenceType();
4782}
4783
4784static bool
4785BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4786 ImplicitInitializerKind ImplicitInitKind,
4787 FieldDecl *Field, IndirectFieldDecl *Indirect,
4788 CXXCtorInitializer *&CXXMemberInit) {
4789 if (Field->isInvalidDecl())
4790 return true;
4791
4792 SourceLocation Loc = Constructor->getLocation();
4793
4794 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4795 bool Moving = ImplicitInitKind == IIK_Move;
4796 ParmVarDecl *Param = Constructor->getParamDecl(0);
4797 QualType ParamType = Param->getType().getNonReferenceType();
4798
4799 // Suppress copying zero-width bitfields.
4800 if (Field->isZeroLengthBitField(SemaRef.Context))
4801 return false;
4802
4803 Expr *MemberExprBase =
4804 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4805 SourceLocation(), Param, false,
4806 Loc, ParamType, VK_LValue, nullptr);
4807
4808 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4809
4810 if (Moving) {
4811 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4812 }
4813
4814 // Build a reference to this field within the parameter.
4815 CXXScopeSpec SS;
4816 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4817 Sema::LookupMemberName);
4818 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4819 : cast<ValueDecl>(Field), AS_public);
4820 MemberLookup.resolveKind();
4821 ExprResult CtorArg
4822 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4823 ParamType, Loc,
4824 /*IsArrow=*/false,
4825 SS,
4826 /*TemplateKWLoc=*/SourceLocation(),
4827 /*FirstQualifierInScope=*/nullptr,
4828 MemberLookup,
4829 /*TemplateArgs=*/nullptr,
4830 /*S*/nullptr);
4831 if (CtorArg.isInvalid())
4832 return true;
4833
4834 // C++11 [class.copy]p15:
4835 // - if a member m has rvalue reference type T&&, it is direct-initialized
4836 // with static_cast<T&&>(x.m);
4837 if (RefersToRValueRef(CtorArg.get())) {
4838 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4839 }
4840
4841 InitializedEntity Entity =
4842 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4843 /*Implicit*/ true)
4844 : InitializedEntity::InitializeMember(Field, nullptr,
4845 /*Implicit*/ true);
4846
4847 // Direct-initialize to use the copy constructor.
4848 InitializationKind InitKind =
4849 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4850
4851 Expr *CtorArgE = CtorArg.getAs<Expr>();
4852 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4853 ExprResult MemberInit =
4854 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4855 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4856 if (MemberInit.isInvalid())
4857 return true;
4858
4859 if (Indirect)
4860 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4861 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4862 else
4863 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4864 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4865 return false;
4866 }
4867
4868 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", 4869, __extension__ __PRETTY_FUNCTION__
))
4869 "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", 4869, __extension__ __PRETTY_FUNCTION__
))
;
4870
4871 QualType FieldBaseElementType =
4872 SemaRef.Context.getBaseElementType(Field->getType());
4873
4874 if (FieldBaseElementType->isRecordType()) {
4875 InitializedEntity InitEntity =
4876 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4877 /*Implicit*/ true)
4878 : InitializedEntity::InitializeMember(Field, nullptr,
4879 /*Implicit*/ true);
4880 InitializationKind InitKind =
4881 InitializationKind::CreateDefault(Loc);
4882
4883 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4884 ExprResult MemberInit =
4885 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4886
4887 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4888 if (MemberInit.isInvalid())
4889 return true;
4890
4891 if (Indirect)
4892 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4893 Indirect, Loc,
4894 Loc,
4895 MemberInit.get(),
4896 Loc);
4897 else
4898 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4899 Field, Loc, Loc,
4900 MemberInit.get(),
4901 Loc);
4902 return false;
4903 }
4904
4905 if (!Field->getParent()->isUnion()) {
4906 if (FieldBaseElementType->isReferenceType()) {
4907 SemaRef.Diag(Constructor->getLocation(),
4908 diag::err_uninitialized_member_in_ctor)
4909 << (int)Constructor->isImplicit()
4910 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4911 << 0 << Field->getDeclName();
4912 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4913 return true;
4914 }
4915
4916 if (FieldBaseElementType.isConstQualified()) {
4917 SemaRef.Diag(Constructor->getLocation(),
4918 diag::err_uninitialized_member_in_ctor)
4919 << (int)Constructor->isImplicit()
4920 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4921 << 1 << Field->getDeclName();
4922 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4923 return true;
4924 }
4925 }
4926
4927 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4928 // ARC and Weak:
4929 // Default-initialize Objective-C pointers to NULL.
4930 CXXMemberInit
4931 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4932 Loc, Loc,
4933 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4934 Loc);
4935 return false;
4936 }
4937
4938 // Nothing to initialize.
4939 CXXMemberInit = nullptr;
4940 return false;
4941}
4942
4943namespace {
4944struct BaseAndFieldInfo {
4945 Sema &S;
4946 CXXConstructorDecl *Ctor;
4947 bool AnyErrorsInInits;
4948 ImplicitInitializerKind IIK;
4949 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4950 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4951 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4952
4953 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4954 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4955 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4956 if (Ctor->getInheritedConstructor())
4957 IIK = IIK_Inherit;
4958 else if (Generated && Ctor->isCopyConstructor())
4959 IIK = IIK_Copy;
4960 else if (Generated && Ctor->isMoveConstructor())
4961 IIK = IIK_Move;
4962 else
4963 IIK = IIK_Default;
4964 }
4965
4966 bool isImplicitCopyOrMove() const {
4967 switch (IIK) {
4968 case IIK_Copy:
4969 case IIK_Move:
4970 return true;
4971
4972 case IIK_Default:
4973 case IIK_Inherit:
4974 return false;
4975 }
4976
4977 llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!"
, "clang/lib/Sema/SemaDeclCXX.cpp", 4977)
;
4978 }
4979
4980 bool addFieldInitializer(CXXCtorInitializer *Init) {
4981 AllToInit.push_back(Init);
4982
4983 // Check whether this initializer makes the field "used".
4984 if (Init->getInit()->HasSideEffects(S.Context))
4985 S.UnusedPrivateFields.remove(Init->getAnyMember());
4986
4987 return false;
4988 }
4989
4990 bool isInactiveUnionMember(FieldDecl *Field) {
4991 RecordDecl *Record = Field->getParent();
4992 if (!Record->isUnion())
4993 return false;
4994
4995 if (FieldDecl *Active =
4996 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4997 return Active != Field->getCanonicalDecl();
4998
4999 // In an implicit copy or move constructor, ignore any in-class initializer.
5000 if (isImplicitCopyOrMove())
5001 return true;
5002
5003 // If there's no explicit initialization, the field is active only if it
5004 // has an in-class initializer...
5005 if (Field->hasInClassInitializer())
5006 return false;
5007 // ... or it's an anonymous struct or union whose class has an in-class
5008 // initializer.
5009 if (!Field->isAnonymousStructOrUnion())
5010 return true;
5011 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5012 return !FieldRD->hasInClassInitializer();
5013 }
5014
5015 /// Determine whether the given field is, or is within, a union member
5016 /// that is inactive (because there was an initializer given for a different
5017 /// member of the union, or because the union was not initialized at all).
5018 bool isWithinInactiveUnionMember(FieldDecl *Field,
5019 IndirectFieldDecl *Indirect) {
5020 if (!Indirect)
5021 return isInactiveUnionMember(Field);
5022
5023 for (auto *C : Indirect->chain()) {
5024 FieldDecl *Field = dyn_cast<FieldDecl>(C);
5025 if (Field && isInactiveUnionMember(Field))
5026 return true;
5027 }
5028 return false;
5029 }
5030};
5031}
5032
5033/// Determine whether the given type is an incomplete or zero-lenfgth
5034/// array type.
5035static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5036 if (T->isIncompleteArrayType())
5037 return true;
5038
5039 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5040 if (!ArrayT->getSize())
5041 return true;
5042
5043 T = ArrayT->getElementType();
5044 }
5045
5046 return false;
5047}
5048
5049static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5050 FieldDecl *Field,
5051 IndirectFieldDecl *Indirect = nullptr) {
5052 if (Field->isInvalidDecl())
5053 return false;
5054
5055 // Overwhelmingly common case: we have a direct initializer for this field.
5056 if (CXXCtorInitializer *Init =
5057 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5058 return Info.addFieldInitializer(Init);
5059
5060 // C++11 [class.base.init]p8:
5061 // if the entity is a non-static data member that has a
5062 // brace-or-equal-initializer and either
5063 // -- the constructor's class is a union and no other variant member of that
5064 // union is designated by a mem-initializer-id or
5065 // -- the constructor's class is not a union, and, if the entity is a member
5066 // of an anonymous union, no other member of that union is designated by
5067 // a mem-initializer-id,
5068 // the entity is initialized as specified in [dcl.init].
5069 //
5070 // We also apply the same rules to handle anonymous structs within anonymous
5071 // unions.
5072 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5073 return false;
5074
5075 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5076 ExprResult DIE =
5077 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5078 if (DIE.isInvalid())
5079 return true;
5080
5081 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5082 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5083
5084 CXXCtorInitializer *Init;
5085 if (Indirect)
5086 Init = new (SemaRef.Context)
5087 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5088 SourceLocation(), DIE.get(), SourceLocation());
5089 else
5090 Init = new (SemaRef.Context)
5091 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5092 SourceLocation(), DIE.get(), SourceLocation());
5093 return Info.addFieldInitializer(Init);
5094 }
5095
5096 // Don't initialize incomplete or zero-length arrays.
5097 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5098 return false;
5099
5100 // Don't try to build an implicit initializer if there were semantic
5101 // errors in any of the initializers (and therefore we might be
5102 // missing some that the user actually wrote).
5103 if (Info.AnyErrorsInInits)
5104 return false;
5105
5106 CXXCtorInitializer *Init = nullptr;
5107 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5108 Indirect, Init))
5109 return true;
5110
5111 if (!Init)
5112 return false;
5113
5114 return Info.addFieldInitializer(Init);
5115}
5116
5117bool
5118Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5119 CXXCtorInitializer *Initializer) {
5120 assert(Initializer->isDelegatingInitializer())(static_cast <bool> (Initializer->isDelegatingInitializer
()) ? void (0) : __assert_fail ("Initializer->isDelegatingInitializer()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 5120, __extension__ __PRETTY_FUNCTION__
))
;
5121 Constructor->setNumCtorInitializers(1);
5122 CXXCtorInitializer **initializer =
5123 new (Context) CXXCtorInitializer*[1];
5124 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5125 Constructor->setCtorInitializers(initializer);
5126
5127 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5128 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5129 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5130 }
5131
5132 DelegatingCtorDecls.push_back(Constructor);
5133
5134 DiagnoseUninitializedFields(*this, Constructor);
5135
5136 return false;
5137}
5138
5139bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5140 ArrayRef<CXXCtorInitializer *> Initializers) {
5141 if (Constructor->isDependentContext()) {
5142 // Just store the initializers as written, they will be checked during
5143 // instantiation.
5144 if (!Initializers.empty()) {
5145 Constructor->setNumCtorInitializers(Initializers.size());
5146 CXXCtorInitializer **baseOrMemberInitializers =
5147 new (Context) CXXCtorInitializer*[Initializers.size()];
5148 memcpy(baseOrMemberInitializers, Initializers.data(),
5149 Initializers.size() * sizeof(CXXCtorInitializer*));
5150 Constructor->setCtorInitializers(baseOrMemberInitializers);
5151 }
5152
5153 // Let template instantiation know whether we had errors.
5154 if (AnyErrors)
5155 Constructor->setInvalidDecl();
5156
5157 return false;
5158 }
5159
5160 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5161
5162 // We need to build the initializer AST according to order of construction
5163 // and not what user specified in the Initializers list.
5164 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5165 if (!ClassDecl)
5166 return true;
5167
5168 bool HadError = false;
5169
5170 for (unsigned i = 0; i < Initializers.size(); i++) {
5171 CXXCtorInitializer *Member = Initializers[i];
5172
5173 if (Member->isBaseInitializer())
5174 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5175 else {
5176 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5177
5178 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5179 for (auto *C : F->chain()) {
5180 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5181 if (FD && FD->getParent()->isUnion())
5182 Info.ActiveUnionMember.insert(std::make_pair(
5183 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5184 }
5185 } else if (FieldDecl *FD = Member->getMember()) {
5186 if (FD->getParent()->isUnion())
5187 Info.ActiveUnionMember.insert(std::make_pair(
5188 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5189 }
5190 }
5191 }
5192
5193 // Keep track of the direct virtual bases.
5194 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5195 for (auto &I : ClassDecl->bases()) {
5196 if (I.isVirtual())
5197 DirectVBases.insert(&I);
5198 }
5199
5200 // Push virtual bases before others.
5201 for (auto &VBase : ClassDecl->vbases()) {
5202 if (CXXCtorInitializer *Value
5203 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5204 // [class.base.init]p7, per DR257:
5205 // A mem-initializer where the mem-initializer-id names a virtual base
5206 // class is ignored during execution of a constructor of any class that
5207 // is not the most derived class.
5208 if (ClassDecl->isAbstract()) {
5209 // FIXME: Provide a fixit to remove the base specifier. This requires
5210 // tracking the location of the associated comma for a base specifier.
5211 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5212 << VBase.getType() << ClassDecl;
5213 DiagnoseAbstractType(ClassDecl);
5214 }
5215
5216 Info.AllToInit.push_back(Value);
5217 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5218 // [class.base.init]p8, per DR257:
5219 // If a given [...] base class is not named by a mem-initializer-id
5220 // [...] and the entity is not a virtual base class of an abstract
5221 // class, then [...] the entity is default-initialized.
5222 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5223 CXXCtorInitializer *CXXBaseInit;
5224 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5225 &VBase, IsInheritedVirtualBase,
5226 CXXBaseInit)) {
5227 HadError = true;
5228 continue;
5229 }
5230
5231 Info.AllToInit.push_back(CXXBaseInit);
5232 }
5233 }
5234
5235 // Non-virtual bases.
5236 for (auto &Base : ClassDecl->bases()) {
5237 // Virtuals are in the virtual base list and already constructed.
5238 if (Base.isVirtual())
5239 continue;
5240
5241 if (CXXCtorInitializer *Value
5242 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5243 Info.AllToInit.push_back(Value);
5244 } else if (!AnyErrors) {
5245 CXXCtorInitializer *CXXBaseInit;
5246 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5247 &Base, /*IsInheritedVirtualBase=*/false,
5248 CXXBaseInit)) {
5249 HadError = true;
5250 continue;
5251 }
5252
5253 Info.AllToInit.push_back(CXXBaseInit);
5254 }
5255 }
5256
5257 // Fields.
5258 for (auto *Mem : ClassDecl->decls()) {
5259 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5260 // C++ [class.bit]p2:
5261 // A declaration for a bit-field that omits the identifier declares an
5262 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5263 // initialized.
5264 if (F->isUnnamedBitfield())
5265 continue;
5266
5267 // If we're not generating the implicit copy/move constructor, then we'll
5268 // handle anonymous struct/union fields based on their individual
5269 // indirect fields.
5270 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5271 continue;
5272
5273 if (CollectFieldInitializer(*this, Info, F))
5274 HadError = true;
5275 continue;
5276 }
5277
5278 // Beyond this point, we only consider default initialization.
5279 if (Info.isImplicitCopyOrMove())
5280 continue;
5281
5282 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5283 if (F->getType()->isIncompleteArrayType()) {
5284 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", 5285, __extension__ __PRETTY_FUNCTION__
))
5285 "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", 5285, __extension__ __PRETTY_FUNCTION__
))
;
5286 continue;
5287 }
5288
5289 // Initialize each field of an anonymous struct individually.
5290 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5291 HadError = true;
5292
5293 continue;
5294 }
5295 }
5296
5297 unsigned NumInitializers = Info.AllToInit.size();
5298 if (NumInitializers > 0) {
5299 Constructor->setNumCtorInitializers(NumInitializers);
5300 CXXCtorInitializer **baseOrMemberInitializers =
5301 new (Context) CXXCtorInitializer*[NumInitializers];
5302 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5303 NumInitializers * sizeof(CXXCtorInitializer*));
5304 Constructor->setCtorInitializers(baseOrMemberInitializers);
5305
5306 // Constructors implicitly reference the base and member
5307 // destructors.
5308 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5309 Constructor->getParent());
5310 }
5311
5312 return HadError;
5313}
5314
5315static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5316 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5317 const RecordDecl *RD = RT->getDecl();
5318 if (RD->isAnonymousStructOrUnion()) {
5319 for (auto *Field : RD->fields())
5320 PopulateKeysForFields(Field, IdealInits);
5321 return;
5322 }
5323 }
5324 IdealInits.push_back(Field->getCanonicalDecl());
5325}
5326
5327static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5328 return Context.getCanonicalType(BaseType).getTypePtr();
5329}
5330
5331static const void *GetKeyForMember(ASTContext &Context,
5332 CXXCtorInitializer *Member) {
5333 if (!Member->isAnyMemberInitializer())
5334 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5335
5336 return Member->getAnyMember()->getCanonicalDecl();
5337}
5338
5339static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5340 const CXXCtorInitializer *Previous,
5341 const CXXCtorInitializer *Current) {
5342 if (Previous->isAnyMemberInitializer())
5343 Diag << 0 << Previous->getAnyMember();
5344 else
5345 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5346
5347 if (Current->isAnyMemberInitializer())
5348 Diag << 0 << Current->getAnyMember();
5349 else
5350 Diag << 1 << Current->getTypeSourceInfo()->getType();
5351}
5352
5353static void DiagnoseBaseOrMemInitializerOrder(
5354 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5355 ArrayRef<CXXCtorInitializer *> Inits) {
5356 if (Constructor->getDeclContext()->isDependentContext())
5357 return;
5358
5359 // Don't check initializers order unless the warning is enabled at the
5360 // location of at least one initializer.
5361 bool ShouldCheckOrder = false;
5362 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5363 CXXCtorInitializer *Init = Inits[InitIndex];
5364 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5365 Init->getSourceLocation())) {
5366 ShouldCheckOrder = true;
5367 break;
5368 }
5369 }
5370 if (!ShouldCheckOrder)
5371 return;
5372
5373 // Build the list of bases and members in the order that they'll
5374 // actually be initialized. The explicit initializers should be in
5375 // this same order but may be missing things.
5376 SmallVector<const void*, 32> IdealInitKeys;
5377
5378 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5379
5380 // 1. Virtual bases.
5381 for (const auto &VBase : ClassDecl->vbases())
5382 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5383
5384 // 2. Non-virtual bases.
5385 for (const auto &Base : ClassDecl->bases()) {
5386 if (Base.isVirtual())
5387 continue;
5388 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5389 }
5390
5391 // 3. Direct fields.
5392 for (auto *Field : ClassDecl->fields()) {
5393 if (Field->isUnnamedBitfield())
5394 continue;
5395
5396 PopulateKeysForFields(Field, IdealInitKeys);
5397 }
5398
5399 unsigned NumIdealInits = IdealInitKeys.size();
5400 unsigned IdealIndex = 0;
5401
5402 // Track initializers that are in an incorrect order for either a warning or
5403 // note if multiple ones occur.
5404 SmallVector<unsigned> WarnIndexes;
5405 // Correlates the index of an initializer in the init-list to the index of
5406 // the field/base in the class.
5407 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5408
5409 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5410 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5411
5412 // Scan forward to try to find this initializer in the idealized
5413 // initializers list.
5414 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5415 if (InitKey == IdealInitKeys[IdealIndex])
5416 break;
5417
5418 // If we didn't find this initializer, it must be because we
5419 // scanned past it on a previous iteration. That can only
5420 // happen if we're out of order; emit a warning.
5421 if (IdealIndex == NumIdealInits && InitIndex) {
5422 WarnIndexes.push_back(InitIndex);
5423
5424 // Move back to the initializer's location in the ideal list.
5425 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5426 if (InitKey == IdealInitKeys[IdealIndex])
5427 break;
5428
5429 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", 5430, __extension__ __PRETTY_FUNCTION__
))
5430 "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", 5430, __extension__ __PRETTY_FUNCTION__
))
;
5431 }
5432 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5433 }
5434
5435 if (WarnIndexes.empty())
5436 return;
5437
5438 // Sort based on the ideal order, first in the pair.
5439 llvm::sort(CorrelatedInitOrder, llvm::less_first());
5440
5441 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5442 // emit the diagnostic before we can try adding notes.
5443 {
5444 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5445 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5446 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5447 : diag::warn_some_initializers_out_of_order);
5448
5449 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5450 if (CorrelatedInitOrder[I].second == I)
5451 continue;
5452 // Ideally we would be using InsertFromRange here, but clang doesn't
5453 // appear to handle InsertFromRange correctly when the source range is
5454 // modified by another fix-it.
5455 D << FixItHint::CreateReplacement(
5456 Inits[I]->getSourceRange(),
5457 Lexer::getSourceText(
5458 CharSourceRange::getTokenRange(
5459 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5460 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5461 }
5462
5463 // If there is only 1 item out of order, the warning expects the name and
5464 // type of each being added to it.
5465 if (WarnIndexes.size() == 1) {
5466 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5467 Inits[WarnIndexes.front()]);
5468 return;
5469 }
5470 }
5471 // More than 1 item to warn, create notes letting the user know which ones
5472 // are bad.
5473 for (unsigned WarnIndex : WarnIndexes) {
5474 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5475 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5476 diag::note_initializer_out_of_order);
5477 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5478 D << PrevInit->getSourceRange();
5479 }
5480}
5481
5482namespace {
5483bool CheckRedundantInit(Sema &S,
5484 CXXCtorInitializer *Init,
5485 CXXCtorInitializer *&PrevInit) {
5486 if (!PrevInit) {
5487 PrevInit = Init;
5488 return false;
5489 }
5490
5491 if (FieldDecl *Field = Init->getAnyMember())
5492 S.Diag(Init->getSourceLocation(),
5493 diag::err_multiple_mem_initialization)
5494 << Field->getDeclName()
5495 << Init->getSourceRange();
5496 else {
5497 const Type *BaseClass = Init->getBaseClass();
5498 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", 5498, __extension__ __PRETTY_FUNCTION__
))
;
5499 S.Diag(Init->getSourceLocation(),
5500 diag::err_multiple_base_initialization)
5501 << QualType(BaseClass, 0)
5502 << Init->getSourceRange();
5503 }
5504 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5505 << 0 << PrevInit->getSourceRange();
5506
5507 return true;
5508}
5509
5510typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5511typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5512
5513bool CheckRedundantUnionInit(Sema &S,
5514 CXXCtorInitializer *Init,
5515 RedundantUnionMap &Unions) {
5516 FieldDecl *Field = Init->getAnyMember();
5517 RecordDecl *Parent = Field->getParent();
5518 NamedDecl *Child = Field;
5519
5520 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5521 if (Parent->isUnion()) {
5522 UnionEntry &En = Unions[Parent];
5523 if (En.first && En.first != Child) {
5524 S.Diag(Init->getSourceLocation(),
5525 diag::err_multiple_mem_union_initialization)
5526 << Field->getDeclName()
5527 << Init->getSourceRange();
5528 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5529 << 0 << En.second->getSourceRange();
5530 return true;
5531 }
5532 if (!En.first) {
5533 En.first = Child;
5534 En.second = Init;
5535 }
5536 if (!Parent->isAnonymousStructOrUnion())
5537 return false;
5538 }
5539
5540 Child = Parent;
5541 Parent = cast<RecordDecl>(Parent->getDeclContext());
5542 }
5543
5544 return false;
5545}
5546} // namespace
5547
5548/// ActOnMemInitializers - Handle the member initializers for a constructor.
5549void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5550 SourceLocation ColonLoc,
5551 ArrayRef<CXXCtorInitializer*> MemInits,
5552 bool AnyErrors) {
5553 if (!ConstructorDecl)
5554 return;
5555
5556 AdjustDeclIfTemplate(ConstructorDecl);
5557
5558 CXXConstructorDecl *Constructor
5559 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5560
5561 if (!Constructor) {
5562 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5563 return;
5564 }
5565
5566 // Mapping for the duplicate initializers check.
5567 // For member initializers, this is keyed with a FieldDecl*.
5568 // For base initializers, this is keyed with a Type*.
5569 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5570
5571 // Mapping for the inconsistent anonymous-union initializers check.
5572 RedundantUnionMap MemberUnions;
5573
5574 bool HadError = false;
5575 for (unsigned i = 0; i < MemInits.size(); i++) {
5576 CXXCtorInitializer *Init = MemInits[i];
5577
5578 // Set the source order index.
5579 Init->setSourceOrder(i);
5580
5581 if (Init->isAnyMemberInitializer()) {
5582 const void *Key = GetKeyForMember(Context, Init);
5583 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5584 CheckRedundantUnionInit(*this, Init, MemberUnions))
5585 HadError = true;
5586 } else if (Init->isBaseInitializer()) {
5587 const void *Key = GetKeyForMember(Context, Init);
5588 if (CheckRedundantInit(*this, Init, Members[Key]))
5589 HadError = true;
5590 } else {
5591 assert(Init->isDelegatingInitializer())(static_cast <bool> (Init->isDelegatingInitializer()
) ? void (0) : __assert_fail ("Init->isDelegatingInitializer()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 5591, __extension__ __PRETTY_FUNCTION__
))
;
5592 // This must be the only initializer
5593 if (MemInits.size() != 1) {
5594 Diag(Init->getSourceLocation(),
5595 diag::err_delegating_initializer_alone)
5596 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5597 // We will treat this as being the only initializer.
5598 }
5599 SetDelegatingInitializer(Constructor, MemInits[i]);
5600 // Return immediately as the initializer is set.
5601 return;
5602 }
5603 }
5604
5605 if (HadError)
5606 return;
5607
5608 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5609
5610 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5611
5612 DiagnoseUninitializedFields(*this, Constructor);
5613}
5614
5615void
5616Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5617 CXXRecordDecl *ClassDecl) {
5618 // Ignore dependent contexts. Also ignore unions, since their members never
5619 // have destructors implicitly called.
5620 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5621 return;
5622
5623 // FIXME: all the access-control diagnostics are positioned on the
5624 // field/base declaration. That's probably good; that said, the
5625 // user might reasonably want to know why the destructor is being
5626 // emitted, and we currently don't say.
5627
5628 // Non-static data members.
5629 for (auto *Field : ClassDecl->fields()) {
5630 if (Field->isInvalidDecl())
5631 continue;
5632
5633 // Don't destroy incomplete or zero-length arrays.
5634 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5635 continue;
5636
5637 QualType FieldType = Context.getBaseElementType(Field->getType());
5638
5639 const RecordType* RT = FieldType->getAs<RecordType>();
5640 if (!RT)
5641 continue;
5642
5643 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5644 if (FieldClassDecl->isInvalidDecl())
5645 continue;
5646 if (FieldClassDecl->hasIrrelevantDestructor())
5647 continue;
5648 // The destructor for an implicit anonymous union member is never invoked.
5649 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5650 continue;
5651
5652 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5653 assert(Dtor && "No dtor found for FieldClassDecl!")(static_cast <bool> (Dtor && "No dtor found for FieldClassDecl!"
) ? void (0) : __assert_fail ("Dtor && \"No dtor found for FieldClassDecl!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 5653, __extension__ __PRETTY_FUNCTION__
))
;
5654 CheckDestructorAccess(Field->getLocation(), Dtor,
5655 PDiag(diag::err_access_dtor_field)
5656 << Field->getDeclName()
5657 << FieldType);
5658
5659 MarkFunctionReferenced(Location, Dtor);
5660 DiagnoseUseOfDecl(Dtor, Location);
5661 }
5662
5663 // We only potentially invoke the destructors of potentially constructed
5664 // subobjects.
5665 bool VisitVirtualBases = !ClassDecl->isAbstract();
5666
5667 // If the destructor exists and has already been marked used in the MS ABI,
5668 // then virtual base destructors have already been checked and marked used.
5669 // Skip checking them again to avoid duplicate diagnostics.
5670 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5671 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5672 if (Dtor && Dtor->isUsed())
5673 VisitVirtualBases = false;
5674 }
5675
5676 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5677
5678 // Bases.
5679 for (const auto &Base : ClassDecl->bases()) {
5680 const RecordType *RT = Base.getType()->getAs<RecordType>();
5681 if (!RT)
5682 continue;
5683
5684 // Remember direct virtual bases.
5685 if (Base.isVirtual()) {
5686 if (!VisitVirtualBases)
5687 continue;
5688 DirectVirtualBases.insert(RT);
5689 }
5690
5691 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5692 // If our base class is invalid, we probably can't get its dtor anyway.
5693 if (BaseClassDecl->isInvalidDecl())
5694 continue;
5695 if (BaseClassDecl->hasIrrelevantDestructor())
5696 continue;
5697
5698 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5699 assert(Dtor && "No dtor found for BaseClassDecl!")(static_cast <bool> (Dtor && "No dtor found for BaseClassDecl!"
) ? void (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 5699, __extension__ __PRETTY_FUNCTION__
))
;
5700
5701 // FIXME: caret should be on the start of the class name
5702 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5703 PDiag(diag::err_access_dtor_base)
5704 << Base.getType() << Base.getSourceRange(),
5705 Context.getTypeDeclType(ClassDecl));
5706
5707 MarkFunctionReferenced(Location, Dtor);
5708 DiagnoseUseOfDecl(Dtor, Location);
5709 }
5710
5711 if (VisitVirtualBases)
5712 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5713 &DirectVirtualBases);
5714}
5715
5716void Sema::MarkVirtualBaseDestructorsReferenced(
5717 SourceLocation Location, CXXRecordDecl *ClassDecl,
5718 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5719 // Virtual bases.
5720 for (const auto &VBase : ClassDecl->vbases()) {
5721 // Bases are always records in a well-formed non-dependent class.
5722 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5723
5724 // Ignore already visited direct virtual bases.
5725 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5726 continue;
5727
5728 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5729 // If our base class is invalid, we probably can't get its dtor anyway.
5730 if (BaseClassDecl->isInvalidDecl())
5731 continue;
5732 if (BaseClassDecl->hasIrrelevantDestructor())
5733 continue;
5734
5735 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5736 assert(Dtor && "No dtor found for BaseClassDecl!")(static_cast <bool> (Dtor && "No dtor found for BaseClassDecl!"
) ? void (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 5736, __extension__ __PRETTY_FUNCTION__
))
;
5737 if (CheckDestructorAccess(
5738 ClassDecl->getLocation(), Dtor,
5739 PDiag(diag::err_access_dtor_vbase)
5740 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5741 Context.getTypeDeclType(ClassDecl)) ==
5742 AR_accessible) {
5743 CheckDerivedToBaseConversion(
5744 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5745 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5746 SourceRange(), DeclarationName(), nullptr);
5747 }
5748
5749 MarkFunctionReferenced(Location, Dtor);
5750 DiagnoseUseOfDecl(Dtor, Location);
5751 }
5752}
5753
5754void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5755 if (!CDtorDecl)
5756 return;
5757
5758 if (CXXConstructorDecl *Constructor
5759 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5760 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5761 DiagnoseUninitializedFields(*this, Constructor);
5762 }
5763}
5764
5765bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5766 if (!getLangOpts().CPlusPlus)
5767 return false;
5768
5769 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5770 if (!RD)
5771 return false;
5772
5773 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5774 // class template specialization here, but doing so breaks a lot of code.
5775
5776 // We can't answer whether something is abstract until it has a
5777 // definition. If it's currently being defined, we'll walk back
5778 // over all the declarations when we have a full definition.
5779 const CXXRecordDecl *Def = RD->getDefinition();
5780 if (!Def || Def->isBeingDefined())
5781 return false;
5782
5783 return RD->isAbstract();
5784}
5785
5786bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5787 TypeDiagnoser &Diagnoser) {
5788 if (!isAbstractType(Loc, T))
5789 return false;
5790
5791 T = Context.getBaseElementType(T);
5792 Diagnoser.diagnose(*this, Loc, T);
5793 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5794 return true;
5795}
5796
5797void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5798 // Check if we've already emitted the list of pure virtual functions
5799 // for this class.
5800 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5801 return;
5802
5803 // If the diagnostic is suppressed, don't emit the notes. We're only
5804 // going to emit them once, so try to attach them to a diagnostic we're
5805 // actually going to show.
5806 if (Diags.isLastDiagnosticIgnored())
5807 return;
5808
5809 CXXFinalOverriderMap FinalOverriders;
5810 RD->getFinalOverriders(FinalOverriders);
5811
5812 // Keep a set of seen pure methods so we won't diagnose the same method
5813 // more than once.
5814 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5815
5816 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5817 MEnd = FinalOverriders.end();
5818 M != MEnd;
5819 ++M) {
5820 for (OverridingMethods::iterator SO = M->second.begin(),
5821 SOEnd = M->second.end();
5822 SO != SOEnd; ++SO) {
5823 // C++ [class.abstract]p4:
5824 // A class is abstract if it contains or inherits at least one
5825 // pure virtual function for which the final overrider is pure
5826 // virtual.
5827
5828 //
5829 if (SO->second.size() != 1)
5830 continue;
5831
5832 if (!SO->second.front().Method->isPure())
5833 continue;
5834
5835 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5836 continue;
5837
5838 Diag(SO->second.front().Method->getLocation(),
5839 diag::note_pure_virtual_function)
5840 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5841 }
5842 }
5843
5844 if (!PureVirtualClassDiagSet)
5845 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5846 PureVirtualClassDiagSet->insert(RD);
5847}
5848
5849namespace {
5850struct AbstractUsageInfo {
5851 Sema &S;
5852 CXXRecordDecl *Record;
5853 CanQualType AbstractType;
5854 bool Invalid;
5855
5856 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5857 : S(S), Record(Record),
5858 AbstractType(S.Context.getCanonicalType(
5859 S.Context.getTypeDeclType(Record))),
5860 Invalid(false) {}
5861
5862 void DiagnoseAbstractType() {
5863 if (Invalid) return;
5864 S.DiagnoseAbstractType(Record);
5865 Invalid = true;
5866 }
5867
5868 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5869};
5870
5871struct CheckAbstractUsage {
5872 AbstractUsageInfo &Info;
5873 const NamedDecl *Ctx;
5874
5875 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5876 : Info(Info), Ctx(Ctx) {}
5877
5878 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5879 switch (TL.getTypeLocClass()) {
5880#define ABSTRACT_TYPELOC(CLASS, PARENT)
5881#define TYPELOC(CLASS, PARENT) \
5882 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5883#include "clang/AST/TypeLocNodes.def"
5884 }
5885 }
5886
5887 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5888 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5889 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5890 if (!TL.getParam(I))
5891 continue;
5892
5893 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5894 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5895 }
5896 }
5897
5898 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5899 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5900 }
5901
5902 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5903 // Visit the type parameters from a permissive context.
5904 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5905 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5906 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5907 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5908 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5909 // TODO: other template argument types?
5910 }
5911 }
5912
5913 // Visit pointee types from a permissive context.
5914#define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc
(), Sema::AbstractNone); }
\
5915 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5916 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5917 }
5918 CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5919 CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5920 CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5921 CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5922 CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5923
5924 /// Handle all the types we haven't given a more specific
5925 /// implementation for above.
5926 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5927 // Every other kind of type that we haven't called out already
5928 // that has an inner type is either (1) sugar or (2) contains that
5929 // inner type in some way as a subobject.
5930 if (TypeLoc Next = TL.getNextTypeLoc())
5931 return Visit(Next, Sel);
5932
5933 // If there's no inner type and we're in a permissive context,
5934 // don't diagnose.
5935 if (Sel == Sema::AbstractNone) return;
5936
5937 // Check whether the type matches the abstract type.
5938 QualType T = TL.getType();
5939 if (T->isArrayType()) {
5940 Sel = Sema::AbstractArrayType;
5941 T = Info.S.Context.getBaseElementType(T);
5942 }
5943 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5944 if (CT != Info.AbstractType) return;
5945
5946 // It matched; do some magic.
5947 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
5948 if (Sel == Sema::AbstractArrayType) {
5949 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5950 << T << TL.getSourceRange();
5951 } else {
5952 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5953 << Sel << T << TL.getSourceRange();
5954 }
5955 Info.DiagnoseAbstractType();
5956 }
5957};
5958
5959void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5960 Sema::AbstractDiagSelID Sel) {
5961 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5962}
5963
5964}
5965
5966/// Check for invalid uses of an abstract type in a function declaration.
5967static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5968 FunctionDecl *FD) {
5969 // No need to do the check on definitions, which require that
5970 // the return/param types be complete.
5971 if (FD->doesThisDeclarationHaveABody())
5972 return;
5973
5974 // For safety's sake, just ignore it if we don't have type source
5975 // information. This should never happen for non-implicit methods,
5976 // but...
5977 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5978 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
5979}
5980
5981/// Check for invalid uses of an abstract type in a variable0 declaration.
5982static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5983 VarDecl *VD) {
5984 // No need to do the check on definitions, which require that
5985 // the type is complete.
5986 if (VD->isThisDeclarationADefinition())
5987 return;
5988
5989 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
5990 Sema::AbstractVariableType);
5991}
5992
5993/// Check for invalid uses of an abstract type within a class definition.
5994static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5995 CXXRecordDecl *RD) {
5996 for (auto *D : RD->decls()) {
5997 if (D->isImplicit()) continue;
5998
5999 // Step through friends to the befriended declaration.
6000 if (auto *FD = dyn_cast<FriendDecl>(D)) {
6001 D = FD->getFriendDecl();
6002 if (!D) continue;
6003 }
6004
6005 // Functions and function templates.
6006 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6007 CheckAbstractClassUsage(Info, FD);
6008 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6009 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6010
6011 // Fields and static variables.
6012 } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6013 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6014 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6015 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6016 CheckAbstractClassUsage(Info, VD);
6017 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6018 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6019
6020 // Nested classes and class templates.
6021 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6022 CheckAbstractClassUsage(Info, RD);
6023 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6024 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6025 }
6026 }
6027}
6028
6029static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6030 Attr *ClassAttr = getDLLAttr(Class);
6031 if (!ClassAttr)
6032 return;
6033
6034 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", 6034, __extension__ __PRETTY_FUNCTION__
))
;
6035
6036 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6037
6038 if (TSK == TSK_ExplicitInstantiationDeclaration)
6039 // Don't go any further if this is just an explicit instantiation
6040 // declaration.
6041 return;
6042
6043 // Add a context note to explain how we got to any diagnostics produced below.
6044 struct MarkingClassDllexported {
6045 Sema &S;
6046 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6047 SourceLocation AttrLoc)
6048 : S(S) {
6049 Sema::CodeSynthesisContext Ctx;
6050 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6051 Ctx.PointOfInstantiation = AttrLoc;
6052 Ctx.Entity = Class;
6053 S.pushCodeSynthesisContext(Ctx);
6054 }
6055 ~MarkingClassDllexported() {
6056 S.popCodeSynthesisContext();
6057 }
6058 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6059
6060 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6061 S.MarkVTableUsed(Class->getLocation(), Class, true);
6062
6063 for (Decl *Member : Class->decls()) {
6064 // Skip members that were not marked exported.
6065 if (!Member->hasAttr<DLLExportAttr>())
6066 continue;
6067
6068 // Defined static variables that are members of an exported base
6069 // class must be marked export too.
6070 auto *VD = dyn_cast<VarDecl>(Member);
6071 if (VD && VD->getStorageClass() == SC_Static &&
6072 TSK == TSK_ImplicitInstantiation)
6073 S.MarkVariableReferenced(VD->getLocation(), VD);
6074
6075 auto *MD = dyn_cast<CXXMethodDecl>(Member);
6076 if (!MD)
6077 continue;
6078
6079 if (MD->isUserProvided()) {
6080 // Instantiate non-default class member functions ...
6081
6082 // .. except for certain kinds of template specializations.
6083 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6084 continue;
6085
6086 // If this is an MS ABI dllexport default constructor, instantiate any
6087 // default arguments.
6088 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6089 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6090 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6091 S.InstantiateDefaultCtorDefaultArgs(CD);
6092 }
6093 }
6094
6095 S.MarkFunctionReferenced(Class->getLocation(), MD);
6096
6097 // The function will be passed to the consumer when its definition is
6098 // encountered.
6099 } else if (MD->isExplicitlyDefaulted()) {
6100 // Synthesize and instantiate explicitly defaulted methods.
6101 S.MarkFunctionReferenced(Class->getLocation(), MD);
6102
6103 if (TSK != TSK_ExplicitInstantiationDefinition) {
6104 // Except for explicit instantiation defs, we will not see the
6105 // definition again later, so pass it to the consumer now.
6106 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6107 }
6108 } else if (!MD->isTrivial() ||
6109 MD->isCopyAssignmentOperator() ||
6110 MD->isMoveAssignmentOperator()) {
6111 // Synthesize and instantiate non-trivial implicit methods, and the copy
6112 // and move assignment operators. The latter are exported even if they
6113 // are trivial, because the address of an operator can be taken and
6114 // should compare equal across libraries.
6115 S.MarkFunctionReferenced(Class->getLocation(), MD);
6116
6117 // There is no later point when we will see the definition of this
6118 // function, so pass it to the consumer now.
6119 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6120 }
6121 }
6122}
6123
6124static void checkForMultipleExportedDefaultConstructors(Sema &S,
6125 CXXRecordDecl *Class) {
6126 // Only the MS ABI has default constructor closures, so we don't need to do
6127 // this semantic checking anywhere else.
6128 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6129 return;
6130
6131 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6132 for (Decl *Member : Class->decls()) {
6133 // Look for exported default constructors.
6134 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6135 if (!CD || !CD->isDefaultConstructor())
6136 continue;
6137 auto *Attr = CD->getAttr<DLLExportAttr>();
6138 if (!Attr)
6139 continue;
6140
6141 // If the class is non-dependent, mark the default arguments as ODR-used so
6142 // that we can properly codegen the constructor closure.
6143 if (!Class->isDependentContext()) {
6144 for (ParmVarDecl *PD : CD->parameters()) {
6145 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6146 S.DiscardCleanupsInEvaluationContext();
6147 }
6148 }
6149
6150 if (LastExportedDefaultCtor) {
6151 S.Diag(LastExportedDefaultCtor->getLocation(),
6152 diag::err_attribute_dll_ambiguous_default_ctor)
6153 << Class;
6154 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6155 << CD->getDeclName();
6156 return;
6157 }
6158 LastExportedDefaultCtor = CD;
6159 }
6160}
6161
6162static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6163 CXXRecordDecl *Class) {
6164 bool ErrorReported = false;
6165 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6166 ClassTemplateDecl *TD) {
6167 if (ErrorReported)
6168 return;
6169 S.Diag(TD->getLocation(),
6170 diag::err_cuda_device_builtin_surftex_cls_template)
6171 << /*surface*/ 0 << TD;
6172 ErrorReported = true;
6173 };
6174
6175 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6176 if (!TD) {
6177 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6178 if (!SD) {
6179 S.Diag(Class->getLocation(),
6180 diag::err_cuda_device_builtin_surftex_ref_decl)
6181 << /*surface*/ 0 << Class;
6182 S.Diag(Class->getLocation(),
6183 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6184 << Class;
6185 return;
6186 }
6187 TD = SD->getSpecializedTemplate();
6188 }
6189
6190 TemplateParameterList *Params = TD->getTemplateParameters();
6191 unsigned N = Params->size();
6192
6193 if (N != 2) {
6194 reportIllegalClassTemplate(S, TD);
6195 S.Diag(TD->getLocation(),
6196 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6197 << TD << 2;
6198 }
6199 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6200 reportIllegalClassTemplate(S, TD);
6201 S.Diag(TD->getLocation(),
6202 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6203 << TD << /*1st*/ 0 << /*type*/ 0;
6204 }
6205 if (N > 1) {
6206 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6207 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6208 reportIllegalClassTemplate(S, TD);
6209 S.Diag(TD->getLocation(),
6210 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6211 << TD << /*2nd*/ 1 << /*integer*/ 1;
6212 }
6213 }
6214}
6215
6216static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6217 CXXRecordDecl *Class) {
6218 bool ErrorReported = false;
6219 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6220 ClassTemplateDecl *TD) {
6221 if (ErrorReported)
6222 return;
6223 S.Diag(TD->getLocation(),
6224 diag::err_cuda_device_builtin_surftex_cls_template)
6225 << /*texture*/ 1 << TD;
6226 ErrorReported = true;
6227 };
6228
6229 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6230 if (!TD) {
6231 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6232 if (!SD) {
6233 S.Diag(Class->getLocation(),
6234 diag::err_cuda_device_builtin_surftex_ref_decl)
6235 << /*texture*/ 1 << Class;
6236 S.Diag(Class->getLocation(),
6237 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6238 << Class;
6239 return;
6240 }
6241 TD = SD->getSpecializedTemplate();
6242 }
6243
6244 TemplateParameterList *Params = TD->getTemplateParameters();
6245 unsigned N = Params->size();
6246
6247 if (N != 3) {
6248 reportIllegalClassTemplate(S, TD);
6249 S.Diag(TD->getLocation(),
6250 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6251 << TD << 3;
6252 }
6253 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6254 reportIllegalClassTemplate(S, TD);
6255 S.Diag(TD->getLocation(),
6256 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6257 << TD << /*1st*/ 0 << /*type*/ 0;
6258 }
6259 if (N > 1) {
6260 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6261 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6262 reportIllegalClassTemplate(S, TD);
6263 S.Diag(TD->getLocation(),
6264 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6265 << TD << /*2nd*/ 1 << /*integer*/ 1;
6266 }
6267 }
6268 if (N > 2) {
6269 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6270 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6271 reportIllegalClassTemplate(S, TD);
6272 S.Diag(TD->getLocation(),
6273 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6274 << TD << /*3rd*/ 2 << /*integer*/ 1;
6275 }
6276 }
6277}
6278
6279void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6280 // Mark any compiler-generated routines with the implicit code_seg attribute.
6281 for (auto *Method : Class->methods()) {
6282 if (Method->isUserProvided())
6283 continue;
6284 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6285 Method->addAttr(A);
6286 }
6287}
6288
6289/// Check class-level dllimport/dllexport attribute.
6290void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6291 Attr *ClassAttr = getDLLAttr(Class);
6292
6293 // MSVC inherits DLL attributes to partial class template specializations.
6294 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6295 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6296 if (Attr *TemplateAttr =
6297 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6298 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6299 A->setInherited(true);
6300 ClassAttr = A;
6301 }
6302 }
6303 }
6304
6305 if (!ClassAttr)
6306 return;
6307
6308 if (!Class->isExternallyVisible()) {
6309 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6310 << Class << ClassAttr;
6311 return;
6312 }
6313
6314 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6315 !ClassAttr->isInherited()) {
6316 // Diagnose dll attributes on members of class with dll attribute.
6317 for (Decl *Member : Class->decls()) {
6318 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6319 continue;
6320 InheritableAttr *MemberAttr = getDLLAttr(Member);
6321 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6322 continue;
6323
6324 Diag(MemberAttr->getLocation(),
6325 diag::err_attribute_dll_member_of_dll_class)
6326 << MemberAttr << ClassAttr;
6327 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6328 Member->setInvalidDecl();
6329 }
6330 }
6331
6332 if (Class->getDescribedClassTemplate())
6333 // Don't inherit dll attribute until the template is instantiated.
6334 return;
6335
6336 // The class is either imported or exported.
6337 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6338
6339 // Check if this was a dllimport attribute propagated from a derived class to
6340 // a base class template specialization. We don't apply these attributes to
6341 // static data members.
6342 const bool PropagatedImport =
6343 !ClassExported &&
6344 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6345
6346 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6347
6348 // Ignore explicit dllexport on explicit class template instantiation
6349 // declarations, except in MinGW mode.
6350 if (ClassExported && !ClassAttr->isInherited() &&
6351 TSK == TSK_ExplicitInstantiationDeclaration &&
6352 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6353 Class->dropAttr<DLLExportAttr>();
6354 return;
6355 }
6356
6357 // Force declaration of implicit members so they can inherit the attribute.
6358 ForceDeclarationOfImplicitMembers(Class);
6359
6360 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6361 // seem to be true in practice?
6362
6363 for (Decl *Member : Class->decls()) {
6364 VarDecl *VD = dyn_cast<VarDecl>(Member);
6365 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6366
6367 // Only methods and static fields inherit the attributes.
6368 if (!VD && !MD)
6369 continue;
6370
6371 if (MD) {
6372 // Don't process deleted methods.
6373 if (MD->isDeleted())
6374 continue;
6375
6376 if (MD->isInlined()) {
6377 // MinGW does not import or export inline methods. But do it for
6378 // template instantiations.
6379 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6380 TSK != TSK_ExplicitInstantiationDeclaration &&
6381 TSK != TSK_ExplicitInstantiationDefinition)
6382 continue;
6383
6384 // MSVC versions before 2015 don't export the move assignment operators
6385 // and move constructor, so don't attempt to import/export them if
6386 // we have a definition.
6387 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6388 if ((MD->isMoveAssignmentOperator() ||
6389 (Ctor && Ctor->isMoveConstructor())) &&
6390 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6391 continue;
6392
6393 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6394 // operator is exported anyway.
6395 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6396 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6397 continue;
6398 }
6399 }
6400
6401 // Don't apply dllimport attributes to static data members of class template
6402 // instantiations when the attribute is propagated from a derived class.
6403 if (VD && PropagatedImport)
6404 continue;
6405
6406 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6407 continue;
6408
6409 if (!getDLLAttr(Member)) {
6410 InheritableAttr *NewAttr = nullptr;
6411
6412 // Do not export/import inline function when -fno-dllexport-inlines is
6413 // passed. But add attribute for later local static var check.
6414 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6415 TSK != TSK_ExplicitInstantiationDeclaration &&
6416 TSK != TSK_ExplicitInstantiationDefinition) {
6417 if (ClassExported) {
6418 NewAttr = ::new (getASTContext())
6419 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6420 } else {
6421 NewAttr = ::new (getASTContext())
6422 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6423 }
6424 } else {
6425 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6426 }
6427
6428 NewAttr->setInherited(true);
6429 Member->addAttr(NewAttr);
6430
6431 if (MD) {
6432 // Propagate DLLAttr to friend re-declarations of MD that have already
6433 // been constructed.
6434 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6435 FD = FD->getPreviousDecl()) {
6436 if (FD->getFriendObjectKind() == Decl::FOK_None)
6437 continue;
6438 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", 6439, __extension__ __PRETTY_FUNCTION__
))
6439 "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", 6439, __extension__ __PRETTY_FUNCTION__
))
;
6440 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6441 NewAttr->setInherited(true);
6442 FD->addAttr(NewAttr);
6443 }
6444 }
6445 }
6446 }
6447
6448 if (ClassExported)
6449 DelayedDllExportClasses.push_back(Class);
6450}
6451
6452/// Perform propagation of DLL attributes from a derived class to a
6453/// templated base class for MS compatibility.
6454void Sema::propagateDLLAttrToBaseClassTemplate(
6455 CXXRecordDecl *Class, Attr *ClassAttr,
6456 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6457 if (getDLLAttr(
6458 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6459 // If the base class template has a DLL attribute, don't try to change it.
6460 return;
6461 }
6462
6463 auto TSK = BaseTemplateSpec->getSpecializationKind();
6464 if (!getDLLAttr(BaseTemplateSpec) &&
6465 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6466 TSK == TSK_ImplicitInstantiation)) {
6467 // The template hasn't been instantiated yet (or it has, but only as an
6468 // explicit instantiation declaration or implicit instantiation, which means
6469 // we haven't codegenned any members yet), so propagate the attribute.
6470 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6471 NewAttr->setInherited(true);
6472 BaseTemplateSpec->addAttr(NewAttr);
6473
6474 // If this was an import, mark that we propagated it from a derived class to
6475 // a base class template specialization.
6476 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6477 ImportAttr->setPropagatedToBaseTemplate();
6478
6479 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6480 // needs to be run again to work see the new attribute. Otherwise this will
6481 // get run whenever the template is instantiated.
6482 if (TSK != TSK_Undeclared)
6483 checkClassLevelDLLAttribute(BaseTemplateSpec);
6484
6485 return;
6486 }
6487
6488 if (getDLLAttr(BaseTemplateSpec)) {
6489 // The template has already been specialized or instantiated with an
6490 // attribute, explicitly or through propagation. We should not try to change
6491 // it.
6492 return;
6493 }
6494
6495 // The template was previously instantiated or explicitly specialized without
6496 // a dll attribute, It's too late for us to add an attribute, so warn that
6497 // this is unsupported.
6498 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6499 << BaseTemplateSpec->isExplicitSpecialization();
6500 Diag(ClassAttr->getLocation(), diag::note_attribute);
6501 if (BaseTemplateSpec->isExplicitSpecialization()) {
6502 Diag(BaseTemplateSpec->getLocation(),
6503 diag::note_template_class_explicit_specialization_was_here)
6504 << BaseTemplateSpec;
6505 } else {
6506 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6507 diag::note_template_class_instantiation_was_here)
6508 << BaseTemplateSpec;
6509 }
6510}
6511
6512/// Determine the kind of defaulting that would be done for a given function.
6513///
6514/// If the function is both a default constructor and a copy / move constructor
6515/// (due to having a default argument for the first parameter), this picks
6516/// CXXDefaultConstructor.
6517///
6518/// FIXME: Check that case is properly handled by all callers.
6519Sema::DefaultedFunctionKind
6520Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6521 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6522 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6523 if (Ctor->isDefaultConstructor())
6524 return Sema::CXXDefaultConstructor;
6525
6526 if (Ctor->isCopyConstructor())
6527 return Sema::CXXCopyConstructor;
6528
6529 if (Ctor->isMoveConstructor())
6530 return Sema::CXXMoveConstructor;
6531 }
6532
6533 if (MD->isCopyAssignmentOperator())
6534 return Sema::CXXCopyAssignment;
6535
6536 if (MD->isMoveAssignmentOperator())
6537 return Sema::CXXMoveAssignment;
6538
6539 if (isa<CXXDestructorDecl>(FD))
6540 return Sema::CXXDestructor;
6541 }
6542
6543 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6544 case OO_EqualEqual:
6545 return DefaultedComparisonKind::Equal;
6546
6547 case OO_ExclaimEqual:
6548 return DefaultedComparisonKind::NotEqual;
6549
6550 case OO_Spaceship:
6551 // No point allowing this if <=> doesn't exist in the current language mode.
6552 if (!getLangOpts().CPlusPlus20)
6553 break;
6554 return DefaultedComparisonKind::ThreeWay;
6555
6556 case OO_Less:
6557 case OO_LessEqual:
6558 case OO_Greater:
6559 case OO_GreaterEqual:
6560 // No point allowing this if <=> doesn't exist in the current language mode.
6561 if (!getLangOpts().CPlusPlus20)
6562 break;
6563 return DefaultedComparisonKind::Relational;
6564
6565 default:
6566 break;
6567 }
6568
6569 // Not defaultable.
6570 return DefaultedFunctionKind();
6571}
6572
6573static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6574 SourceLocation DefaultLoc) {
6575 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6576 if (DFK.isComparison())
6577 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6578
6579 switch (DFK.asSpecialMember()) {
6580 case Sema::CXXDefaultConstructor:
6581 S.DefineImplicitDefaultConstructor(DefaultLoc,
6582 cast<CXXConstructorDecl>(FD));
6583 break;
6584 case Sema::CXXCopyConstructor:
6585 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6586 break;
6587 case Sema::CXXCopyAssignment:
6588 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6589 break;
6590 case Sema::CXXDestructor:
6591 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6592 break;
6593 case Sema::CXXMoveConstructor:
6594 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6595 break;
6596 case Sema::CXXMoveAssignment:
6597 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6598 break;
6599 case Sema::CXXInvalid:
6600 llvm_unreachable("Invalid special member.")::llvm::llvm_unreachable_internal("Invalid special member.", "clang/lib/Sema/SemaDeclCXX.cpp"
, 6600)
;
6601 }
6602}
6603
6604/// Determine whether a type is permitted to be passed or returned in
6605/// registers, per C++ [class.temporary]p3.
6606static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6607 TargetInfo::CallingConvKind CCK) {
6608 if (D->isDependentType() || D->isInvalidDecl())
6609 return false;
6610
6611 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6612 // The PS4 platform ABI follows the behavior of Clang 3.2.
6613 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6614 return !D->hasNonTrivialDestructorForCall() &&
6615 !D->hasNonTrivialCopyConstructorForCall();
6616
6617 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6618 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6619 bool DtorIsTrivialForCall = false;
6620
6621 // If a class has at least one eligible, trivial copy constructor, it
6622 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6623 //
6624 // Note: This permits classes with non-trivial copy or move ctors to be
6625 // passed in registers, so long as they *also* have a trivial copy ctor,
6626 // which is non-conforming.
6627 if (D->needsImplicitCopyConstructor()) {
6628 if (!D->defaultedCopyConstructorIsDeleted()) {
6629 if (D->hasTrivialCopyConstructor())
6630 CopyCtorIsTrivial = true;
6631 if (D->hasTrivialCopyConstructorForCall())
6632 CopyCtorIsTrivialForCall = true;
6633 }
6634 } else {
6635 for (const CXXConstructorDecl *CD : D->ctors()) {
6636 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6637 !CD->isIneligibleOrNotSelected()) {
6638 if (CD->isTrivial())
6639 CopyCtorIsTrivial = true;
6640 if (CD->isTrivialForCall())
6641 CopyCtorIsTrivialForCall = true;
6642 }
6643 }
6644 }
6645
6646 if (D->needsImplicitDestructor()) {
6647 if (!D->defaultedDestructorIsDeleted() &&
6648 D->hasTrivialDestructorForCall())
6649 DtorIsTrivialForCall = true;
6650 } else if (const auto *DD = D->getDestructor()) {
6651 if (!DD->isDeleted() && DD->isTrivialForCall())
6652 DtorIsTrivialForCall = true;
6653 }
6654
6655 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6656 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6657 return true;
6658
6659 // If a class has a destructor, we'd really like to pass it indirectly
6660 // because it allows us to elide copies. Unfortunately, MSVC makes that
6661 // impossible for small types, which it will pass in a single register or
6662 // stack slot. Most objects with dtors are large-ish, so handle that early.
6663 // We can't call out all large objects as being indirect because there are
6664 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6665 // how we pass large POD types.
6666
6667 // Note: This permits small classes with nontrivial destructors to be
6668 // passed in registers, which is non-conforming.
6669 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6670 uint64_t TypeSize = isAArch64 ? 128 : 64;
6671
6672 if (CopyCtorIsTrivial &&
6673 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6674 return true;
6675 return false;
6676 }
6677
6678 // Per C++ [class.temporary]p3, the relevant condition is:
6679 // each copy constructor, move constructor, and destructor of X is
6680 // either trivial or deleted, and X has at least one non-deleted copy
6681 // or move constructor
6682 bool HasNonDeletedCopyOrMove = false;
6683
6684 if (D->needsImplicitCopyConstructor() &&
6685 !D->defaultedCopyConstructorIsDeleted()) {
6686 if (!D->hasTrivialCopyConstructorForCall())
6687 return false;
6688 HasNonDeletedCopyOrMove = true;
6689 }
6690
6691 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6692 !D->defaultedMoveConstructorIsDeleted()) {
6693 if (!D->hasTrivialMoveConstructorForCall())
6694 return false;
6695 HasNonDeletedCopyOrMove = true;
6696 }
6697
6698 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6699 !D->hasTrivialDestructorForCall())
6700 return false;
6701
6702 for (const CXXMethodDecl *MD : D->methods()) {
6703 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6704 continue;
6705
6706 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6707 if (CD && CD->isCopyOrMoveConstructor())
6708 HasNonDeletedCopyOrMove = true;
6709 else if (!isa<CXXDestructorDecl>(MD))
6710 continue;
6711
6712 if (!MD->isTrivialForCall())
6713 return false;
6714 }
6715
6716 return HasNonDeletedCopyOrMove;
6717}
6718
6719/// Report an error regarding overriding, along with any relevant
6720/// overridden methods.
6721///
6722/// \param DiagID the primary error to report.
6723/// \param MD the overriding method.
6724static bool
6725ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6726 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6727 bool IssuedDiagnostic = false;
6728 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6729 if (Report(O)) {
6730 if (!IssuedDiagnostic) {
6731 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6732 IssuedDiagnostic = true;
6733 }
6734 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6735 }
6736 }
6737 return IssuedDiagnostic;
6738}
6739
6740/// Perform semantic checks on a class definition that has been
6741/// completing, introducing implicitly-declared members, checking for
6742/// abstract types, etc.
6743///
6744/// \param S The scope in which the class was parsed. Null if we didn't just
6745/// parse a class definition.
6746/// \param Record The completed class.
6747void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6748 if (!Record)
6749 return;
6750
6751 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6752 AbstractUsageInfo Info(*this, Record);
6753 CheckAbstractClassUsage(Info, Record);
6754 }
6755
6756 // If this is not an aggregate type and has no user-declared constructor,
6757 // complain about any non-static data members of reference or const scalar
6758 // type, since they will never get initializers.
6759 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6760 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6761 !Record->isLambda()) {
6762 bool Complained = false;
6763 for (const auto *F : Record->fields()) {
6764 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6765 continue;
6766
6767 if (F->getType()->isReferenceType() ||
6768 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6769 if (!Complained) {
6770 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6771 << Record->getTagKind() << Record;
6772 Complained = true;
6773 }
6774
6775 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6776 << F->getType()->isReferenceType()
6777 << F->getDeclName();
6778 }
6779 }
6780 }
6781
6782 if (Record->getIdentifier()) {
6783 // C++ [class.mem]p13:
6784 // If T is the name of a class, then each of the following shall have a
6785 // name different from T:
6786 // - every member of every anonymous union that is a member of class T.
6787 //
6788 // C++ [class.mem]p14:
6789 // In addition, if class T has a user-declared constructor (12.1), every
6790 // non-static data member of class T shall have a name different from T.
6791 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6792 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6793 ++I) {
6794 NamedDecl *D = (*I)->getUnderlyingDecl();
6795 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6796 Record->hasUserDeclaredConstructor()) ||
6797 isa<IndirectFieldDecl>(D)) {
6798 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6799 << D->getDeclName();
6800 break;
6801 }
6802 }
6803 }
6804
6805 // Warn if the class has virtual methods but non-virtual public destructor.
6806 if (Record->isPolymorphic() && !Record->isDependentType()) {
6807 CXXDestructorDecl *dtor = Record->getDestructor();
6808 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6809 !Record->hasAttr<FinalAttr>())
6810 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6811 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6812 }
6813
6814 if (Record->isAbstract()) {
6815 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6816 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6817 << FA->isSpelledAsSealed();
6818 DiagnoseAbstractType(Record);
6819 }
6820 }
6821
6822 // Warn if the class has a final destructor but is not itself marked final.
6823 if (!Record->hasAttr<FinalAttr>()) {
6824 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6825 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6826 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6827 << FA->isSpelledAsSealed()
6828 << FixItHint::CreateInsertion(
6829 getLocForEndOfToken(Record->getLocation()),
6830 (FA->isSpelledAsSealed() ? " sealed" : " final"));
6831 Diag(Record->getLocation(),
6832 diag::note_final_dtor_non_final_class_silence)
6833 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6834 }
6835 }
6836 }
6837
6838 // See if trivial_abi has to be dropped.
6839 if (Record->hasAttr<TrivialABIAttr>())
6840 checkIllFormedTrivialABIStruct(*Record);
6841
6842 // Set HasTrivialSpecialMemberForCall if the record has attribute
6843 // "trivial_abi".
6844 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6845
6846 if (HasTrivialABI)
6847 Record->setHasTrivialSpecialMemberForCall();
6848
6849 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6850 // We check these last because they can depend on the properties of the
6851 // primary comparison functions (==, <=>).
6852 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6853
6854 // Perform checks that can't be done until we know all the properties of a
6855 // member function (whether it's defaulted, deleted, virtual, overriding,
6856 // ...).
6857 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6858 // A static function cannot override anything.
6859 if (MD->getStorageClass() == SC_Static) {
6860 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6861 [](const CXXMethodDecl *) { return true; }))
6862 return;
6863 }
6864
6865 // A deleted function cannot override a non-deleted function and vice
6866 // versa.
6867 if (ReportOverrides(*this,
6868 MD->isDeleted() ? diag::err_deleted_override
6869 : diag::err_non_deleted_override,
6870 MD, [&](const CXXMethodDecl *V) {
6871 return MD->isDeleted() != V->isDeleted();
6872 })) {
6873 if (MD->isDefaulted() && MD->isDeleted())
6874 // Explain why this defaulted function was deleted.
6875 DiagnoseDeletedDefaultedFunction(MD);
6876 return;
6877 }
6878
6879 // A consteval function cannot override a non-consteval function and vice
6880 // versa.
6881 if (ReportOverrides(*this,
6882 MD->isConsteval() ? diag::err_consteval_override
6883 : diag::err_non_consteval_override,
6884 MD, [&](const CXXMethodDecl *V) {
6885 return MD->isConsteval() != V->isConsteval();
6886 })) {
6887 if (MD->isDefaulted() && MD->isDeleted())
6888 // Explain why this defaulted function was deleted.
6889 DiagnoseDeletedDefaultedFunction(MD);
6890 return;
6891 }
6892 };
6893
6894 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6895 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6896 return false;
6897
6898 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6899 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6900 DFK.asComparison() == DefaultedComparisonKind::Relational) {
6901 DefaultedSecondaryComparisons.push_back(FD);
6902 return true;
6903 }
6904
6905 CheckExplicitlyDefaultedFunction(S, FD);
6906 return false;
6907 };
6908
6909 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6910 // Check whether the explicitly-defaulted members are valid.
6911 bool Incomplete = CheckForDefaultedFunction(M);
6912
6913 // Skip the rest of the checks for a member of a dependent class.
6914 if (Record->isDependentType())
6915 return;
6916
6917 // For an explicitly defaulted or deleted special member, we defer
6918 // determining triviality until the class is complete. That time is now!
6919 CXXSpecialMember CSM = getSpecialMember(M);
6920 if (!M->isImplicit() && !M->isUserProvided()) {
6921 if (CSM != CXXInvalid) {
6922 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6923 // Inform the class that we've finished declaring this member.
6924 Record->finishedDefaultedOrDeletedMember(M);
6925 M->setTrivialForCall(
6926 HasTrivialABI ||
6927 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6928 Record->setTrivialForCallFlags(M);
6929 }
6930 }
6931
6932 // Set triviality for the purpose of calls if this is a user-provided
6933 // copy/move constructor or destructor.
6934 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6935 CSM == CXXDestructor) && M->isUserProvided()) {
6936 M->setTrivialForCall(HasTrivialABI);
6937 Record->setTrivialForCallFlags(M);
6938 }
6939
6940 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6941 M->hasAttr<DLLExportAttr>()) {
6942 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6943 M->isTrivial() &&
6944 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6945 CSM == CXXDestructor))
6946 M->dropAttr<DLLExportAttr>();
6947
6948 if (M->hasAttr<DLLExportAttr>()) {
6949 // Define after any fields with in-class initializers have been parsed.
6950 DelayedDllExportMemberFunctions.push_back(M);
6951 }
6952 }
6953
6954 // Define defaulted constexpr virtual functions that override a base class
6955 // function right away.
6956 // FIXME: We can defer doing this until the vtable is marked as used.
6957 if (CSM != CXXInvalid && !M->isDeleted() && M->isDefaulted() &&
6958 M->isConstexpr() && M->size_overridden_methods())
6959 DefineDefaultedFunction(*this, M, M->getLocation());
6960
6961 if (!Incomplete)
6962 CheckCompletedMemberFunction(M);
6963 };
6964
6965 // Check the destructor before any other member function. We need to
6966 // determine whether it's trivial in order to determine whether the claas
6967 // type is a literal type, which is a prerequisite for determining whether
6968 // other special member functions are valid and whether they're implicitly
6969 // 'constexpr'.
6970 if (CXXDestructorDecl *Dtor = Record->getDestructor())
6971 CompleteMemberFunction(Dtor);
6972
6973 bool HasMethodWithOverrideControl = false,
6974 HasOverridingMethodWithoutOverrideControl = false;
6975 for (auto *D : Record->decls()) {
6976 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6977 // FIXME: We could do this check for dependent types with non-dependent
6978 // bases.
6979 if (!Record->isDependentType()) {
6980 // See if a method overloads virtual methods in a base
6981 // class without overriding any.
6982 if (!M->isStatic())
6983 DiagnoseHiddenVirtualMethods(M);
6984 if (M->hasAttr<OverrideAttr>())
6985 HasMethodWithOverrideControl = true;
6986 else if (M->size_overridden_methods() > 0)
6987 HasOverridingMethodWithoutOverrideControl = true;
6988 }
6989
6990 if (!isa<CXXDestructorDecl>(M))
6991 CompleteMemberFunction(M);
6992 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6993 CheckForDefaultedFunction(
6994 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6995 }
6996 }
6997
6998 if (HasOverridingMethodWithoutOverrideControl) {
6999 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7000 for (auto *M : Record->methods())
7001 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
7002 }
7003
7004 // Check the defaulted secondary comparisons after any other member functions.
7005 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7006 CheckExplicitlyDefaultedFunction(S, FD);
7007
7008 // If this is a member function, we deferred checking it until now.
7009 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7010 CheckCompletedMemberFunction(MD);
7011 }
7012
7013 // ms_struct is a request to use the same ABI rules as MSVC. Check
7014 // whether this class uses any C++ features that are implemented
7015 // completely differently in MSVC, and if so, emit a diagnostic.
7016 // That diagnostic defaults to an error, but we allow projects to
7017 // map it down to a warning (or ignore it). It's a fairly common
7018 // practice among users of the ms_struct pragma to mass-annotate
7019 // headers, sweeping up a bunch of types that the project doesn't
7020 // really rely on MSVC-compatible layout for. We must therefore
7021 // support "ms_struct except for C++ stuff" as a secondary ABI.
7022 // Don't emit this diagnostic if the feature was enabled as a
7023 // language option (as opposed to via a pragma or attribute), as
7024 // the option -mms-bitfields otherwise essentially makes it impossible
7025 // to build C++ code, unless this diagnostic is turned off.
7026 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7027 (Record->isPolymorphic() || Record->getNumBases())) {
7028 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7029 }
7030
7031 checkClassLevelDLLAttribute(Record);
7032 checkClassLevelCodeSegAttribute(Record);
7033
7034 bool ClangABICompat4 =
7035 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7036 TargetInfo::CallingConvKind CCK =
7037 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7038 bool CanPass = canPassInRegisters(*this, Record, CCK);
7039
7040 // Do not change ArgPassingRestrictions if it has already been set to
7041 // APK_CanNeverPassInRegs.
7042 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
7043 Record->setArgPassingRestrictions(CanPass
7044 ? RecordDecl::APK_CanPassInRegs
7045 : RecordDecl::APK_CannotPassInRegs);
7046
7047 // If canPassInRegisters returns true despite the record having a non-trivial
7048 // destructor, the record is destructed in the callee. This happens only when
7049 // the record or one of its subobjects has a field annotated with trivial_abi
7050 // or a field qualified with ObjC __strong/__weak.
7051 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7052 Record->setParamDestroyedInCallee(true);
7053 else if (Record->hasNonTrivialDestructor())
7054 Record->setParamDestroyedInCallee(CanPass);
7055
7056 if (getLangOpts().ForceEmitVTables) {
7057 // If we want to emit all the vtables, we need to mark it as used. This
7058 // is especially required for cases like vtable assumption loads.
7059 MarkVTableUsed(Record->getInnerLocStart(), Record);
7060 }
7061
7062 if (getLangOpts().CUDA) {
7063 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7064 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7065 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7066 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7067 }
7068}
7069
7070/// Look up the special member function that would be called by a special
7071/// member function for a subobject of class type.
7072///
7073/// \param Class The class type of the subobject.
7074/// \param CSM The kind of special member function.
7075/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7076/// \param ConstRHS True if this is a copy operation with a const object
7077/// on its RHS, that is, if the argument to the outer special member
7078/// function is 'const' and this is not a field marked 'mutable'.
7079static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7080 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7081 unsigned FieldQuals, bool ConstRHS) {
7082 unsigned LHSQuals = 0;
7083 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7084 LHSQuals = FieldQuals;
7085
7086 unsigned RHSQuals = FieldQuals;
7087 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7088 RHSQuals = 0;
7089 else if (ConstRHS)
7090 RHSQuals |= Qualifiers::Const;
7091
7092 return S.LookupSpecialMember(Class, CSM,
7093 RHSQuals & Qualifiers::Const,
7094 RHSQuals & Qualifiers::Volatile,
7095 false,
7096 LHSQuals & Qualifiers::Const,
7097 LHSQuals & Qualifiers::Volatile);
7098}
7099
7100class Sema::InheritedConstructorInfo {
7101 Sema &S;
7102 SourceLocation UseLoc;
7103
7104 /// A mapping from the base classes through which the constructor was
7105 /// inherited to the using shadow declaration in that base class (or a null
7106 /// pointer if the constructor was declared in that base class).
7107 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7108 InheritedFromBases;
7109
7110public:
7111 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7112 ConstructorUsingShadowDecl *Shadow)
7113 : S(S), UseLoc(UseLoc) {
7114 bool DiagnosedMultipleConstructedBases = false;
7115 CXXRecordDecl *ConstructedBase = nullptr;
7116 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7117
7118 // Find the set of such base class subobjects and check that there's a
7119 // unique constructed subobject.
7120 for (auto *D : Shadow->redecls()) {
7121 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7122 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7123 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7124
7125 InheritedFromBases.insert(
7126 std::make_pair(DNominatedBase->getCanonicalDecl(),
7127 DShadow->getNominatedBaseClassShadowDecl()));
7128 if (DShadow->constructsVirtualBase())
7129 InheritedFromBases.insert(
7130 std::make_pair(DConstructedBase->getCanonicalDecl(),
7131 DShadow->getConstructedBaseClassShadowDecl()));
7132 else
7133 assert(DNominatedBase == DConstructedBase)(static_cast <bool> (DNominatedBase == DConstructedBase
) ? void (0) : __assert_fail ("DNominatedBase == DConstructedBase"
, "clang/lib/Sema/SemaDeclCXX.cpp", 7133, __extension__ __PRETTY_FUNCTION__
))
;
7134
7135 // [class.inhctor.init]p2:
7136 // If the constructor was inherited from multiple base class subobjects
7137 // of type B, the program is ill-formed.
7138 if (!ConstructedBase) {
7139 ConstructedBase = DConstructedBase;
7140 ConstructedBaseIntroducer = D->getIntroducer();
7141 } else if (ConstructedBase != DConstructedBase &&
7142 !Shadow->isInvalidDecl()) {
7143 if (!DiagnosedMultipleConstructedBases) {
7144 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7145 << Shadow->getTargetDecl();
7146 S.Diag(ConstructedBaseIntroducer->getLocation(),
7147 diag::note_ambiguous_inherited_constructor_using)
7148 << ConstructedBase;
7149 DiagnosedMultipleConstructedBases = true;
7150 }
7151 S.Diag(D->getIntroducer()->getLocation(),
7152 diag::note_ambiguous_inherited_constructor_using)
7153 << DConstructedBase;
7154 }
7155 }
7156
7157 if (DiagnosedMultipleConstructedBases)
7158 Shadow->setInvalidDecl();
7159 }
7160
7161 /// Find the constructor to use for inherited construction of a base class,
7162 /// and whether that base class constructor inherits the constructor from a
7163 /// virtual base class (in which case it won't actually invoke it).
7164 std::pair<CXXConstructorDecl *, bool>
7165 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7166 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7167 if (It == InheritedFromBases.end())
7168 return std::make_pair(nullptr, false);
7169
7170 // This is an intermediary class.
7171 if (It->second)
7172 return std::make_pair(
7173 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7174 It->second->constructsVirtualBase());
7175
7176 // This is the base class from which the constructor was inherited.
7177 return std::make_pair(Ctor, false);
7178 }
7179};
7180
7181/// Is the special member function which would be selected to perform the
7182/// specified operation on the specified class type a constexpr constructor?
7183static bool
7184specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7185 Sema::CXXSpecialMember CSM, unsigned Quals,
7186 bool ConstRHS,
7187 CXXConstructorDecl *InheritedCtor = nullptr,
7188 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7189 // If we're inheriting a constructor, see if we need to call it for this base
7190 // class.
7191 if (InheritedCtor) {
7192 assert(CSM == Sema::CXXDefaultConstructor)(static_cast <bool> (CSM == Sema::CXXDefaultConstructor
) ? void (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor"
, "clang/lib/Sema/SemaDeclCXX.cpp", 7192, __extension__ __PRETTY_FUNCTION__
))
;
7193 auto BaseCtor =
7194 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7195 if (BaseCtor)
7196 return BaseCtor->isConstexpr();
7197 }
7198
7199 if (CSM == Sema::CXXDefaultConstructor)
7200 return ClassDecl->hasConstexprDefaultConstructor();
7201 if (CSM == Sema::CXXDestructor)
7202 return ClassDecl->hasConstexprDestructor();
7203
7204 Sema::SpecialMemberOverloadResult SMOR =
7205 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7206 if (!SMOR.getMethod())
7207 // A constructor we wouldn't select can't be "involved in initializing"
7208 // anything.
7209 return true;
7210 return SMOR.getMethod()->isConstexpr();
7211}
7212
7213/// Determine whether the specified special member function would be constexpr
7214/// if it were implicitly defined.
7215static bool defaultedSpecialMemberIsConstexpr(
7216 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7217 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7218 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7219 if (!S.getLangOpts().CPlusPlus11)
7220 return false;
7221
7222 // C++11 [dcl.constexpr]p4:
7223 // In the definition of a constexpr constructor [...]
7224 bool Ctor = true;
7225 switch (CSM) {
7226 case Sema::CXXDefaultConstructor:
7227 if (Inherited)
7228 break;
7229 // Since default constructor lookup is essentially trivial (and cannot
7230 // involve, for instance, template instantiation), we compute whether a
7231 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7232 //
7233 // This is important for performance; we need to know whether the default
7234 // constructor is constexpr to determine whether the type is a literal type.
7235 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7236
7237 case Sema::CXXCopyConstructor:
7238 case Sema::CXXMoveConstructor:
7239 // For copy or move constructors, we need to perform overload resolution.
7240 break;
7241
7242 case Sema::CXXCopyAssignment:
7243 case Sema::CXXMoveAssignment:
7244 if (!S.getLangOpts().CPlusPlus14)
7245 return false;
7246 // In C++1y, we need to perform overload resolution.
7247 Ctor = false;
7248 break;
7249
7250 case Sema::CXXDestructor:
7251 return ClassDecl->defaultedDestructorIsConstexpr();
7252
7253 case Sema::CXXInvalid:
7254 return false;
7255 }
7256
7257 // -- if the class is a non-empty union, or for each non-empty anonymous
7258 // union member of a non-union class, exactly one non-static data member
7259 // shall be initialized; [DR1359]
7260 //
7261 // If we squint, this is guaranteed, since exactly one non-static data member
7262 // will be initialized (if the constructor isn't deleted), we just don't know
7263 // which one.
7264 if (Ctor && ClassDecl->isUnion())
7265 return CSM == Sema::CXXDefaultConstructor
7266 ? ClassDecl->hasInClassInitializer() ||
7267 !ClassDecl->hasVariantMembers()
7268 : true;
7269
7270 // -- the class shall not have any virtual base classes;
7271 if (Ctor && ClassDecl->getNumVBases())
7272 return false;
7273
7274 // C++1y [class.copy]p26:
7275 // -- [the class] is a literal type, and
7276 if (!Ctor && !ClassDecl->isLiteral())
7277 return false;
7278
7279 // -- every constructor involved in initializing [...] base class
7280 // sub-objects shall be a constexpr constructor;
7281 // -- the assignment operator selected to copy/move each direct base
7282 // class is a constexpr function, and
7283 for (const auto &B : ClassDecl->bases()) {
7284 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7285 if (!BaseType) continue;
7286
7287 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7288 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7289 InheritedCtor, Inherited))
7290 return false;
7291 }
7292
7293 // -- every constructor involved in initializing non-static data members
7294 // [...] shall be a constexpr constructor;
7295 // -- every non-static data member and base class sub-object shall be
7296 // initialized
7297 // -- for each non-static data member of X that is of class type (or array
7298 // thereof), the assignment operator selected to copy/move that member is
7299 // a constexpr function
7300 for (const auto *F : ClassDecl->fields()) {
7301 if (F->isInvalidDecl())
7302 continue;
7303 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7304 continue;
7305 QualType BaseType = S.Context.getBaseElementType(F->getType());
7306 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7307 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7308 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7309 BaseType.getCVRQualifiers(),
7310 ConstArg && !F->isMutable()))
7311 return false;
7312 } else if (CSM == Sema::CXXDefaultConstructor) {
7313 return false;
7314 }
7315 }
7316
7317 // All OK, it's constexpr!
7318 return true;
7319}
7320
7321namespace {
7322/// RAII object to register a defaulted function as having its exception
7323/// specification computed.
7324struct ComputingExceptionSpec {
7325 Sema &S;
7326
7327 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7328 : S(S) {
7329 Sema::CodeSynthesisContext Ctx;
7330 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7331 Ctx.PointOfInstantiation = Loc;
7332 Ctx.Entity = FD;
7333 S.pushCodeSynthesisContext(Ctx);
7334 }
7335 ~ComputingExceptionSpec() {
7336 S.popCodeSynthesisContext();
7337 }
7338};
7339}
7340
7341static Sema::ImplicitExceptionSpecification
7342ComputeDefaultedSpecialMemberExceptionSpec(
7343 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7344 Sema::InheritedConstructorInfo *ICI);
7345
7346static Sema::ImplicitExceptionSpecification
7347ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7348 FunctionDecl *FD,
7349 Sema::DefaultedComparisonKind DCK);
7350
7351static Sema::ImplicitExceptionSpecification
7352computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7353 auto DFK = S.getDefaultedFunctionKind(FD);
7354 if (DFK.isSpecialMember())
7355 return ComputeDefaultedSpecialMemberExceptionSpec(
7356 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7357 if (DFK.isComparison())
7358 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7359 DFK.asComparison());
7360
7361 auto *CD = cast<CXXConstructorDecl>(FD);
7362 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", 7364, __extension__ __PRETTY_FUNCTION__
))
7363 "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", 7364, __extension__ __PRETTY_FUNCTION__
))
7364 "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", 7364, __extension__ __PRETTY_FUNCTION__
))
;
7365 Sema::InheritedConstructorInfo ICI(
7366 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7367 return ComputeDefaultedSpecialMemberExceptionSpec(
7368 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7369}
7370
7371static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7372 CXXMethodDecl *MD) {
7373 FunctionProtoType::ExtProtoInfo EPI;
7374
7375 // Build an exception specification pointing back at this member.
7376 EPI.ExceptionSpec.Type = EST_Unevaluated;
7377 EPI.ExceptionSpec.SourceDecl = MD;
7378
7379 // Set the calling convention to the default for C++ instance methods.
7380 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7381 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7382 /*IsCXXMethod=*/true));
7383 return EPI;
7384}
7385
7386void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7387 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7388 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7389 return;
7390
7391 // Evaluate the exception specification.
7392 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7393 auto ESI = IES.getExceptionSpec();
7394
7395 // Update the type of the special member to use it.
7396 UpdateExceptionSpec(FD, ESI);
7397}
7398
7399void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7400 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", 7400, __extension__ __PRETTY_FUNCTION__
))
;
7401
7402 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7403 if (!DefKind) {
7404 assert(FD->getDeclContext()->isDependentContext())(static_cast <bool> (FD->getDeclContext()->isDependentContext
()) ? void (0) : __assert_fail ("FD->getDeclContext()->isDependentContext()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 7404, __extension__ __PRETTY_FUNCTION__
))
;
7405 return;
7406 }
7407
7408 if (DefKind.isComparison())
7409 UnusedPrivateFields.clear();
7410
7411 if (DefKind.isSpecialMember()
7412 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7413 DefKind.asSpecialMember())
7414 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7415 FD->setInvalidDecl();
7416}
7417
7418bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7419 CXXSpecialMember CSM) {
7420 CXXRecordDecl *RD = MD->getParent();
7421
7422 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", 7423, __extension__ __PRETTY_FUNCTION__
))
1
Assuming the condition is true
2
Assuming 'CSM' is not equal to CXXInvalid
3
'?' condition is true
7423 "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", 7423, __extension__ __PRETTY_FUNCTION__
))
;
7424
7425 // Defer all checking for special members of a dependent type.
7426 if (RD->isDependentType())
4
Assuming the condition is false
5
Taking false branch
7427 return false;
7428
7429 // Whether this was the first-declared instance of the constructor.
7430 // This affects whether we implicitly add an exception spec and constexpr.
7431 bool First = MD == MD->getCanonicalDecl();
6
Assuming the condition is false
7432
7433 bool HadError = false;
7434
7435 // C++11 [dcl.fct.def.default]p1:
7436 // A function that is explicitly defaulted shall
7437 // -- be a special member function [...] (checked elsewhere),
7438 // -- have the same type (except for ref-qualifiers, and except that a
7439 // copy operation can take a non-const reference) as an implicit
7440 // declaration, and
7441 // -- not have default arguments.
7442 // C++2a changes the second bullet to instead delete the function if it's
7443 // defaulted on its first declaration, unless it's "an assignment operator,
7444 // and its return type differs or its parameter type is not a reference".
7445 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7
Assuming field 'CPlusPlus20' is 0
7446 bool ShouldDeleteForTypeMismatch = false;
7447 unsigned ExpectedParams = 1;
7448 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
8
Assuming 'CSM' is not equal to CXXDefaultConstructor
9
Assuming 'CSM' is not equal to CXXDestructor
10
Taking false branch
7449 ExpectedParams = 0;
7450 if (MD->getNumParams() != ExpectedParams) {
11
Assuming the condition is false
12
Taking false branch
7451 // This checks for default arguments: a copy or move constructor with a
7452 // default argument is classified as a default constructor, and assignment
7453 // operations and destructors can't have default arguments.
7454 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7455 << CSM << MD->getSourceRange();
7456 HadError = true;
7457 } else if (MD->isVariadic()) {
13
Assuming the condition is false
14
Taking false branch
7458 if (DeleteOnTypeMismatch)
7459 ShouldDeleteForTypeMismatch = true;
7460 else {
7461 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7462 << CSM << MD->getSourceRange();
7463 HadError = true;
7464 }
7465 }
7466
7467 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
15
Assuming the object is not a 'const class clang::FunctionProtoType *'
16
'Type' initialized to a null pointer value
7468
7469 bool CanHaveConstParam = false;
7470 if (CSM == CXXCopyConstructor)
17
Assuming 'CSM' is not equal to CXXCopyConstructor
18
Taking false branch
7471 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7472 else if (CSM == CXXCopyAssignment)
19
Assuming 'CSM' is not equal to CXXCopyAssignment
20
Taking false branch
7473 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7474
7475 QualType ReturnType = Context.VoidTy;
7476 if (CSM
20.1
'CSM' is not equal to CXXCopyAssignment
== CXXCopyAssignment || CSM == CXXMoveAssignment) {
21
Assuming 'CSM' is equal to CXXMoveAssignment
22
Taking true branch
7477 // Check for return type matching.
7478 ReturnType = Type->getReturnType();
23
Called C++ object pointer is null
7479
7480 QualType DeclType = Context.getTypeDeclType(RD);
7481 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7482 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7483
7484 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7485 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7486 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7487 HadError = true;
7488 }
7489
7490 // A defaulted special member cannot have cv-qualifiers.
7491 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7492 if (DeleteOnTypeMismatch)
7493 ShouldDeleteForTypeMismatch = true;
7494 else {
7495 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7496 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7497 HadError = true;
7498 }
7499 }
7500 }
7501
7502 // Check for parameter type matching.
7503 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7504 bool HasConstParam = false;
7505 if (ExpectedParams && ArgType->isReferenceType()) {
7506 // Argument must be reference to possibly-const T.
7507 QualType ReferentType = ArgType->getPointeeType();
7508 HasConstParam = ReferentType.isConstQualified();
7509
7510 if (ReferentType.isVolatileQualified()) {
7511 if (DeleteOnTypeMismatch)
7512 ShouldDeleteForTypeMismatch = true;
7513 else {
7514 Diag(MD->getLocation(),
7515 diag::err_defaulted_special_member_volatile_param) << CSM;
7516 HadError = true;
7517 }
7518 }
7519
7520 if (HasConstParam && !CanHaveConstParam) {
7521 if (DeleteOnTypeMismatch)
7522 ShouldDeleteForTypeMismatch = true;
7523 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7524 Diag(MD->getLocation(),
7525 diag::err_defaulted_special_member_copy_const_param)
7526 << (CSM == CXXCopyAssignment);
7527 // FIXME: Explain why this special member can't be const.
7528 HadError = true;
7529 } else {
7530 Diag(MD->getLocation(),
7531 diag::err_defaulted_special_member_move_const_param)
7532 << (CSM == CXXMoveAssignment);
7533 HadError = true;
7534 }
7535 }
7536 } else if (ExpectedParams) {
7537 // A copy assignment operator can take its argument by value, but a
7538 // defaulted one cannot.
7539 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", 7539, __extension__ __PRETTY_FUNCTION__
))
;
7540 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7541 HadError = true;
7542 }
7543
7544 // C++11 [dcl.fct.def.default]p2:
7545 // An explicitly-defaulted function may be declared constexpr only if it
7546 // would have been implicitly declared as constexpr,
7547 // Do not apply this rule to members of class templates, since core issue 1358
7548 // makes such functions always instantiate to constexpr functions. For
7549 // functions which cannot be constexpr (for non-constructors in C++11 and for
7550 // destructors in C++14 and C++17), this is checked elsewhere.
7551 //
7552 // FIXME: This should not apply if the member is deleted.
7553 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7554 HasConstParam);
7555
7556 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
7557 // If the instantiated template specialization of a constexpr function
7558 // template or member function of a class template would fail to satisfy
7559 // the requirements for a constexpr function or constexpr constructor, that
7560 // specialization is still a constexpr function or constexpr constructor,
7561 // even though a call to such a function cannot appear in a constant
7562 // expression.
7563 if (MD->isTemplateInstantiation() && MD->isConstexpr())
7564 Constexpr = true;
7565
7566 if ((getLangOpts().CPlusPlus20 ||
7567 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7568 : isa<CXXConstructorDecl>(MD))) &&
7569 MD->isConstexpr() && !Constexpr &&
7570 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7571 Diag(MD->getBeginLoc(), MD->isConsteval()
7572 ? diag::err_incorrect_defaulted_consteval
7573 : diag::err_incorrect_defaulted_constexpr)
7574 << CSM;
7575 // FIXME: Explain why the special member can't be constexpr.
7576 HadError = true;
7577 }
7578
7579 if (First) {
7580 // C++2a [dcl.fct.def.default]p3:
7581 // If a function is explicitly defaulted on its first declaration, it is
7582 // implicitly considered to be constexpr if the implicit declaration
7583 // would be.
7584 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7585 ? ConstexprSpecKind::Consteval
7586 : ConstexprSpecKind::Constexpr)
7587 : ConstexprSpecKind::Unspecified);
7588
7589 if (!Type->hasExceptionSpec()) {
7590 // C++2a [except.spec]p3:
7591 // If a declaration of a function does not have a noexcept-specifier
7592 // [and] is defaulted on its first declaration, [...] the exception
7593 // specification is as specified below
7594 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7595 EPI.ExceptionSpec.Type = EST_Unevaluated;
7596 EPI.ExceptionSpec.SourceDecl = MD;
7597 MD->setType(Context.getFunctionType(ReturnType,
7598 llvm::makeArrayRef(&ArgType,
7599 ExpectedParams),
7600 EPI));
7601 }
7602 }
7603
7604 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7605 if (First) {
7606 SetDeclDeleted(MD, MD->getLocation());
7607 if (!inTemplateInstantiation() && !HadError) {
7608 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7609 if (ShouldDeleteForTypeMismatch) {
7610 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7611 } else {
7612 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7613 }
7614 }
7615 if (ShouldDeleteForTypeMismatch && !HadError) {
7616 Diag(MD->getLocation(),
7617 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7618 }
7619 } else {
7620 // C++11 [dcl.fct.def.default]p4:
7621 // [For a] user-provided explicitly-defaulted function [...] if such a
7622 // function is implicitly defined as deleted, the program is ill-formed.
7623 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7624 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", 7624, __extension__ __PRETTY_FUNCTION__
))
;
7625 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7626 HadError = true;
7627 }
7628 }
7629
7630 return HadError;
7631}
7632
7633namespace {
7634/// Helper class for building and checking a defaulted comparison.
7635///
7636/// Defaulted functions are built in two phases:
7637///
7638/// * First, the set of operations that the function will perform are
7639/// identified, and some of them are checked. If any of the checked
7640/// operations is invalid in certain ways, the comparison function is
7641/// defined as deleted and no body is built.
7642/// * Then, if the function is not defined as deleted, the body is built.
7643///
7644/// This is accomplished by performing two visitation steps over the eventual
7645/// body of the function.
7646template<typename Derived, typename ResultList, typename Result,
7647 typename Subobject>
7648class DefaultedComparisonVisitor {
7649public:
7650 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7651
7652 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7653 DefaultedComparisonKind DCK)
7654 : S(S), RD(RD), FD(FD), DCK(DCK) {
7655 if (auto *Info = FD->getDefaultedFunctionInfo()) {
7656 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7657 // UnresolvedSet to avoid this copy.
7658 Fns.assign(Info->getUnqualifiedLookups().begin(),
7659 Info->getUnqualifiedLookups().end());
7660 }
7661 }
7662
7663 ResultList visit() {
7664 // The type of an lvalue naming a parameter of this function.
7665 QualType ParamLvalType =
7666 FD->getParamDecl(0)->getType().getNonReferenceType();
7667
7668 ResultList Results;
7669
7670 switch (DCK) {
7671 case DefaultedComparisonKind::None:
7672 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "clang/lib/Sema/SemaDeclCXX.cpp", 7672)
;
7673
7674 case DefaultedComparisonKind::Equal:
7675 case DefaultedComparisonKind::ThreeWay:
7676 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7677 return Results;
7678
7679 case DefaultedComparisonKind::NotEqual:
7680 case DefaultedComparisonKind::Relational:
7681 Results.add(getDerived().visitExpandedSubobject(
7682 ParamLvalType, getDerived().getCompleteObject()));
7683 return Results;
7684 }
7685 llvm_unreachable("")::llvm::llvm_unreachable_internal("", "clang/lib/Sema/SemaDeclCXX.cpp"
, 7685)
;
7686 }
7687
7688protected:
7689 Derived &getDerived() { return static_cast<Derived&>(*this); }
7690
7691 /// Visit the expanded list of subobjects of the given type, as specified in
7692 /// C++2a [class.compare.default].
7693 ///
7694 /// \return \c true if the ResultList object said we're done, \c false if not.
7695 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7696 Qualifiers Quals) {
7697 // C++2a [class.compare.default]p4:
7698 // The direct base class subobjects of C
7699 for (CXXBaseSpecifier &Base : Record->bases())
7700 if (Results.add(getDerived().visitSubobject(
7701 S.Context.getQualifiedType(Base.getType(), Quals),
7702 getDerived().getBase(&Base))))
7703 return true;
7704
7705 // followed by the non-static data members of C
7706 for (FieldDecl *Field : Record->fields()) {
7707 // Recursively expand anonymous structs.
7708 if (Field->isAnonymousStructOrUnion()) {
7709 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7710 Quals))
7711 return true;
7712 continue;
7713 }
7714
7715 // Figure out the type of an lvalue denoting this field.
7716 Qualifiers FieldQuals = Quals;
7717 if (Field->isMutable())
7718 FieldQuals.removeConst();
7719 QualType FieldType =
7720 S.Context.getQualifiedType(Field->getType(), FieldQuals);
7721
7722 if (Results.add(getDerived().visitSubobject(
7723 FieldType, getDerived().getField(Field))))
7724 return true;
7725 }
7726
7727 // form a list of subobjects.
7728 return false;
7729 }
7730
7731 Result visitSubobject(QualType Type, Subobject Subobj) {
7732 // In that list, any subobject of array type is recursively expanded
7733 const ArrayType *AT = S.Context.getAsArrayType(Type);
7734 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7735 return getDerived().visitSubobjectArray(CAT->getElementType(),
7736 CAT->getSize(), Subobj);
7737 return getDerived().visitExpandedSubobject(Type, Subobj);
7738 }
7739
7740 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7741 Subobject Subobj) {
7742 return getDerived().visitSubobject(Type, Subobj);
7743 }
7744
7745protected:
7746 Sema &S;
7747 CXXRecordDecl *RD;
7748 FunctionDecl *FD;
7749 DefaultedComparisonKind DCK;
7750 UnresolvedSet<16> Fns;
7751};
7752
7753/// Information about a defaulted comparison, as determined by
7754/// DefaultedComparisonAnalyzer.
7755struct DefaultedComparisonInfo {
7756 bool Deleted = false;
7757 bool Constexpr = true;
7758 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7759
7760 static DefaultedComparisonInfo deleted() {
7761 DefaultedComparisonInfo Deleted;
7762 Deleted.Deleted = true;
7763 return Deleted;
7764 }
7765
7766 bool add(const DefaultedComparisonInfo &R) {
7767 Deleted |= R.Deleted;
7768 Constexpr &= R.Constexpr;
7769 Category = commonComparisonType(Category, R.Category);
7770 return Deleted;
7771 }
7772};
7773
7774/// An element in the expanded list of subobjects of a defaulted comparison, as
7775/// specified in C++2a [class.compare.default]p4.
7776struct DefaultedComparisonSubobject {
7777 enum { CompleteObject, Member, Base } Kind;
7778 NamedDecl *Decl;
7779 SourceLocation Loc;
7780};
7781
7782/// A visitor over the notional body of a defaulted comparison that determines
7783/// whether that body would be deleted or constexpr.
7784class DefaultedComparisonAnalyzer
7785 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7786 DefaultedComparisonInfo,
7787 DefaultedComparisonInfo,
7788 DefaultedComparisonSubobject> {
7789public:
7790 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7791
7792private:
7793 DiagnosticKind Diagnose;
7794
7795public:
7796 using Base = DefaultedComparisonVisitor;
7797 using Result = DefaultedComparisonInfo;
7798 using Subobject = DefaultedComparisonSubobject;
7799
7800 friend Base;
7801
7802 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7803 DefaultedComparisonKind DCK,
7804 DiagnosticKind Diagnose = NoDiagnostics)
7805 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7806
7807 Result visit() {
7808 if ((DCK == DefaultedComparisonKind::Equal ||
7809 DCK == DefaultedComparisonKind::ThreeWay) &&
7810 RD->hasVariantMembers()) {
7811 // C++2a [class.compare.default]p2 [P2002R0]:
7812 // A defaulted comparison operator function for class C is defined as
7813 // deleted if [...] C has variant members.
7814 if (Diagnose == ExplainDeleted) {
7815 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7816 << FD << RD->isUnion() << RD;
7817 }
7818 return Result::deleted();
7819 }
7820
7821 return Base::visit();
7822 }
7823
7824private:
7825 Subobject getCompleteObject() {
7826 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7827 }
7828
7829 Subobject getBase(CXXBaseSpecifier *Base) {
7830 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7831 Base->getBaseTypeLoc()};
7832 }
7833
7834 Subobject getField(FieldDecl *Field) {
7835 return Subobject{Subobject::Member, Field, Field->getLocation()};
7836 }
7837
7838 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7839 // C++2a [class.compare.default]p2 [P2002R0]:
7840 // A defaulted <=> or == operator function for class C is defined as
7841 // deleted if any non-static data member of C is of reference type
7842 if (Type->isReferenceType()) {
7843 if (Diagnose == ExplainDeleted) {
7844 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7845 << FD << RD;
7846 }
7847 return Result::deleted();
7848 }
7849
7850 // [...] Let xi be an lvalue denoting the ith element [...]
7851 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7852 Expr *Args[] = {&Xi, &Xi};
7853
7854 // All operators start by trying to apply that same operator recursively.
7855 OverloadedOperatorKind OO = FD->getOverloadedOperator();
7856 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", 7856, __extension__ __PRETTY_FUNCTION__
))
;
7857 return visitBinaryOperator(OO, Args, Subobj);
7858 }
7859
7860 Result
7861 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7862 Subobject Subobj,
7863 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7864 // Note that there is no need to consider rewritten candidates here if
7865 // we've already found there is no viable 'operator<=>' candidate (and are
7866 // considering synthesizing a '<=>' from '==' and '<').
7867 OverloadCandidateSet CandidateSet(
7868 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7869 OverloadCandidateSet::OperatorRewriteInfo(
7870 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7871
7872 /// C++2a [class.compare.default]p1 [P2002R0]:
7873 /// [...] the defaulted function itself is never a candidate for overload
7874 /// resolution [...]
7875 CandidateSet.exclude(FD);
7876
7877 if (Args[0]->getType()->isOverloadableType())
7878 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7879 else
7880 // FIXME: We determine whether this is a valid expression by checking to
7881 // see if there's a viable builtin operator candidate for it. That isn't
7882 // really what the rules ask us to do, but should give the right results.
7883 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7884
7885 Result R;
7886
7887 OverloadCandidateSet::iterator Best;
7888 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7889 case OR_Success: {
7890 // C++2a [class.compare.secondary]p2 [P2002R0]:
7891 // The operator function [...] is defined as deleted if [...] the
7892 // candidate selected by overload resolution is not a rewritten
7893 // candidate.
7894 if ((DCK == DefaultedComparisonKind::NotEqual ||
7895 DCK == DefaultedComparisonKind::Relational) &&
7896 !Best->RewriteKind) {
7897 if (Diagnose == ExplainDeleted) {
7898 if (Best->Function) {
7899 S.Diag(Best->Function->getLocation(),
7900 diag::note_defaulted_comparison_not_rewritten_callee)
7901 << FD;
7902 } else {
7903 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", 7906, __extension__ __PRETTY_FUNCTION__
))
7904 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", 7906, __extension__ __PRETTY_FUNCTION__
))
7905 "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", 7906, __extension__ __PRETTY_FUNCTION__
))
7906 "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", 7906, __extension__ __PRETTY_FUNCTION__
))
;
7907 S.Diag(Best->Conversions[0]
7908 .UserDefined.FoundConversionFunction.getDecl()
7909 ->getLocation(),
7910 diag::note_defaulted_comparison_not_rewritten_conversion)
7911 << FD;
7912 }
7913 }
7914 return Result::deleted();
7915 }
7916
7917 // Throughout C++2a [class.compare]: if overload resolution does not
7918 // result in a usable function, the candidate function is defined as
7919 // deleted. This requires that we selected an accessible function.
7920 //
7921 // Note that this only considers the access of the function when named
7922 // within the type of the subobject, and not the access path for any
7923 // derived-to-base conversion.
7924 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7925 if (ArgClass && Best->FoundDecl.getDecl() &&
7926 Best->FoundDecl.getDecl()->isCXXClassMember()) {
7927 QualType ObjectType = Subobj.Kind == Subobject::Member
7928 ? Args[0]->getType()
7929 : S.Context.getRecordType(RD);
7930 if (!S.isMemberAccessibleForDeletion(
7931 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7932 Diagnose == ExplainDeleted
7933 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7934 << FD << Subobj.Kind << Subobj.Decl
7935 : S.PDiag()))
7936 return Result::deleted();
7937 }
7938
7939 bool NeedsDeducing =
7940 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
7941
7942 if (FunctionDecl *BestFD = Best->Function) {
7943 // C++2a [class.compare.default]p3 [P2002R0]:
7944 // A defaulted comparison function is constexpr-compatible if
7945 // [...] no overlod resolution performed [...] results in a
7946 // non-constexpr function.
7947 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", 7947, __extension__ __PRETTY_FUNCTION__
))
;
7948 // If it's not constexpr, explain why not.
7949 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7950 if (Subobj.Kind != Subobject::CompleteObject)
7951 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7952 << Subobj.Kind << Subobj.Decl;
7953 S.Diag(BestFD->getLocation(),
7954 diag::note_defaulted_comparison_not_constexpr_here);
7955 // Bail out after explaining; we don't want any more notes.
7956 return Result::deleted();
7957 }
7958 R.Constexpr &= BestFD->isConstexpr();
7959
7960 if (NeedsDeducing) {
7961 // If any callee has an undeduced return type, deduce it now.
7962 // FIXME: It's not clear how a failure here should be handled. For
7963 // now, we produce an eager diagnostic, because that is forward
7964 // compatible with most (all?) other reasonable options.
7965 if (BestFD->getReturnType()->isUndeducedType() &&
7966 S.DeduceReturnType(BestFD, FD->getLocation(),
7967 /*Diagnose=*/false)) {
7968 // Don't produce a duplicate error when asked to explain why the
7969 // comparison is deleted: we diagnosed that when initially checking
7970 // the defaulted operator.
7971 if (Diagnose == NoDiagnostics) {
7972 S.Diag(
7973 FD->getLocation(),
7974 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7975 << Subobj.Kind << Subobj.Decl;
7976 S.Diag(
7977 Subobj.Loc,
7978 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7979 << Subobj.Kind << Subobj.Decl;
7980 S.Diag(BestFD->getLocation(),
7981 diag::note_defaulted_comparison_cannot_deduce_callee)
7982 << Subobj.Kind << Subobj.Decl;
7983 }
7984 return Result::deleted();
7985 }
7986 auto *Info = S.Context.CompCategories.lookupInfoForType(
7987 BestFD->getCallResultType());
7988 if (!Info) {
7989 if (Diagnose == ExplainDeleted) {
7990 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7991 << Subobj.Kind << Subobj.Decl
7992 << BestFD->getCallResultType().withoutLocalFastQualifiers();
7993 S.Diag(BestFD->getLocation(),
7994 diag::note_defaulted_comparison_cannot_deduce_callee)
7995 << Subobj.Kind << Subobj.Decl;
7996 }
7997 return Result::deleted();
7998 }
7999 R.Category = Info->Kind;
8000 }
8001 } else {
8002 QualType T = Best->BuiltinParamTypes[0];
8003 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", 8004, __extension__ __PRETTY_FUNCTION__
))
8004 "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", 8004, __extension__ __PRETTY_FUNCTION__
))
;
8005 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", 8006, __extension__ __PRETTY_FUNCTION__
))
8006 "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", 8006, __extension__ __PRETTY_FUNCTION__
))
;
8007
8008 if (NeedsDeducing) {
8009 Optional<ComparisonCategoryType> Cat =
8010 getComparisonCategoryForBuiltinCmp(T);
8011 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", 8011, __extension__ __PRETTY_FUNCTION__
))
;
8012 R.Category = *Cat;
8013 }
8014 }
8015
8016 // Note that we might be rewriting to a different operator. That call is
8017 // not considered until we come to actually build the comparison function.
8018 break;
8019 }
8020
8021 case OR_Ambiguous:
8022 if (Diagnose == ExplainDeleted) {
8023 unsigned Kind = 0;
8024 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8025 Kind = OO == OO_EqualEqual ? 1 : 2;
8026 CandidateSet.NoteCandidates(
8027 PartialDiagnosticAt(
8028 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8029 << FD << Kind << Subobj.Kind << Subobj.Decl),
8030 S, OCD_AmbiguousCandidates, Args);
8031 }
8032 R = Result::deleted();
8033 break;
8034
8035 case OR_Deleted:
8036 if (Diagnose == ExplainDeleted) {
8037 if ((DCK == DefaultedComparisonKind::NotEqual ||
8038 DCK == DefaultedComparisonKind::Relational) &&
8039 !Best->RewriteKind) {
8040 S.Diag(Best->Function->getLocation(),
8041 diag::note_defaulted_comparison_not_rewritten_callee)
8042 << FD;
8043 } else {
8044 S.Diag(Subobj.Loc,
8045 diag::note_defaulted_comparison_calls_deleted)
8046 << FD << Subobj.Kind << Subobj.Decl;
8047 S.NoteDeletedFunction(Best->Function);
8048 }
8049 }
8050 R = Result::deleted();
8051 break;
8052
8053 case OR_No_Viable_Function:
8054 // If there's no usable candidate, we're done unless we can rewrite a
8055 // '<=>' in terms of '==' and '<'.
8056 if (OO == OO_Spaceship &&
8057 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
8058 // For any kind of comparison category return type, we need a usable
8059 // '==' and a usable '<'.
8060 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8061 &CandidateSet)))
8062 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8063 break;
8064 }
8065
8066 if (Diagnose == ExplainDeleted) {
8067 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8068 << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl;
8069
8070 // For a three-way comparison, list both the candidates for the
8071 // original operator and the candidates for the synthesized operator.
8072 if (SpaceshipCandidates) {
8073 SpaceshipCandidates->NoteCandidates(
8074 S, Args,
8075 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8076 Args, FD->getLocation()));
8077 S.Diag(Subobj.Loc,
8078 diag::note_defaulted_comparison_no_viable_function_synthesized)
8079 << (OO == OO_EqualEqual ? 0 : 1);
8080 }
8081
8082 CandidateSet.NoteCandidates(
8083 S, Args,
8084 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8085 FD->getLocation()));
8086 }
8087 R = Result::deleted();
8088 break;
8089 }
8090
8091 return R;
8092 }
8093};
8094
8095/// A list of statements.
8096struct StmtListResult {
8097 bool IsInvalid = false;
8098 llvm::SmallVector<Stmt*, 16> Stmts;
8099
8100 bool add(const StmtResult &S) {
8101 IsInvalid |= S.isInvalid();
8102 if (IsInvalid)
8103 return true;
8104 Stmts.push_back(S.get());
8105 return false;
8106 }
8107};
8108
8109/// A visitor over the notional body of a defaulted comparison that synthesizes
8110/// the actual body.
8111class DefaultedComparisonSynthesizer
8112 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8113 StmtListResult, StmtResult,
8114 std::pair<ExprResult, ExprResult>> {
8115 SourceLocation Loc;
8116 unsigned ArrayDepth = 0;
8117
8118public:
8119 using Base = DefaultedComparisonVisitor;
8120 using ExprPair = std::pair<ExprResult, ExprResult>;
8121
8122 friend Base;
8123
8124 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8125 DefaultedComparisonKind DCK,
8126 SourceLocation BodyLoc)
8127 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8128
8129 /// Build a suitable function body for this defaulted comparison operator.
8130 StmtResult build() {
8131 Sema::CompoundScopeRAII CompoundScope(S);
8132
8133 StmtListResult Stmts = visit();
8134 if (Stmts.IsInvalid)
8135 return StmtError();
8136
8137 ExprResult RetVal;
8138 switch (DCK) {
8139 case DefaultedComparisonKind::None:
8140 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8140)
;
8141
8142 case DefaultedComparisonKind::Equal: {
8143 // C++2a [class.eq]p3:
8144 // [...] compar[e] the corresponding elements [...] until the first
8145 // index i where xi == yi yields [...] false. If no such index exists,
8146 // V is true. Otherwise, V is false.
8147 //
8148 // Join the comparisons with '&&'s and return the result. Use a right
8149 // fold (traversing the conditions right-to-left), because that
8150 // short-circuits more naturally.
8151 auto OldStmts = std::move(Stmts.Stmts);
8152 Stmts.Stmts.clear();
8153 ExprResult CmpSoFar;
8154 // Finish a particular comparison chain.
8155 auto FinishCmp = [&] {
8156 if (Expr *Prior = CmpSoFar.get()) {
8157 // Convert the last expression to 'return ...;'
8158 if (RetVal.isUnset() && Stmts.Stmts.empty())
8159 RetVal = CmpSoFar;
8160 // Convert any prior comparison to 'if (!(...)) return false;'
8161 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8162 return true;
8163 CmpSoFar = ExprResult();
8164 }
8165 return false;
8166 };
8167 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8168 Expr *E = dyn_cast<Expr>(EAsStmt);
8169 if (!E) {
8170 // Found an array comparison.
8171 if (FinishCmp() || Stmts.add(EAsStmt))
8172 return StmtError();
8173 continue;
8174 }
8175
8176 if (CmpSoFar.isUnset()) {
8177 CmpSoFar = E;
8178 continue;
8179 }
8180 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8181 if (CmpSoFar.isInvalid())
8182 return StmtError();
8183 }
8184 if (FinishCmp())
8185 return StmtError();
8186 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8187 // If no such index exists, V is true.
8188 if (RetVal.isUnset())
8189 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8190 break;
8191 }
8192
8193 case DefaultedComparisonKind::ThreeWay: {
8194 // Per C++2a [class.spaceship]p3, as a fallback add:
8195 // return static_cast<R>(std::strong_ordering::equal);
8196 QualType StrongOrdering = S.CheckComparisonCategoryType(
8197 ComparisonCategoryType::StrongOrdering, Loc,
8198 Sema::ComparisonCategoryUsage::DefaultedOperator);
8199 if (StrongOrdering.isNull())
8200 return StmtError();
8201 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8202 .getValueInfo(ComparisonCategoryResult::Equal)
8203 ->VD;
8204 RetVal = getDecl(EqualVD);
8205 if (RetVal.isInvalid())
8206 return StmtError();
8207 RetVal = buildStaticCastToR(RetVal.get());
8208 break;
8209 }
8210
8211 case DefaultedComparisonKind::NotEqual:
8212 case DefaultedComparisonKind::Relational:
8213 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8214 break;
8215 }
8216
8217 // Build the final return statement.
8218 if (RetVal.isInvalid())
8219 return StmtError();
8220 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8221 if (ReturnStmt.isInvalid())
8222 return StmtError();
8223 Stmts.Stmts.push_back(ReturnStmt.get());
8224
8225 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8226 }
8227
8228private:
8229 ExprResult getDecl(ValueDecl *VD) {
8230 return S.BuildDeclarationNameExpr(
8231 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8232 }
8233
8234 ExprResult getParam(unsigned I) {
8235 ParmVarDecl *PD = FD->getParamDecl(I);
8236 return getDecl(PD);
8237 }
8238
8239 ExprPair getCompleteObject() {
8240 unsigned Param = 0;
8241 ExprResult LHS;
8242 if (isa<CXXMethodDecl>(FD)) {
8243 // LHS is '*this'.
8244 LHS = S.ActOnCXXThis(Loc);
8245 if (!LHS.isInvalid())
8246 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8247 } else {
8248 LHS = getParam(Param++);
8249 }
8250 ExprResult RHS = getParam(Param++);
8251 assert(Param == FD->getNumParams())(static_cast <bool> (Param == FD->getNumParams()) ? void
(0) : __assert_fail ("Param == FD->getNumParams()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 8251, __extension__ __PRETTY_FUNCTION__))
;
8252 return {LHS, RHS};
8253 }
8254
8255 ExprPair getBase(CXXBaseSpecifier *Base) {
8256 ExprPair Obj = getCompleteObject();
8257 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8258 return {ExprError(), ExprError()};
8259 CXXCastPath Path = {Base};
8260 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8261 CK_DerivedToBase, VK_LValue, &Path),
8262 S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8263 CK_DerivedToBase, VK_LValue, &Path)};
8264 }
8265
8266 ExprPair getField(FieldDecl *Field) {
8267 ExprPair Obj = getCompleteObject();
8268 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8269 return {ExprError(), ExprError()};
8270
8271 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8272 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8273 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8274 CXXScopeSpec(), Field, Found, NameInfo),
8275 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8276 CXXScopeSpec(), Field, Found, NameInfo)};
8277 }
8278
8279 // FIXME: When expanding a subobject, register a note in the code synthesis
8280 // stack to say which subobject we're comparing.
8281
8282 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8283 if (Cond.isInvalid())
8284 return StmtError();
8285
8286 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8287 if (NotCond.isInvalid())
8288 return StmtError();
8289
8290 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8291 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", 8291, __extension__ __PRETTY_FUNCTION__
))
;
8292 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8293 if (ReturnFalse.isInvalid())
8294 return StmtError();
8295
8296 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8297 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8298 Sema::ConditionKind::Boolean),
8299 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8300 }
8301
8302 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8303 ExprPair Subobj) {
8304 QualType SizeType = S.Context.getSizeType();
8305 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8306
8307 // Build 'size_t i$n = 0'.
8308 IdentifierInfo *IterationVarName = nullptr;
8309 {
8310 SmallString<8> Str;
8311 llvm::raw_svector_ostream OS(Str);
8312 OS << "i" << ArrayDepth;
8313 IterationVarName = &S.Context.Idents.get(OS.str());
8314 }
8315 VarDecl *IterationVar = VarDecl::Create(
8316 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8317 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8318 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8319 IterationVar->setInit(
8320 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8321 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8322
8323 auto IterRef = [&] {
8324 ExprResult Ref = S.BuildDeclarationNameExpr(
8325 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8326 IterationVar);
8327 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", 8327, __extension__ __PRETTY_FUNCTION__
))
;
8328 return Ref.get();
8329 };
8330
8331 // Build 'i$n != Size'.
8332 ExprResult Cond = S.CreateBuiltinBinOp(
8333 Loc, BO_NE, IterRef(),
8334 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8335 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", 8335, __extension__ __PRETTY_FUNCTION__
))
;
8336
8337 // Build '++i$n'.
8338 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8339 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", 8339, __extension__ __PRETTY_FUNCTION__
))
;
8340
8341 // Build 'a[i$n]' and 'b[i$n]'.
8342 auto Index = [&](ExprResult E) {
8343 if (E.isInvalid())
8344 return ExprError();
8345 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8346 };
8347 Subobj.first = Index(Subobj.first);
8348 Subobj.second = Index(Subobj.second);
8349
8350 // Compare the array elements.
8351 ++ArrayDepth;
8352 StmtResult Substmt = visitSubobject(Type, Subobj);
8353 --ArrayDepth;
8354
8355 if (Substmt.isInvalid())
8356 return StmtError();
8357
8358 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8359 // For outer levels or for an 'operator<=>' we already have a suitable
8360 // statement that returns as necessary.
8361 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8362 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", 8363, __extension__ __PRETTY_FUNCTION__
))
8363 "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", 8363, __extension__ __PRETTY_FUNCTION__
))
;
8364 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8365 if (Substmt.isInvalid())
8366 return StmtError();
8367 }
8368
8369 // Build 'for (...) ...'
8370 return S.ActOnForStmt(Loc, Loc, Init,
8371 S.ActOnCondition(nullptr, Loc, Cond.get(),
8372 Sema::ConditionKind::Boolean),
8373 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8374 Substmt.get());
8375 }
8376
8377 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8378 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8379 return StmtError();
8380
8381 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8382 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8383 ExprResult Op;
8384 if (Type->isOverloadableType())
8385 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8386 Obj.second.get(), /*PerformADL=*/true,
8387 /*AllowRewrittenCandidates=*/true, FD);
8388 else
8389 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8390 if (Op.isInvalid())
8391 return StmtError();
8392
8393 switch (DCK) {
8394 case DefaultedComparisonKind::None:
8395 llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8395)
;
8396
8397 case DefaultedComparisonKind::Equal:
8398 // Per C++2a [class.eq]p2, each comparison is individually contextually
8399 // converted to bool.
8400 Op = S.PerformContextuallyConvertToBool(Op.get());
8401 if (Op.isInvalid())
8402 return StmtError();
8403 return Op.get();
8404
8405 case DefaultedComparisonKind::ThreeWay: {
8406 // Per C++2a [class.spaceship]p3, form:
8407 // if (R cmp = static_cast<R>(op); cmp != 0)
8408 // return cmp;
8409 QualType R = FD->getReturnType();
8410 Op = buildStaticCastToR(Op.get());
8411 if (Op.isInvalid())
8412 return StmtError();
8413
8414 // R cmp = ...;
8415 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8416 VarDecl *VD =
8417 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8418 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8419 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8420 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8421
8422 // cmp != 0
8423 ExprResult VDRef = getDecl(VD);
8424 if (VDRef.isInvalid())
8425 return StmtError();
8426 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8427 Expr *Zero =
8428 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8429 ExprResult Comp;
8430 if (VDRef.get()->getType()->isOverloadableType())
8431 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8432 true, FD);
8433 else
8434 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8435 if (Comp.isInvalid())
8436 return StmtError();
8437 Sema::ConditionResult Cond = S.ActOnCondition(
8438 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8439 if (Cond.isInvalid())
8440 return StmtError();
8441
8442 // return cmp;
8443 VDRef = getDecl(VD);
8444 if (VDRef.isInvalid())
8445 return StmtError();
8446 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8447 if (ReturnStmt.isInvalid())
8448 return StmtError();
8449
8450 // if (...)
8451 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8452 Loc, ReturnStmt.get(),
8453 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8454 }
8455
8456 case DefaultedComparisonKind::NotEqual:
8457 case DefaultedComparisonKind::Relational:
8458 // C++2a [class.compare.secondary]p2:
8459 // Otherwise, the operator function yields x @ y.
8460 return Op.get();
8461 }
8462 llvm_unreachable("")::llvm::llvm_unreachable_internal("", "clang/lib/Sema/SemaDeclCXX.cpp"
, 8462)
;
8463 }
8464
8465 /// Build "static_cast<R>(E)".
8466 ExprResult buildStaticCastToR(Expr *E) {
8467 QualType R = FD->getReturnType();
8468 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", 8468, __extension__ __PRETTY_FUNCTION__
))
;
8469
8470 // Don't bother forming a no-op cast in the common case.
8471 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8472 return E;
8473 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8474 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8475 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8476 }
8477};
8478}
8479
8480/// Perform the unqualified lookups that might be needed to form a defaulted
8481/// comparison function for the given operator.
8482static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8483 UnresolvedSetImpl &Operators,
8484 OverloadedOperatorKind Op) {
8485 auto Lookup = [&](OverloadedOperatorKind OO) {
8486 Self.LookupOverloadedOperatorName(OO, S, Operators);
8487 };
8488
8489 // Every defaulted operator looks up itself.
8490 Lookup(Op);
8491 // ... and the rewritten form of itself, if any.
8492 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8493 Lookup(ExtraOp);
8494
8495 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8496 // synthesize a three-way comparison from '<' and '=='. In a dependent
8497 // context, we also need to look up '==' in case we implicitly declare a
8498 // defaulted 'operator=='.
8499 if (Op == OO_Spaceship) {
8500 Lookup(OO_ExclaimEqual);
8501 Lookup(OO_Less);
8502 Lookup(OO_EqualEqual);
8503 }
8504}
8505
8506bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8507 DefaultedComparisonKind DCK) {
8508 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", 8508, __extension__ __PRETTY_FUNCTION__
))
;
8509
8510 // Perform any unqualified lookups we're going to need to default this
8511 // function.
8512 if (S) {
8513 UnresolvedSet<32> Operators;
8514 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8515 FD->getOverloadedOperator());
8516 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8517 Context, Operators.pairs()));
8518 }
8519
8520 // C++2a [class.compare.default]p1:
8521 // A defaulted comparison operator function for some class C shall be a
8522 // non-template function declared in the member-specification of C that is
8523 // -- a non-static const member of C having one parameter of type
8524 // const C&, or
8525 // -- a friend of C having two parameters of type const C& or two
8526 // parameters of type C.
8527
8528 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8529 bool IsMethod = isa<CXXMethodDecl>(FD);
8530 if (IsMethod) {
8531 auto *MD = cast<CXXMethodDecl>(FD);
8532 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", 8532, __extension__ __PRETTY_FUNCTION__
))
;
8533
8534 // If we're out-of-class, this is the class we're comparing.
8535 if (!RD)
8536 RD = MD->getParent();
8537
8538 if (!MD->isConst()) {
8539 SourceLocation InsertLoc;
8540 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8541 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8542 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8543 // corresponding defaulted 'operator<=>' already.
8544 if (!MD->isImplicit()) {
8545 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8546 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8547 }
8548
8549 // Add the 'const' to the type to recover.
8550 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8551 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8552 EPI.TypeQuals.addConst();
8553 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8554 FPT->getParamTypes(), EPI));
8555 }
8556 }
8557
8558 if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
8559 // Let's not worry about using a variadic template pack here -- who would do
8560 // such a thing?
8561 Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8562 << int(IsMethod) << int(DCK);
8563 return true;
8564 }
8565
8566 const ParmVarDecl *KnownParm = nullptr;
8567 for (const ParmVarDecl *Param : FD->parameters()) {
8568 QualType ParmTy = Param->getType();
8569 if (ParmTy->isDependentType())
8570 continue;
8571 if (!KnownParm) {
8572 auto CTy = ParmTy;
8573 // Is it `T const &`?
8574 bool Ok = !IsMethod;
8575 QualType ExpectedTy;
8576 if (RD)
8577 ExpectedTy = Context.getRecordType(RD);
8578 if (auto *Ref = CTy->getAs<ReferenceType>()) {
8579 CTy = Ref->getPointeeType();
8580 if (RD)
8581 ExpectedTy.addConst();
8582 Ok = true;
8583 }
8584
8585 // Is T a class?
8586 if (!Ok) {
8587 } else if (RD) {
8588 if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8589 Ok = false;
8590 } else if (auto *CRD = CTy->getAsRecordDecl()) {
8591 RD = cast<CXXRecordDecl>(CRD);
8592 } else {
8593 Ok = false;
8594 }
8595
8596 if (Ok) {
8597 KnownParm = Param;
8598 } else {
8599 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8600 // corresponding defaulted 'operator<=>' already.
8601 if (!FD->isImplicit()) {
8602 if (RD) {
8603 QualType PlainTy = Context.getRecordType(RD);
8604 QualType RefTy =
8605 Context.getLValueReferenceType(PlainTy.withConst());
8606 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8607 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8608 << Param->getSourceRange();
8609 } else {
8610 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", 8610, __extension__ __PRETTY_FUNCTION__
))
;
8611 Diag(FD->getLocation(),
8612 diag::err_defaulted_comparison_param_unknown)
8613 << int(DCK) << ParmTy << Param->getSourceRange();
8614 }
8615 }
8616 return true;
8617 }
8618 } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8619 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8620 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8621 << ParmTy << Param->getSourceRange();
8622 return true;
8623 }
8624 }
8625
8626 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", 8626, __extension__ __PRETTY_FUNCTION__
))
;
8627 if (IsMethod) {
8628 } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8629 // In-class, must be a friend decl.
8630 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", 8630, __extension__ __PRETTY_FUNCTION__
))
;
8631 } else {
8632 // Out of class, require the defaulted comparison to be a friend (of a
8633 // complete type).
8634 if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8635 diag::err_defaulted_comparison_not_friend, int(DCK),
8636 int(1)))
8637 return true;
8638
8639 if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8640 return FD->getCanonicalDecl() ==
8641 F->getFriendDecl()->getCanonicalDecl();
8642 })) {
8643 Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8644 << int(DCK) << int(0) << RD;
8645 Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8646 return true;
8647 }
8648 }
8649
8650 // C++2a [class.eq]p1, [class.rel]p1:
8651 // A [defaulted comparison other than <=>] shall have a declared return
8652 // type bool.
8653 if (DCK != DefaultedComparisonKind::ThreeWay &&
8654 !FD->getDeclaredReturnType()->isDependentType() &&
8655 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8656 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8657 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8658 << FD->getReturnTypeSourceRange();
8659 return true;
8660 }
8661 // C++2a [class.spaceship]p2 [P2002R0]:
8662 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8663 // R shall not contain a placeholder type.
8664 if (DCK == DefaultedComparisonKind::ThreeWay &&
8665 FD->getDeclaredReturnType()->getContainedDeducedType() &&
8666 !Context.hasSameType(FD->getDeclaredReturnType(),
8667 Context.getAutoDeductType())) {
8668 Diag(FD->getLocation(),
8669 diag::err_defaulted_comparison_deduced_return_type_not_auto)
8670 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8671 << FD->getReturnTypeSourceRange();
8672 return true;
8673 }
8674
8675 // For a defaulted function in a dependent class, defer all remaining checks
8676 // until instantiation.
8677 if (RD->isDependentType())
8678 return false;
8679
8680 // Determine whether the function should be defined as deleted.
8681 DefaultedComparisonInfo Info =
8682 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8683
8684 bool First = FD == FD->getCanonicalDecl();
8685
8686 // If we want to delete the function, then do so; there's nothing else to
8687 // check in that case.
8688 if (Info.Deleted) {
8689 if (!First) {
8690 // C++11 [dcl.fct.def.default]p4:
8691 // [For a] user-provided explicitly-defaulted function [...] if such a
8692 // function is implicitly defined as deleted, the program is ill-formed.
8693 //
8694 // This is really just a consequence of the general rule that you can
8695 // only delete a function on its first declaration.
8696 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8697 << FD->isImplicit() << (int)DCK;
8698 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8699 DefaultedComparisonAnalyzer::ExplainDeleted)
8700 .visit();
8701 return true;
8702 }
8703
8704 SetDeclDeleted(FD, FD->getLocation());
8705 if (!inTemplateInstantiation() && !FD->isImplicit()) {
8706 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8707 << (int)DCK;
8708 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8709 DefaultedComparisonAnalyzer::ExplainDeleted)
8710 .visit();
8711 }
8712 return false;
8713 }
8714
8715 // C++2a [class.spaceship]p2:
8716 // The return type is deduced as the common comparison type of R0, R1, ...
8717 if (DCK == DefaultedComparisonKind::ThreeWay &&
8718 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8719 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8720 if (RetLoc.isInvalid())
8721 RetLoc = FD->getBeginLoc();
8722 // FIXME: Should we really care whether we have the complete type and the
8723 // 'enumerator' constants here? A forward declaration seems sufficient.
8724 QualType Cat = CheckComparisonCategoryType(
8725 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8726 if (Cat.isNull())
8727 return true;
8728 Context.adjustDeducedFunctionResultType(
8729 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8730 }
8731
8732 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8733 // An explicitly-defaulted function that is not defined as deleted may be
8734 // declared constexpr or consteval only if it is constexpr-compatible.
8735 // C++2a [class.compare.default]p3 [P2002R0]:
8736 // A defaulted comparison function is constexpr-compatible if it satisfies
8737 // the requirements for a constexpr function [...]
8738 // The only relevant requirements are that the parameter and return types are
8739 // literal types. The remaining conditions are checked by the analyzer.
8740 if (FD->isConstexpr()) {
8741 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8742 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8743 !Info.Constexpr) {
8744 Diag(FD->getBeginLoc(),
8745 diag::err_incorrect_defaulted_comparison_constexpr)
8746 << FD->isImplicit() << (int)DCK << FD->isConsteval();
8747 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8748 DefaultedComparisonAnalyzer::ExplainConstexpr)
8749 .visit();
8750 }
8751 }
8752
8753 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8754 // If a constexpr-compatible function is explicitly defaulted on its first
8755 // declaration, it is implicitly considered to be constexpr.
8756 // FIXME: Only applying this to the first declaration seems problematic, as
8757 // simple reorderings can affect the meaning of the program.
8758 if (First && !FD->isConstexpr() && Info.Constexpr)
8759 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8760
8761 // C++2a [except.spec]p3:
8762 // If a declaration of a function does not have a noexcept-specifier
8763 // [and] is defaulted on its first declaration, [...] the exception
8764 // specification is as specified below
8765 if (FD->getExceptionSpecType() == EST_None) {
8766 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8767 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8768 EPI.ExceptionSpec.Type = EST_Unevaluated;
8769 EPI.ExceptionSpec.SourceDecl = FD;
8770 FD->setType(Context.getFunctionType(FPT->getReturnType(),
8771 FPT->getParamTypes(), EPI));
8772 }
8773
8774 return false;
8775}
8776
8777void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8778 FunctionDecl *Spaceship) {
8779 Sema::CodeSynthesisContext Ctx;
8780 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8781 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8782 Ctx.Entity = Spaceship;
8783 pushCodeSynthesisContext(Ctx);
8784
8785 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8786 EqualEqual->setImplicit();
8787
8788 popCodeSynthesisContext();
8789}
8790
8791void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8792 DefaultedComparisonKind DCK) {
8793 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", 8794, __extension__ __PRETTY_FUNCTION__
))
8794 !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", 8794, __extension__ __PRETTY_FUNCTION__
))
;
8795 if (FD->willHaveBody() || FD->isInvalidDecl())
8796 return;
8797
8798 SynthesizedFunctionScope Scope(*this, FD);
8799
8800 // Add a context note for diagnostics produced after this point.
8801 Scope.addContextNote(UseLoc);
8802
8803 {
8804 // Build and set up the function body.
8805 // The first parameter has type maybe-ref-to maybe-const T, use that to get
8806 // the type of the class being compared.
8807 auto PT = FD->getParamDecl(0)->getType();
8808 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
8809 SourceLocation BodyLoc =
8810 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8811 StmtResult Body =
8812 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8813 if (Body.isInvalid()) {
8814 FD->setInvalidDecl();
8815 return;
8816 }
8817 FD->setBody(Body.get());
8818 FD->markUsed(Context);
8819 }
8820
8821 // The exception specification is needed because we are defining the
8822 // function. Note that this will reuse the body we just built.
8823 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8824
8825 if (ASTMutationListener *L = getASTMutationListener())
8826 L->CompletedImplicitDefinition(FD);
8827}
8828
8829static Sema::ImplicitExceptionSpecification
8830ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8831 FunctionDecl *FD,
8832 Sema::DefaultedComparisonKind DCK) {
8833 ComputingExceptionSpec CES(S, FD, Loc);
8834 Sema::ImplicitExceptionSpecification ExceptSpec(S);
8835
8836 if (FD->isInvalidDecl())
8837 return ExceptSpec;
8838
8839 // The common case is that we just defined the comparison function. In that
8840 // case, just look at whether the body can throw.
8841 if (FD->hasBody()) {
8842 ExceptSpec.CalledStmt(FD->getBody());
8843 } else {
8844 // Otherwise, build a body so we can check it. This should ideally only
8845 // happen when we're not actually marking the function referenced. (This is
8846 // only really important for efficiency: we don't want to build and throw
8847 // away bodies for comparison functions more than we strictly need to.)
8848
8849 // Pretend to synthesize the function body in an unevaluated context.
8850 // Note that we can't actually just go ahead and define the function here:
8851 // we are not permitted to mark its callees as referenced.
8852 Sema::SynthesizedFunctionScope Scope(S, FD);
8853 EnterExpressionEvaluationContext Context(
8854 S, Sema::ExpressionEvaluationContext::Unevaluated);
8855
8856 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8857 SourceLocation BodyLoc =
8858 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8859 StmtResult Body =
8860 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8861 if (!Body.isInvalid())
8862 ExceptSpec.CalledStmt(Body.get());
8863
8864 // FIXME: Can we hold onto this body and just transform it to potentially
8865 // evaluated when we're asked to define the function rather than rebuilding
8866 // it? Either that, or we should only build the bits of the body that we
8867 // need (the expressions, not the statements).
8868 }
8869
8870 return ExceptSpec;
8871}
8872
8873void Sema::CheckDelayedMemberExceptionSpecs() {
8874 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8875 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8876
8877 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8878 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8879
8880 // Perform any deferred checking of exception specifications for virtual
8881 // destructors.
8882 for (auto &Check : Overriding)
8883 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8884
8885 // Perform any deferred checking of exception specifications for befriended
8886 // special members.
8887 for (auto &Check : Equivalent)
8888 CheckEquivalentExceptionSpec(Check.second, Check.first);
8889}
8890
8891namespace {
8892/// CRTP base class for visiting operations performed by a special member
8893/// function (or inherited constructor).
8894template<typename Derived>
8895struct SpecialMemberVisitor {
8896 Sema &S;
8897 CXXMethodDecl *MD;
8898 Sema::CXXSpecialMember CSM;
8899 Sema::InheritedConstructorInfo *ICI;
8900
8901 // Properties of the special member, computed for convenience.
8902 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8903
8904 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8905 Sema::InheritedConstructorInfo *ICI)
8906 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8907 switch (CSM) {
8908 case Sema::CXXDefaultConstructor:
8909 case Sema::CXXCopyConstructor:
8910 case Sema::CXXMoveConstructor:
8911 IsConstructor = true;
8912 break;
8913 case Sema::CXXCopyAssignment:
8914 case Sema::CXXMoveAssignment:
8915 IsAssignment = true;
8916 break;
8917 case Sema::CXXDestructor:
8918 break;
8919 case Sema::CXXInvalid:
8920 llvm_unreachable("invalid special member kind")::llvm::llvm_unreachable_internal("invalid special member kind"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8920)
;
8921 }
8922
8923 if (MD->getNumParams()) {
8924 if (const ReferenceType *RT =
8925 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8926 ConstArg = RT->getPointeeType().isConstQualified();
8927 }
8928 }
8929
8930 Derived &getDerived() { return static_cast<Derived&>(*this); }
8931
8932 /// Is this a "move" special member?
8933 bool isMove() const {
8934 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8935 }
8936
8937 /// Look up the corresponding special member in the given class.
8938 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8939 unsigned Quals, bool IsMutable) {
8940 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8941 ConstArg && !IsMutable);
8942 }
8943
8944 /// Look up the constructor for the specified base class to see if it's
8945 /// overridden due to this being an inherited constructor.
8946 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8947 if (!ICI)
8948 return {};
8949 assert(CSM == Sema::CXXDefaultConstructor)(static_cast <bool> (CSM == Sema::CXXDefaultConstructor
) ? void (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor"
, "clang/lib/Sema/SemaDeclCXX.cpp", 8949, __extension__ __PRETTY_FUNCTION__
))
;
8950 auto *BaseCtor =
8951 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8952 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8953 return MD;
8954 return {};
8955 }
8956
8957 /// A base or member subobject.
8958 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8959
8960 /// Get the location to use for a subobject in diagnostics.
8961 static SourceLocation getSubobjectLoc(Subobject Subobj) {
8962 // FIXME: For an indirect virtual base, the direct base leading to
8963 // the indirect virtual base would be a more useful choice.
8964 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8965 return B->getBaseTypeLoc();
8966 else
8967 return Subobj.get<FieldDecl*>()->getLocation();
8968 }
8969
8970 enum BasesToVisit {
8971 /// Visit all non-virtual (direct) bases.
8972 VisitNonVirtualBases,
8973 /// Visit all direct bases, virtual or not.
8974 VisitDirectBases,
8975 /// Visit all non-virtual bases, and all virtual bases if the class
8976 /// is not abstract.
8977 VisitPotentiallyConstructedBases,
8978 /// Visit all direct or virtual bases.
8979 VisitAllBases
8980 };
8981
8982 // Visit the bases and members of the class.
8983 bool visit(BasesToVisit Bases) {
8984 CXXRecordDecl *RD = MD->getParent();
8985
8986 if (Bases == VisitPotentiallyConstructedBases)
8987 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8988
8989 for (auto &B : RD->bases())
8990 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8991 getDerived().visitBase(&B))
8992 return true;
8993
8994 if (Bases == VisitAllBases)
8995 for (auto &B : RD->vbases())
8996 if (getDerived().visitBase(&B))
8997 return true;
8998
8999 for (auto *F : RD->fields())
9000 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
9001 getDerived().visitField(F))
9002 return true;
9003
9004 return false;
9005 }
9006};
9007}
9008
9009namespace {
9010struct SpecialMemberDeletionInfo
9011 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9012 bool Diagnose;
9013
9014 SourceLocation Loc;
9015
9016 bool AllFieldsAreConst;
9017
9018 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9019 Sema::CXXSpecialMember CSM,
9020 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9021 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9022 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9023
9024 bool inUnion() const { return MD->getParent()->isUnion(); }
9025
9026 Sema::CXXSpecialMember getEffectiveCSM() {
9027 return ICI ? Sema::CXXInvalid : CSM;
9028 }
9029
9030 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9031
9032 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9033 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9034
9035 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9036 bool shouldDeleteForField(FieldDecl *FD);
9037 bool shouldDeleteForAllConstMembers();
9038
9039 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9040 unsigned Quals);
9041 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9042 Sema::SpecialMemberOverloadResult SMOR,
9043 bool IsDtorCallInCtor);
9044
9045 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9046};
9047}
9048
9049/// Is the given special member inaccessible when used on the given
9050/// sub-object.
9051bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9052 CXXMethodDecl *target) {
9053 /// If we're operating on a base class, the object type is the
9054 /// type of this special member.
9055 QualType objectTy;
9056 AccessSpecifier access = target->getAccess();
9057 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9058 objectTy = S.Context.getTypeDeclType(MD->getParent());
9059 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9060
9061 // If we're operating on a field, the object type is the type of the field.
9062 } else {
9063 objectTy = S.Context.getTypeDeclType(target->getParent());
9064 }
9065
9066 return S.isMemberAccessibleForDeletion(
9067 target->getParent(), DeclAccessPair::make(target, access), objectTy);
9068}
9069
9070/// Check whether we should delete a special member due to the implicit
9071/// definition containing a call to a special member of a subobject.
9072bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9073 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9074 bool IsDtorCallInCtor) {
9075 CXXMethodDecl *Decl = SMOR.getMethod();
9076 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9077
9078 int DiagKind = -1;
9079
9080 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9081 DiagKind = !Decl ? 0 : 1;
9082 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9083 DiagKind = 2;
9084 else if (!isAccessible(Subobj, Decl))
9085 DiagKind = 3;
9086 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9087 !Decl->isTrivial()) {
9088 // A member of a union must have a trivial corresponding special member.
9089 // As a weird special case, a destructor call from a union's constructor
9090 // must be accessible and non-deleted, but need not be trivial. Such a
9091 // destructor is never actually called, but is semantically checked as
9092 // if it were.
9093 DiagKind = 4;
9094 }
9095
9096 if (DiagKind == -1)
9097 return false;
9098
9099 if (Diagnose) {
9100 if (Field) {
9101 S.Diag(Field->getLocation(),
9102 diag::note_deleted_special_member_class_subobject)
9103 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9104 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9105 } else {
9106 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9107 S.Diag(Base->getBeginLoc(),
9108 diag::note_deleted_special_member_class_subobject)
9109 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9110 << Base->getType() << DiagKind << IsDtorCallInCtor
9111 << /*IsObjCPtr*/false;
9112 }
9113
9114 if (DiagKind == 1)
9115 S.NoteDeletedFunction(Decl);
9116 // FIXME: Explain inaccessibility if DiagKind == 3.
9117 }
9118
9119 return true;
9120}
9121
9122/// Check whether we should delete a special member function due to having a
9123/// direct or virtual base class or non-static data member of class type M.
9124bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9125 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9126 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9127 bool IsMutable = Field && Field->isMutable();
9128
9129 // C++11 [class.ctor]p5:
9130 // -- any direct or virtual base class, or non-static data member with no
9131 // brace-or-equal-initializer, has class type M (or array thereof) and
9132 // either M has no default constructor or overload resolution as applied
9133 // to M's default constructor results in an ambiguity or in a function
9134 // that is deleted or inaccessible
9135 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9136 // -- a direct or virtual base class B that cannot be copied/moved because
9137 // overload resolution, as applied to B's corresponding special member,
9138 // results in an ambiguity or a function that is deleted or inaccessible
9139 // from the defaulted special member
9140 // C++11 [class.dtor]p5:
9141 // -- any direct or virtual base class [...] has a type with a destructor
9142 // that is deleted or inaccessible
9143 if (!(CSM == Sema::CXXDefaultConstructor &&
9144 Field && Field->hasInClassInitializer()) &&
9145 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9146 false))
9147 return true;
9148
9149 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9150 // -- any direct or virtual base class or non-static data member has a
9151 // type with a destructor that is deleted or inaccessible
9152 if (IsConstructor) {
9153 Sema::SpecialMemberOverloadResult SMOR =
9154 S.LookupSpecialMember(Class, Sema::CXXDestructor,
9155 false, false, false, false, false);
9156 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9157 return true;
9158 }
9159
9160 return false;
9161}
9162
9163bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9164 FieldDecl *FD, QualType FieldType) {
9165 // The defaulted special functions are defined as deleted if this is a variant
9166 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9167 // type under ARC.
9168 if (!FieldType.hasNonTrivialObjCLifetime())
9169 return false;
9170
9171 // Don't make the defaulted default constructor defined as deleted if the
9172 // member has an in-class initializer.
9173 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9174 return false;
9175
9176 if (Diagnose) {
9177 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9178 S.Diag(FD->getLocation(),
9179 diag::note_deleted_special_member_class_subobject)
9180 << getEffectiveCSM() << ParentClass << /*IsField*/true
9181 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9182 }
9183
9184 return true;
9185}
9186
9187/// Check whether we should delete a special member function due to the class
9188/// having a particular direct or virtual base class.
9189bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9190 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9191 // If program is correct, BaseClass cannot be null, but if it is, the error
9192 // must be reported elsewhere.
9193 if (!BaseClass)
9194 return false;
9195 // If we have an inheriting constructor, check whether we're calling an
9196 // inherited constructor instead of a default constructor.
9197 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9198 if (auto *BaseCtor = SMOR.getMethod()) {
9199 // Note that we do not check access along this path; other than that,
9200 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9201 // FIXME: Check that the base has a usable destructor! Sink this into
9202 // shouldDeleteForClassSubobject.
9203 if (BaseCtor->isDeleted() && Diagnose) {
9204 S.Diag(Base->getBeginLoc(),
9205 diag::note_deleted_special_member_class_subobject)
9206 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9207 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9208 << /*IsObjCPtr*/false;
9209 S.NoteDeletedFunction(BaseCtor);
9210 }
9211 return BaseCtor->isDeleted();
9212 }
9213 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9214}
9215
9216/// Check whether we should delete a special member function due to the class
9217/// having a particular non-static data member.
9218bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9219 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9220 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9221
9222 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9223 return true;
9224
9225 if (CSM == Sema::CXXDefaultConstructor) {
9226 // For a default constructor, all references must be initialized in-class
9227 // and, if a union, it must have a non-const member.
9228 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9229 if (Diagnose)
9230 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9231 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9232 return true;
9233 }
9234 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9235 // data member of const-qualified type (or array thereof) with no
9236 // brace-or-equal-initializer is not const-default-constructible.
9237 if (!inUnion() && FieldType.isConstQualified() &&
9238 !FD->hasInClassInitializer() &&
9239 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9240 if (Diagnose)
9241 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9242 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9243 return true;
9244 }
9245
9246 if (inUnion() && !FieldType.isConstQualified())
9247 AllFieldsAreConst = false;
9248 } else if (CSM == Sema::CXXCopyConstructor) {
9249 // For a copy constructor, data members must not be of rvalue reference
9250 // type.
9251 if (FieldType->isRValueReferenceType()) {
9252 if (Diagnose)
9253 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9254 << MD->getParent() << FD << FieldType;
9255 return true;
9256 }
9257 } else if (IsAssignment) {
9258 // For an assignment operator, data members must not be of reference type.
9259 if (FieldType->isReferenceType()) {
9260 if (Diagnose)
9261 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9262 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9263 return true;
9264 }
9265 if (!FieldRecord && FieldType.isConstQualified()) {
9266 // C++11 [class.copy]p23:
9267 // -- a non-static data member of const non-class type (or array thereof)
9268 if (Diagnose)
9269 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9270 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9271 return true;
9272 }
9273 }
9274
9275 if (FieldRecord) {
9276 // Some additional restrictions exist on the variant members.
9277 if (!inUnion() && FieldRecord->isUnion() &&
9278 FieldRecord->isAnonymousStructOrUnion()) {
9279 bool AllVariantFieldsAreConst = true;
9280
9281 // FIXME: Handle anonymous unions declared within anonymous unions.
9282 for (auto *UI : FieldRecord->fields()) {
9283 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9284
9285 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9286 return true;
9287
9288 if (!UnionFieldType.isConstQualified())
9289 AllVariantFieldsAreConst = false;
9290
9291 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9292 if (UnionFieldRecord &&
9293 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9294 UnionFieldType.getCVRQualifiers()))
9295 return true;
9296 }
9297
9298 // At least one member in each anonymous union must be non-const
9299 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9300 !FieldRecord->field_empty()) {
9301 if (Diagnose)
9302 S.Diag(FieldRecord->getLocation(),
9303 diag::note_deleted_default_ctor_all_const)
9304 << !!ICI << MD->getParent() << /*anonymous union*/1;
9305 return true;
9306 }
9307
9308 // Don't check the implicit member of the anonymous union type.
9309 // This is technically non-conformant but supported, and we have a
9310 // diagnostic for this elsewhere.
9311 return false;
9312 }
9313
9314 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9315 FieldType.getCVRQualifiers()))
9316 return true;
9317 }
9318
9319 return false;
9320}
9321
9322/// C++11 [class.ctor] p5:
9323/// A defaulted default constructor for a class X is defined as deleted if
9324/// X is a union and all of its variant members are of const-qualified type.
9325bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9326 // This is a silly definition, because it gives an empty union a deleted
9327 // default constructor. Don't do that.
9328 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9329 bool AnyFields = false;
9330 for (auto *F : MD->getParent()->fields())
9331 if ((AnyFields = !F->isUnnamedBitfield()))
9332 break;
9333 if (!AnyFields)
9334 return false;
9335 if (Diagnose)
9336 S.Diag(MD->getParent()->getLocation(),
9337 diag::note_deleted_default_ctor_all_const)
9338 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9339 return true;
9340 }
9341 return false;
9342}
9343
9344/// Determine whether a defaulted special member function should be defined as
9345/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9346/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9347bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9348 InheritedConstructorInfo *ICI,
9349 bool Diagnose) {
9350 if (MD->isInvalidDecl())
9351 return false;
9352 CXXRecordDecl *RD = MD->getParent();
9353 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", 9353, __extension__ __PRETTY_FUNCTION__
))
;
9354 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9355 return false;
9356
9357 // C++11 [expr.lambda.prim]p19:
9358 // The closure type associated with a lambda-expression has a
9359 // deleted (8.4.3) default constructor and a deleted copy
9360 // assignment operator.
9361 // C++2a adds back these operators if the lambda has no lambda-capture.
9362 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9363 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9364 if (Diagnose)
9365 Diag(RD->getLocation(), diag::note_lambda_decl);
9366 return true;
9367 }
9368
9369 // For an anonymous struct or union, the copy and assignment special members
9370 // will never be used, so skip the check. For an anonymous union declared at
9371 // namespace scope, the constructor and destructor are used.
9372 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9373 RD->isAnonymousStructOrUnion())
9374 return false;
9375
9376 // C++11 [class.copy]p7, p18:
9377 // If the class definition declares a move constructor or move assignment
9378 // operator, an implicitly declared copy constructor or copy assignment
9379 // operator is defined as deleted.
9380 if (MD->isImplicit() &&
9381 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9382 CXXMethodDecl *UserDeclaredMove = nullptr;
9383
9384 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9385 // deletion of the corresponding copy operation, not both copy operations.
9386 // MSVC 2015 has adopted the standards conforming behavior.
9387 bool DeletesOnlyMatchingCopy =
9388 getLangOpts().MSVCCompat &&
9389 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9390
9391 if (RD->hasUserDeclaredMoveConstructor() &&
9392 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9393 if (!Diagnose) return true;
9394
9395 // Find any user-declared move constructor.
9396 for (auto *I : RD->ctors()) {
9397 if (I->isMoveConstructor()) {
9398 UserDeclaredMove = I;
9399 break;
9400 }
9401 }
9402 assert(UserDeclaredMove)(static_cast <bool> (UserDeclaredMove) ? void (0) : __assert_fail
("UserDeclaredMove", "clang/lib/Sema/SemaDeclCXX.cpp", 9402,
__extension__ __PRETTY_FUNCTION__))
;
9403 } else if (RD->hasUserDeclaredMoveAssignment() &&
9404 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9405 if (!Diagnose) return true;
9406
9407 // Find any user-declared move assignment operator.
9408 for (auto *I : RD->methods()) {
9409 if (I->isMoveAssignmentOperator()) {
9410 UserDeclaredMove = I;
9411 break;
9412 }
9413 }
9414 assert(UserDeclaredMove)(static_cast <bool> (UserDeclaredMove) ? void (0) : __assert_fail
("UserDeclaredMove", "clang/lib/Sema/SemaDeclCXX.cpp", 9414,
__extension__ __PRETTY_FUNCTION__))
;
9415 }
9416
9417 if (UserDeclaredMove) {
9418 Diag(UserDeclaredMove->getLocation(),
9419 diag::note_deleted_copy_user_declared_move)
9420 << (CSM == CXXCopyAssignment) << RD
9421 << UserDeclaredMove->isMoveAssignmentOperator();
9422 return true;
9423 }
9424 }
9425
9426 // Do access control from the special member function
9427 ContextRAII MethodContext(*this, MD);
9428
9429 // C++11 [class.dtor]p5:
9430 // -- for a virtual destructor, lookup of the non-array deallocation function
9431 // results in an ambiguity or in a function that is deleted or inaccessible
9432 if (CSM == CXXDestructor && MD->isVirtual()) {
9433 FunctionDecl *OperatorDelete = nullptr;
9434 DeclarationName Name =
9435 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9436 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9437 OperatorDelete, /*Diagnose*/false)) {
9438 if (Diagnose)
9439 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9440 return true;
9441 }
9442 }
9443
9444 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9445
9446 // Per DR1611, do not consider virtual bases of constructors of abstract
9447 // classes, since we are not going to construct them.
9448 // Per DR1658, do not consider virtual bases of destructors of abstract
9449 // classes either.
9450 // Per DR2180, for assignment operators we only assign (and thus only
9451 // consider) direct bases.
9452 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9453 : SMI.VisitPotentiallyConstructedBases))
9454 return true;
9455
9456 if (SMI.shouldDeleteForAllConstMembers())
9457 return true;
9458
9459 if (getLangOpts().CUDA) {
9460 // We should delete the special member in CUDA mode if target inference
9461 // failed.
9462 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9463 // is treated as certain special member, which may not reflect what special
9464 // member MD really is. However inferCUDATargetForImplicitSpecialMember
9465 // expects CSM to match MD, therefore recalculate CSM.
9466 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", 9466, __extension__ __PRETTY_FUNCTION__
))
;
9467 auto RealCSM = CSM;
9468 if (ICI)
9469 RealCSM = getSpecialMember(MD);
9470
9471 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9472 SMI.ConstArg, Diagnose);
9473 }
9474
9475 return false;
9476}
9477
9478void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9479 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9480 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", 9480, __extension__ __PRETTY_FUNCTION__
))
;
9481 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", 9481, __extension__ __PRETTY_FUNCTION__
))
;
9482
9483 if (DFK.isSpecialMember()) {
9484 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9485 nullptr, /*Diagnose=*/true);
9486 } else {
9487 DefaultedComparisonAnalyzer(
9488 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9489 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9490 .visit();
9491 }
9492}
9493
9494/// Perform lookup for a special member of the specified kind, and determine
9495/// whether it is trivial. If the triviality can be determined without the
9496/// lookup, skip it. This is intended for use when determining whether a
9497/// special member of a containing object is trivial, and thus does not ever
9498/// perform overload resolution for default constructors.
9499///
9500/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9501/// member that was most likely to be intended to be trivial, if any.
9502///
9503/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9504/// determine whether the special member is trivial.
9505static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9506 Sema::CXXSpecialMember CSM, unsigned Quals,
9507 bool ConstRHS,
9508 Sema::TrivialABIHandling TAH,
9509 CXXMethodDecl **Selected) {
9510 if (Selected)
9511 *Selected = nullptr;
9512
9513 switch (CSM) {
9514 case Sema::CXXInvalid:
9515 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "clang/lib/Sema/SemaDeclCXX.cpp"
, 9515)
;
9516
9517 case Sema::CXXDefaultConstructor:
9518 // C++11 [class.ctor]p5:
9519 // A default constructor is trivial if:
9520 // - all the [direct subobjects] have trivial default constructors
9521 //
9522 // Note, no overload resolution is performed in this case.
9523 if (RD->hasTrivialDefaultConstructor())
9524 return true;
9525
9526 if (Selected) {
9527 // If there's a default constructor which could have been trivial, dig it
9528 // out. Otherwise, if there's any user-provided default constructor, point
9529 // to that as an example of why there's not a trivial one.
9530 CXXConstructorDecl *DefCtor = nullptr;
9531 if (RD->needsImplicitDefaultConstructor())
9532 S.DeclareImplicitDefaultConstructor(RD);
9533 for (auto *CI : RD->ctors()) {
9534 if (!CI->isDefaultConstructor())
9535 continue;
9536 DefCtor = CI;
9537 if (!DefCtor->isUserProvided())
9538 break;
9539 }
9540
9541 *Selected = DefCtor;
9542 }
9543
9544 return false;
9545
9546 case Sema::CXXDestructor:
9547 // C++11 [class.dtor]p5:
9548 // A destructor is trivial if:
9549 // - all the direct [subobjects] have trivial destructors
9550 if (RD->hasTrivialDestructor() ||
9551 (TAH == Sema::TAH_ConsiderTrivialABI &&
9552 RD->hasTrivialDestructorForCall()))
9553 return true;
9554
9555 if (Selected) {
9556 if (RD->needsImplicitDestructor())
9557 S.DeclareImplicitDestructor(RD);
9558 *Selected = RD->getDestructor();
9559 }
9560
9561 return false;
9562
9563 case Sema::CXXCopyConstructor:
9564 // C++11 [class.copy]p12:
9565 // A copy constructor is trivial if:
9566 // - the constructor selected to copy each direct [subobject] is trivial
9567 if (RD->hasTrivialCopyConstructor() ||
9568 (TAH == Sema::TAH_ConsiderTrivialABI &&
9569 RD->hasTrivialCopyConstructorForCall())) {
9570 if (Quals == Qualifiers::Const)
9571 // We must either select the trivial copy constructor or reach an
9572 // ambiguity; no need to actually perform overload resolution.
9573 return true;
9574 } else if (!Selected) {
9575 return false;
9576 }
9577 // In C++98, we are not supposed to perform overload resolution here, but we
9578 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9579 // cases like B as having a non-trivial copy constructor:
9580 // struct A { template<typename T> A(T&); };
9581 // struct B { mutable A a; };
9582 goto NeedOverloadResolution;
9583
9584 case Sema::CXXCopyAssignment:
9585 // C++11 [class.copy]p25:
9586 // A copy assignment operator is trivial if:
9587 // - the assignment operator selected to copy each direct [subobject] is
9588 // trivial
9589 if (RD->hasTrivialCopyAssignment()) {
9590 if (Quals == Qualifiers::Const)
9591 return true;
9592 } else if (!Selected) {
9593 return false;
9594 }
9595 // In C++98, we are not supposed to perform overload resolution here, but we
9596 // treat that as a language defect.
9597 goto NeedOverloadResolution;
9598
9599 case Sema::CXXMoveConstructor:
9600 case Sema::CXXMoveAssignment:
9601 NeedOverloadResolution:
9602 Sema::SpecialMemberOverloadResult SMOR =
9603 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9604
9605 // The standard doesn't describe how to behave if the lookup is ambiguous.
9606 // We treat it as not making the member non-trivial, just like the standard
9607 // mandates for the default constructor. This should rarely matter, because
9608 // the member will also be deleted.
9609 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9610 return true;
9611
9612 if (!SMOR.getMethod()) {
9613 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", 9614, __extension__ __PRETTY_FUNCTION__
))
9614 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", 9614, __extension__ __PRETTY_FUNCTION__
))
;
9615 return false;
9616 }
9617
9618 // We deliberately don't check if we found a deleted special member. We're
9619 // not supposed to!
9620 if (Selected)
9621 *Selected = SMOR.getMethod();
9622
9623 if (TAH == Sema::TAH_ConsiderTrivialABI &&
9624 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9625 return SMOR.getMethod()->isTrivialForCall();
9626 return SMOR.getMethod()->isTrivial();
9627 }
9628
9629 llvm_unreachable("unknown special method kind")::llvm::llvm_unreachable_internal("unknown special method kind"
, "clang/lib/Sema/SemaDeclCXX.cpp", 9629)
;
9630}
9631
9632static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9633 for (auto *CI : RD->ctors())
9634 if (!CI->isImplicit())
9635 return CI;
9636
9637 // Look for constructor templates.
9638 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9639 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9640 if (CXXConstructorDecl *CD =
9641 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9642 return CD;
9643 }
9644
9645 return nullptr;
9646}
9647
9648/// The kind of subobject we are checking for triviality. The values of this
9649/// enumeration are used in diagnostics.
9650enum TrivialSubobjectKind {
9651 /// The subobject is a base class.
9652 TSK_BaseClass,
9653 /// The subobject is a non-static data member.
9654 TSK_Field,
9655 /// The object is actually the complete object.
9656 TSK_CompleteObject
9657};
9658
9659/// Check whether the special member selected for a given type would be trivial.
9660static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9661 QualType SubType, bool ConstRHS,
9662 Sema::CXXSpecialMember CSM,
9663 TrivialSubobjectKind Kind,
9664 Sema::TrivialABIHandling TAH, bool Diagnose) {
9665 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9666 if (!SubRD)
9667 return true;
9668
9669 CXXMethodDecl *Selected;
9670 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9671 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9672 return true;
9673
9674 if (Diagnose) {
9675 if (ConstRHS)
9676 SubType.addConst();
9677
9678 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9679 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9680 << Kind << SubType.getUnqualifiedType();
9681 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9682 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9683 } else if (!Selected)
9684 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9685 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9686 else if (Selected->isUserProvided()) {
9687 if (Kind == TSK_CompleteObject)
9688 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9689 << Kind << SubType.getUnqualifiedType() << CSM;
9690 else {
9691 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9692 << Kind << SubType.getUnqualifiedType() << CSM;
9693 S.Diag(Selected->getLocation(), diag::note_declared_at);
9694 }
9695 } else {
9696 if (Kind != TSK_CompleteObject)
9697 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9698 << Kind << SubType.getUnqualifiedType() << CSM;
9699
9700 // Explain why the defaulted or deleted special member isn't trivial.
9701 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9702 Diagnose);
9703 }
9704 }
9705
9706 return false;
9707}
9708
9709/// Check whether the members of a class type allow a special member to be
9710/// trivial.
9711static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9712 Sema::CXXSpecialMember CSM,
9713 bool ConstArg,
9714 Sema::TrivialABIHandling TAH,
9715 bool Diagnose) {
9716 for (const auto *FI : RD->fields()) {
9717 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9718 continue;
9719
9720 QualType FieldType = S.Context.getBaseElementType(FI->getType());
9721
9722 // Pretend anonymous struct or union members are members of this class.
9723 if (FI->isAnonymousStructOrUnion()) {
9724 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9725 CSM, ConstArg, TAH, Diagnose))
9726 return false;
9727 continue;
9728 }
9729
9730 // C++11 [class.ctor]p5:
9731 // A default constructor is trivial if [...]
9732 // -- no non-static data member of its class has a
9733 // brace-or-equal-initializer
9734 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9735 if (Diagnose)
9736 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9737 << FI;
9738 return false;
9739 }
9740
9741 // Objective C ARC 4.3.5:
9742 // [...] nontrivally ownership-qualified types are [...] not trivially
9743 // default constructible, copy constructible, move constructible, copy
9744 // assignable, move assignable, or destructible [...]
9745 if (FieldType.hasNonTrivialObjCLifetime()) {
9746 if (Diagnose)
9747 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9748 << RD << FieldType.getObjCLifetime();
9749 return false;
9750 }
9751
9752 bool ConstRHS = ConstArg && !FI->isMutable();
9753 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9754 CSM, TSK_Field, TAH, Diagnose))
9755 return false;
9756 }
9757
9758 return true;
9759}
9760
9761/// Diagnose why the specified class does not have a trivial special member of
9762/// the given kind.
9763void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9764 QualType Ty = Context.getRecordType(RD);
9765
9766 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9767 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9768 TSK_CompleteObject, TAH_IgnoreTrivialABI,
9769 /*Diagnose*/true);
9770}
9771
9772/// Determine whether a defaulted or deleted special member function is trivial,
9773/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9774/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9775bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9776 TrivialABIHandling TAH, bool Diagnose) {
9777 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", 9777, __extension__ __PRETTY_FUNCTION__
))
;
9778
9779 CXXRecordDecl *RD = MD->getParent();
9780
9781 bool ConstArg = false;
9782
9783 // C++11 [class.copy]p12, p25: [DR1593]
9784 // A [special member] is trivial if [...] its parameter-type-list is
9785 // equivalent to the parameter-type-list of an implicit declaration [...]
9786 switch (CSM) {
9787 case CXXDefaultConstructor:
9788 case CXXDestructor:
9789 // Trivial default constructors and destructors cannot have parameters.
9790 break;
9791
9792 case CXXCopyConstructor:
9793 case CXXCopyAssignment: {
9794 const ParmVarDecl *Param0 = MD->getParamDecl(0);
9795 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9796
9797 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
9798 // if they are not user-provided and their parameter-type-list is equivalent
9799 // to the parameter-type-list of an implicit declaration. This maintains the
9800 // behavior before dr2171 was implemented.
9801 //
9802 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
9803 // trivial, if they are not user-provided, regardless of the qualifiers on
9804 // the reference type.
9805 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
9806 LangOptions::ClangABI::Ver14;
9807 if (!RT ||
9808 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
9809 ClangABICompat14)) {
9810 if (Diagnose)
9811 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9812 << Param0->getSourceRange() << Param0->getType()
9813 << Context.getLValueReferenceType(
9814 Context.getRecordType(RD).withConst());
9815 return false;
9816 }
9817
9818 ConstArg = RT->getPointeeType().isConstQualified();
9819 break;
9820 }
9821
9822 case CXXMoveConstructor:
9823 case CXXMoveAssignment: {
9824 // Trivial move operations always have non-cv-qualified parameters.
9825 const ParmVarDecl *Param0 = MD->getParamDecl(0);
9826 const RValueReferenceType *RT =
9827 Param0->getType()->getAs<RValueReferenceType>();
9828 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9829 if (Diagnose)
9830 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9831 << Param0->getSourceRange() << Param0->getType()
9832 << Context.getRValueReferenceType(Context.getRecordType(RD));
9833 return false;
9834 }
9835 break;
9836 }
9837
9838 case CXXInvalid:
9839 llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "clang/lib/Sema/SemaDeclCXX.cpp"
, 9839)
;
9840 }
9841
9842 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9843 if (Diagnose)
9844 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9845 diag::note_nontrivial_default_arg)
9846 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9847 return false;
9848 }
9849 if (MD->isVariadic()) {
9850 if (Diagnose)
9851 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9852 return false;
9853 }
9854
9855 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9856 // A copy/move [constructor or assignment operator] is trivial if
9857 // -- the [member] selected to copy/move each direct base class subobject
9858 // is trivial
9859 //
9860 // C++11 [class.copy]p12, C++11 [class.copy]p25:
9861 // A [default constructor or destructor] is trivial if
9862 // -- all the direct base classes have trivial [default constructors or
9863 // destructors]
9864 for (const auto &BI : RD->bases())
9865 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9866 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9867 return false;
9868
9869 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9870 // A copy/move [constructor or assignment operator] for a class X is
9871 // trivial if
9872 // -- for each non-static data member of X that is of class type (or array
9873 // thereof), the constructor selected to copy/move that member is
9874 // trivial
9875 //
9876 // C++11 [class.copy]p12, C++11 [class.copy]p25:
9877 // A [default constructor or destructor] is trivial if
9878 // -- for all of the non-static data members of its class that are of class
9879 // type (or array thereof), each such class has a trivial [default
9880 // constructor or destructor]
9881 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9882 return false;
9883
9884 // C++11 [class.dtor]p5:
9885 // A destructor is trivial if [...]
9886 // -- the destructor is not virtual
9887 if (CSM == CXXDestructor && MD->isVirtual()) {
9888 if (Diagnose)
9889 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9890 return false;
9891 }
9892
9893 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9894 // A [special member] for class X is trivial if [...]
9895 // -- class X has no virtual functions and no virtual base classes
9896 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9897 if (!Diagnose)
9898 return false;
9899
9900 if (RD->getNumVBases()) {
9901 // Check for virtual bases. We already know that the corresponding
9902 // member in all bases is trivial, so vbases must all be direct.
9903 CXXBaseSpecifier &BS = *RD->vbases_begin();
9904 assert(BS.isVirtual())(static_cast <bool> (BS.isVirtual()) ? void (0) : __assert_fail
("BS.isVirtual()", "clang/lib/Sema/SemaDeclCXX.cpp", 9904, __extension__
__PRETTY_FUNCTION__))
;
9905 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9906 return false;
9907 }
9908
9909 // Must have a virtual method.
9910 for (const auto *MI : RD->methods()) {
9911 if (MI->isVirtual()) {
9912 SourceLocation MLoc = MI->getBeginLoc();
9913 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9914 return false;
9915 }
9916 }
9917
9918 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", 9918)
;
9919 }
9920
9921 // Looks like it's trivial!
9922 return true;
9923}
9924
9925namespace {
9926struct FindHiddenVirtualMethod {
9927 Sema *S;
9928 CXXMethodDecl *Method;
9929 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9930 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9931
9932private:
9933 /// Check whether any most overridden method from MD in Methods
9934 static bool CheckMostOverridenMethods(
9935 const CXXMethodDecl *MD,
9936 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9937 if (MD->size_overridden_methods() == 0)
9938 return Methods.count(MD->getCanonicalDecl());
9939 for (const CXXMethodDecl *O : MD->overridden_methods())
9940 if (CheckMostOverridenMethods(O, Methods))
9941 return true;
9942 return false;
9943 }
9944
9945public:
9946 /// Member lookup function that determines whether a given C++
9947 /// method overloads virtual methods in a base class without overriding any,
9948 /// to be used with CXXRecordDecl::lookupInBases().
9949 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9950 RecordDecl *BaseRecord =
9951 Specifier->getType()->castAs<RecordType>()->getDecl();
9952
9953 DeclarationName Name = Method->getDeclName();
9954 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", 9954, __extension__ __PRETTY_FUNCTION__
))
;
9955
9956 bool foundSameNameMethod = false;
9957 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9958 for (Path.Decls = BaseRecord->lookup(Name).begin();
9959 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9960 NamedDecl *D = *Path.Decls;
9961 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9962 MD = MD->getCanonicalDecl();
9963 foundSameNameMethod = true;
9964 // Interested only in hidden virtual methods.
9965 if (!MD->isVirtual())
9966 continue;
9967 // If the method we are checking overrides a method from its base
9968 // don't warn about the other overloaded methods. Clang deviates from
9969 // GCC by only diagnosing overloads of inherited virtual functions that
9970 // do not override any other virtual functions in the base. GCC's
9971 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9972 // function from a base class. These cases may be better served by a
9973 // warning (not specific to virtual functions) on call sites when the
9974 // call would select a different function from the base class, were it
9975 // visible.
9976 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9977 if (!S->IsOverload(Method, MD, false))
9978 return true;
9979 // Collect the overload only if its hidden.
9980 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9981 overloadedMethods.push_back(MD);
9982 }
9983 }
9984
9985 if (foundSameNameMethod)
9986 OverloadedMethods.append(overloadedMethods.begin(),
9987 overloadedMethods.end());
9988 return foundSameNameMethod;
9989 }
9990};
9991} // end anonymous namespace
9992
9993/// Add the most overridden methods from MD to Methods
9994static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9995 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9996 if (MD->size_overridden_methods() == 0)
9997 Methods.insert(MD->getCanonicalDecl());
9998 else
9999 for (const CXXMethodDecl *O : MD->overridden_methods())
10000 AddMostOverridenMethods(O, Methods);
10001}
10002
10003/// Check if a method overloads virtual methods in a base class without
10004/// overriding any.
10005void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10006 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10007 if (!MD->getDeclName().isIdentifier())
10008 return;
10009
10010 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10011 /*bool RecordPaths=*/false,
10012 /*bool DetectVirtual=*/false);
10013 FindHiddenVirtualMethod FHVM;
10014 FHVM.Method = MD;
10015 FHVM.S = this;
10016
10017 // Keep the base methods that were overridden or introduced in the subclass
10018 // by 'using' in a set. A base method not in this set is hidden.
10019 CXXRecordDecl *DC = MD->getParent();
10020 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
10021 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
10022 NamedDecl *ND = *I;
10023 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10024 ND = shad->getTargetDecl();
10025 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10026 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10027 }
10028
10029 if (DC->lookupInBases(FHVM, Paths))
10030 OverloadedMethods = FHVM.OverloadedMethods;
10031}
10032
10033void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10034 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10035 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10036 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10037 PartialDiagnostic PD = PDiag(
10038 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10039 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10040 Diag(overloadedMD->getLocation(), PD);
10041 }
10042}
10043
10044/// Diagnose methods which overload virtual methods in a base class
10045/// without overriding any.
10046void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10047 if (MD->isInvalidDecl())
10048 return;
10049
10050 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10051 return;
10052
10053 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10054 FindHiddenVirtualMethods(MD, OverloadedMethods);
10055 if (!OverloadedMethods.empty()) {
10056 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10057 << MD << (OverloadedMethods.size() > 1);
10058
10059 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10060 }
10061}
10062
10063void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10064 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10065 // No diagnostics if this is a template instantiation.
10066 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
10067 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10068 diag::ext_cannot_use_trivial_abi) << &RD;
10069 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10070 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10071 }
10072 RD.dropAttr<TrivialABIAttr>();
10073 };
10074
10075 // Ill-formed if the copy and move constructors are deleted.
10076 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10077 // If the type is dependent, then assume it might have
10078 // implicit copy or move ctor because we won't know yet at this point.
10079 if (RD.isDependentType())
10080 return true;
10081 if (RD.needsImplicitCopyConstructor() &&
10082 !RD.defaultedCopyConstructorIsDeleted())
10083 return true;
10084 if (RD.needsImplicitMoveConstructor() &&
10085 !RD.defaultedMoveConstructorIsDeleted())
10086 return true;
10087 for (const CXXConstructorDecl *CD : RD.ctors())
10088 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10089 return true;
10090 return false;
10091 };
10092
10093 if (!HasNonDeletedCopyOrMoveConstructor()) {
10094 PrintDiagAndRemoveAttr(0);
10095 return;
10096 }
10097
10098 // Ill-formed if the struct has virtual functions.
10099 if (RD.isPolymorphic()) {
10100 PrintDiagAndRemoveAttr(1);
10101 return;
10102 }
10103
10104 for (const auto &B : RD.bases()) {
10105 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10106 // virtual base.
10107 if (!B.getType()->isDependentType() &&
10108 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10109 PrintDiagAndRemoveAttr(2);
10110 return;
10111 }
10112
10113 if (B.isVirtual()) {
10114 PrintDiagAndRemoveAttr(3);
10115 return;
10116 }
10117 }
10118
10119 for (const auto *FD : RD.fields()) {
10120 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10121 // non-trivial for the purpose of calls.
10122 QualType FT = FD->getType();
10123 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10124 PrintDiagAndRemoveAttr(4);
10125 return;
10126 }
10127
10128 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10129 if (!RT->isDependentType() &&
10130 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10131 PrintDiagAndRemoveAttr(5);
10132 return;
10133 }
10134 }
10135}
10136
10137void Sema::ActOnFinishCXXMemberSpecification(
10138 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10139 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10140 if (!TagDecl)
10141 return;
10142
10143 AdjustDeclIfTemplate(TagDecl);
10144
10145 for (const ParsedAttr &AL : AttrList) {
10146 if (AL.getKind() != ParsedAttr::AT_Visibility)
10147 continue;
10148 AL.setInvalid();
10149 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10150 }
10151
10152 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
10153 // strict aliasing violation!
10154 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
10155 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
10156
10157 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10158}
10159
10160/// Find the equality comparison functions that should be implicitly declared
10161/// in a given class definition, per C++2a [class.compare.default]p3.
10162static void findImplicitlyDeclaredEqualityComparisons(
10163 ASTContext &Ctx, CXXRecordDecl *RD,
10164 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10165 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10166 if (!RD->lookup(EqEq).empty())
10167 // Member operator== explicitly declared: no implicit operator==s.
10168 return;
10169
10170 // Traverse friends looking for an '==' or a '<=>'.
10171 for (FriendDecl *Friend : RD->friends()) {
10172 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10173 if (!FD) continue;
10174
10175 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10176 // Friend operator== explicitly declared: no implicit operator==s.
10177 Spaceships.clear();
10178 return;
10179 }
10180
10181 if (FD->getOverloadedOperator() == OO_Spaceship &&
10182 FD->isExplicitlyDefaulted())
10183 Spaceships.push_back(FD);
10184 }
10185
10186 // Look for members named 'operator<=>'.
10187 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10188 for (NamedDecl *ND : RD->lookup(Cmp)) {
10189 // Note that we could find a non-function here (either a function template
10190 // or a using-declaration). Neither case results in an implicit
10191 // 'operator=='.
10192 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10193 if (FD->isExplicitlyDefaulted())
10194 Spaceships.push_back(FD);
10195 }
10196}
10197
10198/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10199/// special functions, such as the default constructor, copy
10200/// constructor, or destructor, to the given C++ class (C++
10201/// [special]p1). This routine can only be executed just before the
10202/// definition of the class is complete.
10203void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10204 // Don't add implicit special members to templated classes.
10205 // FIXME: This means unqualified lookups for 'operator=' within a class
10206 // template don't work properly.
10207 if (!ClassDecl->isDependentType()) {
10208 if (ClassDecl->needsImplicitDefaultConstructor()) {
10209 ++getASTContext().NumImplicitDefaultConstructors;
10210
10211 if (ClassDecl->hasInheritedConstructor())
10212 DeclareImplicitDefaultConstructor(ClassDecl);
10213 }
10214
10215 if (ClassDecl->needsImplicitCopyConstructor()) {
10216 ++getASTContext().NumImplicitCopyConstructors;
10217
10218 // If the properties or semantics of the copy constructor couldn't be
10219 // determined while the class was being declared, force a declaration
10220 // of it now.
10221 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10222 ClassDecl->hasInheritedConstructor())
10223 DeclareImplicitCopyConstructor(ClassDecl);
10224 // For the MS ABI we need to know whether the copy ctor is deleted. A
10225 // prerequisite for deleting the implicit copy ctor is that the class has
10226 // a move ctor or move assignment that is either user-declared or whose
10227 // semantics are inherited from a subobject. FIXME: We should provide a
10228 // more direct way for CodeGen to ask whether the constructor was deleted.
10229 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10230 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10231 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10232 ClassDecl->hasUserDeclaredMoveAssignment() ||
10233 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10234 DeclareImplicitCopyConstructor(ClassDecl);
10235 }
10236
10237 if (getLangOpts().CPlusPlus11 &&
10238 ClassDecl->needsImplicitMoveConstructor()) {
10239 ++getASTContext().NumImplicitMoveConstructors;
10240
10241 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10242 ClassDecl->hasInheritedConstructor())
10243 DeclareImplicitMoveConstructor(ClassDecl);
10244 }
10245
10246 if (ClassDecl->needsImplicitCopyAssignment()) {
10247 ++getASTContext().NumImplicitCopyAssignmentOperators;
10248
10249 // If we have a dynamic class, then the copy assignment operator may be
10250 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10251 // it shows up in the right place in the vtable and that we diagnose
10252 // problems with the implicit exception specification.
10253 if (ClassDecl->isDynamicClass() ||
10254 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10255 ClassDecl->hasInheritedAssignment())
10256 DeclareImplicitCopyAssignment(ClassDecl);
10257 }
10258
10259 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10260 ++getASTContext().NumImplicitMoveAssignmentOperators;
10261
10262 // Likewise for the move assignment operator.
10263 if (ClassDecl->isDynamicClass() ||
10264 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10265 ClassDecl->hasInheritedAssignment())
10266 DeclareImplicitMoveAssignment(ClassDecl);
10267 }
10268
10269 if (ClassDecl->needsImplicitDestructor()) {
10270 ++getASTContext().NumImplicitDestructors;
10271
10272 // If we have a dynamic class, then the destructor may be virtual, so we
10273 // have to declare the destructor immediately. This ensures that, e.g., it
10274 // shows up in the right place in the vtable and that we diagnose problems
10275 // with the implicit exception specification.
10276 if (ClassDecl->isDynamicClass() ||
10277 ClassDecl->needsOverloadResolutionForDestructor())
10278 DeclareImplicitDestructor(ClassDecl);
10279 }
10280 }
10281
10282 // C++2a [class.compare.default]p3:
10283 // If the member-specification does not explicitly declare any member or
10284 // friend named operator==, an == operator function is declared implicitly
10285 // for each defaulted three-way comparison operator function defined in
10286 // the member-specification
10287 // FIXME: Consider doing this lazily.
10288 // We do this during the initial parse for a class template, not during
10289 // instantiation, so that we can handle unqualified lookups for 'operator=='
10290 // when parsing the template.
10291 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10292 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10293 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10294 DefaultedSpaceships);
10295 for (auto *FD : DefaultedSpaceships)
10296 DeclareImplicitEqualityComparison(ClassDecl, FD);
10297 }
10298}
10299
10300unsigned
10301Sema::ActOnReenterTemplateScope(Decl *D,
10302 llvm::function_ref<Scope *()> EnterScope) {
10303 if (!D)
10304 return 0;
10305 AdjustDeclIfTemplate(D);
10306
10307 // In order to get name lookup right, reenter template scopes in order from
10308 // outermost to innermost.
10309 SmallVector<TemplateParameterList *, 4> ParameterLists;
10310 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10311
10312 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10313 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10314 ParameterLists.push_back(DD->getTemplateParameterList(i));
10315
10316 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10317 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10318 ParameterLists.push_back(FTD->getTemplateParameters());
10319 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10320 LookupDC = VD->getDeclContext();
10321
10322 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10323 ParameterLists.push_back(VTD->getTemplateParameters());
10324 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10325 ParameterLists.push_back(PSD->getTemplateParameters());
10326 }
10327 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10328 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10329 ParameterLists.push_back(TD->getTemplateParameterList(i));
10330
10331 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10332 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10333 ParameterLists.push_back(CTD->getTemplateParameters());
10334 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10335 ParameterLists.push_back(PSD->getTemplateParameters());
10336 }
10337 }
10338 // FIXME: Alias declarations and concepts.
10339
10340 unsigned Count = 0;
10341 Scope *InnermostTemplateScope = nullptr;
10342 for (TemplateParameterList *Params : ParameterLists) {
10343 // Ignore explicit specializations; they don't contribute to the template
10344 // depth.
10345 if (Params->size() == 0)
10346 continue;
10347
10348 InnermostTemplateScope = EnterScope();
10349 for (NamedDecl *Param : *Params) {
10350 if (Param->getDeclName()) {
10351 InnermostTemplateScope->AddDecl(Param);
10352 IdResolver.AddDecl(Param);
10353 }
10354 }
10355 ++Count;
10356 }
10357
10358 // Associate the new template scopes with the corresponding entities.
10359 if (InnermostTemplateScope) {
10360 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", 10360, __extension__ __PRETTY_FUNCTION__
))
;
10361 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10362 }
10363
10364 return Count;
10365}
10366
10367void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10368 if (!RecordD) return;
10369 AdjustDeclIfTemplate(RecordD);
10370 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10371 PushDeclContext(S, Record);
10372}
10373
10374void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10375 if (!RecordD) return;
10376 PopDeclContext();
10377}
10378
10379/// This is used to implement the constant expression evaluation part of the
10380/// attribute enable_if extension. There is nothing in standard C++ which would
10381/// require reentering parameters.
10382void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10383 if (!Param)
10384 return;
10385
10386 S->AddDecl(Param);
10387 if (Param->getDeclName())
10388 IdResolver.AddDecl(Param);
10389}
10390
10391/// ActOnStartDelayedCXXMethodDeclaration - We have completed
10392/// parsing a top-level (non-nested) C++ class, and we are now
10393/// parsing those parts of the given Method declaration that could
10394/// not be parsed earlier (C++ [class.mem]p2), such as default
10395/// arguments. This action should enter the scope of the given
10396/// Method declaration as if we had just parsed the qualified method
10397/// name. However, it should not bring the parameters into scope;
10398/// that will be performed by ActOnDelayedCXXMethodParameter.
10399void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10400}
10401
10402/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10403/// C++ method declaration. We're (re-)introducing the given
10404/// function parameter into scope for use in parsing later parts of
10405/// the method declaration. For example, we could see an
10406/// ActOnParamDefaultArgument event for this parameter.
10407void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10408 if (!ParamD)
10409 return;
10410
10411 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10412
10413 S->AddDecl(Param);
10414 if (Param->getDeclName())
10415 IdResolver.AddDecl(Param);
10416}
10417
10418/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10419/// processing the delayed method declaration for Method. The method
10420/// declaration is now considered finished. There may be a separate
10421/// ActOnStartOfFunctionDef action later (not necessarily
10422/// immediately!) for this method, if it was also defined inside the
10423/// class body.
10424void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10425 if (!MethodD)
10426 return;
10427
10428 AdjustDeclIfTemplate(MethodD);
10429
10430 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10431
10432 // Now that we have our default arguments, check the constructor
10433 // again. It could produce additional diagnostics or affect whether
10434 // the class has implicitly-declared destructors, among other
10435 // things.
10436 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10437 CheckConstructor(Constructor);
10438
10439 // Check the default arguments, which we may have added.
10440 if (!Method->isInvalidDecl())
10441 CheckCXXDefaultArguments(Method);
10442}
10443
10444// Emit the given diagnostic for each non-address-space qualifier.
10445// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10446static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10447 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10448 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10449 bool DiagOccured = false;
10450 FTI.MethodQualifiers->forEachQualifier(
10451 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10452 SourceLocation SL) {
10453 // This diagnostic should be emitted on any qualifier except an addr
10454 // space qualifier. However, forEachQualifier currently doesn't visit
10455 // addr space qualifiers, so there's no way to write this condition
10456 // right now; we just diagnose on everything.
10457 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10458 DiagOccured = true;
10459 });
10460 if (DiagOccured)
10461 D.setInvalidType();
10462 }
10463}
10464
10465/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10466/// the well-formedness of the constructor declarator @p D with type @p
10467/// R. If there are any errors in the declarator, this routine will
10468/// emit diagnostics and set the invalid bit to true. In any case, the type
10469/// will be updated to reflect a well-formed type for the constructor and
10470/// returned.
10471QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10472 StorageClass &SC) {
10473 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10474
10475 // C++ [class.ctor]p3:
10476 // A constructor shall not be virtual (10.3) or static (9.4). A
10477 // constructor can be invoked for a const, volatile or const
10478 // volatile object. A constructor shall not be declared const,
10479 // volatile, or const volatile (9.3.2).
10480 if (isVirtual) {
10481 if (!D.isInvalidType())
10482 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10483 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10484 << SourceRange(D.getIdentifierLoc());
10485 D.setInvalidType();
10486 }
10487 if (SC == SC_Static) {
10488 if (!D.isInvalidType())
10489 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10490 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10491 << SourceRange(D.getIdentifierLoc());
10492 D.setInvalidType();
10493 SC = SC_None;
10494 }
10495
10496 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10497 diagnoseIgnoredQualifiers(
10498 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10499 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10500 D.getDeclSpec().getRestrictSpecLoc(),
10501 D.getDeclSpec().getAtomicSpecLoc());
10502 D.setInvalidType();
10503 }
10504
10505 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10506
10507 // C++0x [class.ctor]p4:
10508 // A constructor shall not be declared with a ref-qualifier.
10509 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10510 if (FTI.hasRefQualifier()) {
10511 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10512 << FTI.RefQualifierIsLValueRef
10513 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10514 D.setInvalidType();
10515 }
10516
10517 // Rebuild the function type "R" without any type qualifiers (in
10518 // case any of the errors above fired) and with "void" as the
10519 // return type, since constructors don't have return types.
10520 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10521 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10522 return R;
10523
10524 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10525 EPI.TypeQuals = Qualifiers();
10526 EPI.RefQualifier = RQ_None;
10527
10528 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10529}
10530
10531/// CheckConstructor - Checks a fully-formed constructor for
10532/// well-formedness, issuing any diagnostics required. Returns true if
10533/// the constructor declarator is invalid.
10534void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10535 CXXRecordDecl *ClassDecl
10536 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10537 if (!ClassDecl)
10538 return Constructor->setInvalidDecl();
10539
10540 // C++ [class.copy]p3:
10541 // A declaration of a constructor for a class X is ill-formed if
10542 // its first parameter is of type (optionally cv-qualified) X and
10543 // either there are no other parameters or else all other
10544 // parameters have default arguments.
10545 if (!Constructor->isInvalidDecl() &&
10546 Constructor->hasOneParamOrDefaultArgs() &&
10547 Constructor->getTemplateSpecializationKind() !=
10548 TSK_ImplicitInstantiation) {
10549 QualType ParamType = Constructor->getParamDecl(0)->getType();
10550 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10551 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10552 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10553 const char *ConstRef
10554 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10555 : " const &";
10556 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10557 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10558
10559 // FIXME: Rather that making the constructor invalid, we should endeavor
10560 // to fix the type.
10561 Constructor->setInvalidDecl();
10562 }
10563 }
10564}
10565
10566/// CheckDestructor - Checks a fully-formed destructor definition for
10567/// well-formedness, issuing any diagnostics required. Returns true
10568/// on error.
10569bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10570 CXXRecordDecl *RD = Destructor->getParent();
10571
10572 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10573 SourceLocation Loc;
10574
10575 if (!Destructor->isImplicit())
10576 Loc = Destructor->getLocation();
10577 else
10578 Loc = RD->getLocation();
10579
10580 // If we have a virtual destructor, look up the deallocation function
10581 if (FunctionDecl *OperatorDelete =
10582 FindDeallocationFunctionForDestructor(Loc, RD)) {
10583 Expr *ThisArg = nullptr;
10584
10585 // If the notional 'delete this' expression requires a non-trivial
10586 // conversion from 'this' to the type of a destroying operator delete's
10587 // first parameter, perform that conversion now.
10588 if (OperatorDelete->isDestroyingOperatorDelete()) {
10589 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10590 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10591 // C++ [class.dtor]p13:
10592 // ... as if for the expression 'delete this' appearing in a
10593 // non-virtual destructor of the destructor's class.
10594 ContextRAII SwitchContext(*this, Destructor);
10595 ExprResult This =
10596 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10597 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", 10597, __extension__ __PRETTY_FUNCTION__
))
;
10598 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10599 if (This.isInvalid()) {
10600 // FIXME: Register this as a context note so that it comes out
10601 // in the right order.
10602 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10603 return true;
10604 }
10605 ThisArg = This.get();
10606 }
10607 }
10608
10609 DiagnoseUseOfDecl(OperatorDelete, Loc);
10610 MarkFunctionReferenced(Loc, OperatorDelete);
10611 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10612 }
10613 }
10614
10615 return false;
10616}
10617
10618/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10619/// the well-formednes of the destructor declarator @p D with type @p
10620/// R. If there are any errors in the declarator, this routine will
10621/// emit diagnostics and set the declarator to invalid. Even if this happens,
10622/// will be updated to reflect a well-formed type for the destructor and
10623/// returned.
10624QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10625 StorageClass& SC) {
10626 // C++ [class.dtor]p1:
10627 // [...] A typedef-name that names a class is a class-name
10628 // (7.1.3); however, a typedef-name that names a class shall not
10629 // be used as the identifier in the declarator for a destructor
10630 // declaration.
10631 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10632 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10633 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10634 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10635 else if (const TemplateSpecializationType *TST =
10636 DeclaratorType->getAs<TemplateSpecializationType>())
10637 if (TST->isTypeAlias())
10638 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10639 << DeclaratorType << 1;
10640
10641 // C++ [class.dtor]p2:
10642 // A destructor is used to destroy objects of its class type. A
10643 // destructor takes no parameters, and no return type can be
10644 // specified for it (not even void). The address of a destructor
10645 // shall not be taken. A destructor shall not be static. A
10646 // destructor can be invoked for a const, volatile or const
10647 // volatile object. A destructor shall not be declared const,
10648 // volatile or const volatile (9.3.2).
10649 if (SC == SC_Static) {
10650 if (!D.isInvalidType())
10651 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10652 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10653 << SourceRange(D.getIdentifierLoc())
10654 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10655
10656 SC = SC_None;
10657 }
10658 if (!D.isInvalidType()) {
10659 // Destructors don't have return types, but the parser will
10660 // happily parse something like:
10661 //
10662 // class X {
10663 // float ~X();
10664 // };
10665 //
10666 // The return type will be eliminated later.
10667 if (D.getDeclSpec().hasTypeSpecifier())
10668 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10669 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10670 << SourceRange(D.getIdentifierLoc());
10671 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10672 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10673 SourceLocation(),
10674 D.getDeclSpec().getConstSpecLoc(),
10675 D.getDeclSpec().getVolatileSpecLoc(),
10676 D.getDeclSpec().getRestrictSpecLoc(),
10677 D.getDeclSpec().getAtomicSpecLoc());
10678 D.setInvalidType();
10679 }
10680 }
10681
10682 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10683
10684 // C++0x [class.dtor]p2:
10685 // A destructor shall not be declared with a ref-qualifier.
10686 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10687 if (FTI.hasRefQualifier()) {
10688 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10689 << FTI.RefQualifierIsLValueRef
10690 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10691 D.setInvalidType();
10692 }
10693
10694 // Make sure we don't have any parameters.
10695 if (FTIHasNonVoidParameters(FTI)) {
10696 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10697
10698 // Delete the parameters.
10699 FTI.freeParams();
10700 D.setInvalidType();
10701 }
10702
10703 // Make sure the destructor isn't variadic.
10704 if (FTI.isVariadic) {
10705 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10706 D.setInvalidType();
10707 }
10708
10709 // Rebuild the function type "R" without any type qualifiers or
10710 // parameters (in case any of the errors above fired) and with
10711 // "void" as the return type, since destructors don't have return
10712 // types.
10713 if (!D.isInvalidType())
10714 return R;
10715
10716 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10717 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10718 EPI.Variadic = false;
10719 EPI.TypeQuals = Qualifiers();
10720 EPI.RefQualifier = RQ_None;
10721 return Context.getFunctionType(Context.VoidTy, None, EPI);
10722}
10723
10724static void extendLeft(SourceRange &R, SourceRange Before) {
10725 if (Before.isInvalid())
10726 return;
10727 R.setBegin(Before.getBegin());
10728 if (R.getEnd().isInvalid())
10729 R.setEnd(Before.getEnd());
10730}
10731
10732static void extendRight(SourceRange &R, SourceRange After) {
10733 if (After.isInvalid())
10734 return;
10735 if (R.getBegin().isInvalid())
10736 R.setBegin(After.getBegin());
10737 R.setEnd(After.getEnd());
10738}
10739
10740/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10741/// well-formednes of the conversion function declarator @p D with
10742/// type @p R. If there are any errors in the declarator, this routine
10743/// will emit diagnostics and return true. Otherwise, it will return
10744/// false. Either way, the type @p R will be updated to reflect a
10745/// well-formed type for the conversion operator.
10746void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10747 StorageClass& SC) {
10748 // C++ [class.conv.fct]p1:
10749 // Neither parameter types nor return type can be specified. The
10750 // type of a conversion function (8.3.5) is "function taking no
10751 // parameter returning conversion-type-id."
10752 if (SC == SC_Static) {
10753 if (!D.isInvalidType())
10754 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10755 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10756 << D.getName().getSourceRange();
10757 D.setInvalidType();
10758 SC = SC_None;
10759 }
10760
10761 TypeSourceInfo *ConvTSI = nullptr;
10762 QualType ConvType =
10763 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10764
10765 const DeclSpec &DS = D.getDeclSpec();
10766 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10767 // Conversion functions don't have return types, but the parser will
10768 // happily parse something like:
10769 //
10770 // class X {
10771 // float operator bool();
10772 // };
10773 //
10774 // The return type will be changed later anyway.
10775 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10776 << SourceRange(DS.getTypeSpecTypeLoc())
10777 << SourceRange(D.getIdentifierLoc());
10778 D.setInvalidType();
10779 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10780 // It's also plausible that the user writes type qualifiers in the wrong
10781 // place, such as:
10782 // struct S { const operator int(); };
10783 // FIXME: we could provide a fixit to move the qualifiers onto the
10784 // conversion type.
10785 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10786 << SourceRange(D.getIdentifierLoc()) << 0;
10787 D.setInvalidType();
10788 }
10789
10790 const auto *Proto = R->castAs<FunctionProtoType>();
10791
10792 // Make sure we don't have any parameters.
10793 if (Proto->getNumParams() > 0) {
10794 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10795
10796 // Delete the parameters.
10797 D.getFunctionTypeInfo().freeParams();
10798 D.setInvalidType();
10799 } else if (Proto->isVariadic()) {
10800 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10801 D.setInvalidType();
10802 }
10803
10804 // Diagnose "&operator bool()" and other such nonsense. This
10805 // is actually a gcc extension which we don't support.
10806 if (Proto->getReturnType() != ConvType) {
10807 bool NeedsTypedef = false;
10808 SourceRange Before, After;
10809
10810 // Walk the chunks and extract information on them for our diagnostic.
10811 bool PastFunctionChunk = false;
10812 for (auto &Chunk : D.type_objects()) {
10813 switch (Chunk.Kind) {
10814 case DeclaratorChunk::Function:
10815 if (!PastFunctionChunk) {
10816 if (Chunk.Fun.HasTrailingReturnType) {
10817 TypeSourceInfo *TRT = nullptr;
10818 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10819 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10820 }
10821 PastFunctionChunk = true;
10822 break;
10823 }
10824 [[fallthrough]];
10825 case DeclaratorChunk::Array:
10826 NeedsTypedef = true;
10827 extendRight(After, Chunk.getSourceRange());
10828 break;
10829
10830 case DeclaratorChunk::Pointer:
10831 case DeclaratorChunk::BlockPointer:
10832 case DeclaratorChunk::Reference:
10833 case DeclaratorChunk::MemberPointer:
10834 case DeclaratorChunk::Pipe:
10835 extendLeft(Before, Chunk.getSourceRange());
10836 break;
10837
10838 case DeclaratorChunk::Paren:
10839 extendLeft(Before, Chunk.Loc);
10840 extendRight(After, Chunk.EndLoc);
10841 break;
10842 }
10843 }
10844
10845 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10846 After.isValid() ? After.getBegin() :
10847 D.getIdentifierLoc();
10848 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10849 DB << Before << After;
10850
10851 if (!NeedsTypedef) {
10852 DB << /*don't need a typedef*/0;
10853
10854 // If we can provide a correct fix-it hint, do so.
10855 if (After.isInvalid() && ConvTSI) {
10856 SourceLocation InsertLoc =
10857 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10858 DB << FixItHint::CreateInsertion(InsertLoc, " ")
10859 << FixItHint::CreateInsertionFromRange(
10860 InsertLoc, CharSourceRange::getTokenRange(Before))
10861 << FixItHint::CreateRemoval(Before);
10862 }
10863 } else if (!Proto->getReturnType()->isDependentType()) {
10864 DB << /*typedef*/1 << Proto->getReturnType();
10865 } else if (getLangOpts().CPlusPlus11) {
10866 DB << /*alias template*/2 << Proto->getReturnType();
10867 } else {
10868 DB << /*might not be fixable*/3;
10869 }
10870
10871 // Recover by incorporating the other type chunks into the result type.
10872 // Note, this does *not* change the name of the function. This is compatible
10873 // with the GCC extension:
10874 // struct S { &operator int(); } s;
10875 // int &r = s.operator int(); // ok in GCC
10876 // S::operator int&() {} // error in GCC, function name is 'operator int'.
10877 ConvType = Proto->getReturnType();
10878 }
10879
10880 // C++ [class.conv.fct]p4:
10881 // The conversion-type-id shall not represent a function type nor
10882 // an array type.
10883 if (ConvType->isArrayType()) {
10884 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10885 ConvType = Context.getPointerType(ConvType);
10886 D.setInvalidType();
10887 } else if (ConvType->isFunctionType()) {
10888 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10889 ConvType = Context.getPointerType(ConvType);
10890 D.setInvalidType();
10891 }
10892
10893 // Rebuild the function type "R" without any parameters (in case any
10894 // of the errors above fired) and with the conversion type as the
10895 // return type.
10896 if (D.isInvalidType())
10897 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10898
10899 // C++0x explicit conversion operators.
10900 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10901 Diag(DS.getExplicitSpecLoc(),
10902 getLangOpts().CPlusPlus11
10903 ? diag::warn_cxx98_compat_explicit_conversion_functions
10904 : diag::ext_explicit_conversion_functions)
10905 << SourceRange(DS.getExplicitSpecRange());
10906}
10907
10908/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10909/// the declaration of the given C++ conversion function. This routine
10910/// is responsible for recording the conversion function in the C++
10911/// class, if possible.
10912Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10913 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", 10913, __extension__ __PRETTY_FUNCTION__
))
;
10914
10915 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10916
10917 // Make sure we aren't redeclaring the conversion function.
10918 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10919 // C++ [class.conv.fct]p1:
10920 // [...] A conversion function is never used to convert a
10921 // (possibly cv-qualified) object to the (possibly cv-qualified)
10922 // same object type (or a reference to it), to a (possibly
10923 // cv-qualified) base class of that type (or a reference to it),
10924 // or to (possibly cv-qualified) void.
10925 QualType ClassType
10926 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10927 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10928 ConvType = ConvTypeRef->getPointeeType();
10929 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10930 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10931 /* Suppress diagnostics for instantiations. */;
10932 else if (Conversion->size_overridden_methods() != 0)
10933 /* Suppress diagnostics for overriding virtual function in a base class. */;
10934 else if (ConvType->isRecordType()) {
10935 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10936 if (ConvType == ClassType)
10937 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10938 << ClassType;
10939 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10940 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10941 << ClassType << ConvType;
10942 } else if (ConvType->isVoidType()) {
10943 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10944 << ClassType << ConvType;
10945 }
10946
10947 if (FunctionTemplateDecl *ConversionTemplate
10948 = Conversion->getDescribedFunctionTemplate())
10949 return ConversionTemplate;
10950
10951 return Conversion;
10952}
10953
10954namespace {
10955/// Utility class to accumulate and print a diagnostic listing the invalid
10956/// specifier(s) on a declaration.
10957struct BadSpecifierDiagnoser {
10958 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10959 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10960 ~BadSpecifierDiagnoser() {
10961 Diagnostic << Specifiers;
10962 }
10963
10964 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10965 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10966 }
10967 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10968 return check(SpecLoc,
10969 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10970 }
10971 void check(SourceLocation SpecLoc, const char *Spec) {
10972 if (SpecLoc.isInvalid()) return;
10973 Diagnostic << SourceRange(SpecLoc, SpecLoc);
10974 if (!Specifiers.empty()) Specifiers += " ";
10975 Specifiers += Spec;
10976 }
10977
10978 Sema &S;
10979 Sema::SemaDiagnosticBuilder Diagnostic;
10980 std::string Specifiers;
10981};
10982}
10983
10984/// Check the validity of a declarator that we parsed for a deduction-guide.
10985/// These aren't actually declarators in the grammar, so we need to check that
10986/// the user didn't specify any pieces that are not part of the deduction-guide
10987/// grammar.
10988void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10989 StorageClass &SC) {
10990 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10991 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10992 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", 10992, __extension__ __PRETTY_FUNCTION__
))
;
10993
10994 // C++ [temp.deduct.guide]p3:
10995 // A deduction-gide shall be declared in the same scope as the
10996 // corresponding class template.
10997 if (!CurContext->getRedeclContext()->Equals(
10998 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10999 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
11000 << GuidedTemplateDecl;
11001 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
11002 }
11003
11004 auto &DS = D.getMutableDeclSpec();
11005 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11006 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11007 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11008 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11009 BadSpecifierDiagnoser Diagnoser(
11010 *this, D.getIdentifierLoc(),
11011 diag::err_deduction_guide_invalid_specifier);
11012
11013 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
11014 DS.ClearStorageClassSpecs();
11015 SC = SC_None;
11016
11017 // 'explicit' is permitted.
11018 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
11019 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
11020 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
11021 DS.ClearConstexprSpec();
11022
11023 Diagnoser.check(DS.getConstSpecLoc(), "const");
11024 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11025 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11026 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11027 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11028 DS.ClearTypeQualifiers();
11029
11030 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11031 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11032 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11033 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11034 DS.ClearTypeSpecType();
11035 }
11036
11037 if (D.isInvalidType())
11038 return;
11039
11040 // Check the declarator is simple enough.
11041 bool FoundFunction = false;
11042 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11043 if (Chunk.Kind == DeclaratorChunk::Paren)
11044 continue;
11045 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11046 Diag(D.getDeclSpec().getBeginLoc(),
11047 diag::err_deduction_guide_with_complex_decl)
11048 << D.getSourceRange();
11049 break;
11050 }
11051 if (!Chunk.Fun.hasTrailingReturnType()) {
11052 Diag(D.getName().getBeginLoc(),
11053 diag::err_deduction_guide_no_trailing_return_type);
11054 break;
11055 }
11056
11057 // Check that the return type is written as a specialization of
11058 // the template specified as the deduction-guide's name.
11059 // The template name may not be qualified. [temp.deduct.guide]
11060 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11061 TypeSourceInfo *TSI = nullptr;
11062 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11063 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", 11063, __extension__ __PRETTY_FUNCTION__
))
;
11064 bool AcceptableReturnType = false;
11065 bool MightInstantiateToSpecialization = false;
11066 if (auto RetTST =
11067 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11068 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11069 bool TemplateMatches =
11070 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11071 auto TKind = SpecifiedName.getKind();
11072 // A Using TemplateName can't actually be valid (either it's qualified, or
11073 // we're in the wrong scope). But we have diagnosed these problems
11074 // already.
11075 bool SimplyWritten = TKind == TemplateName::Template ||
11076 TKind == TemplateName::UsingTemplate;
11077 if (SimplyWritten && TemplateMatches)
11078 AcceptableReturnType = true;
11079 else {
11080 // This could still instantiate to the right type, unless we know it
11081 // names the wrong class template.
11082 auto *TD = SpecifiedName.getAsTemplateDecl();
11083 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11084 !TemplateMatches);
11085 }
11086 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11087 MightInstantiateToSpecialization = true;
11088 }
11089
11090 if (!AcceptableReturnType) {
11091 Diag(TSI->getTypeLoc().getBeginLoc(),
11092 diag::err_deduction_guide_bad_trailing_return_type)
11093 << GuidedTemplate << TSI->getType()
11094 << MightInstantiateToSpecialization
11095 << TSI->getTypeLoc().getSourceRange();
11096 }
11097
11098 // Keep going to check that we don't have any inner declarator pieces (we
11099 // could still have a function returning a pointer to a function).
11100 FoundFunction = true;
11101 }
11102
11103 if (D.isFunctionDefinition())
11104 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11105}
11106
11107//===----------------------------------------------------------------------===//
11108// Namespace Handling
11109//===----------------------------------------------------------------------===//
11110
11111/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11112/// reopened.
11113static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11114 SourceLocation Loc,
11115 IdentifierInfo *II, bool *IsInline,
11116 NamespaceDecl *PrevNS) {
11117 assert(*IsInline != PrevNS->isInline())(static_cast <bool> (*IsInline != PrevNS->isInline()
) ? void (0) : __assert_fail ("*IsInline != PrevNS->isInline()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 11117, __extension__ __PRETTY_FUNCTION__
))
;
11118
11119 // 'inline' must appear on the original definition, but not necessarily
11120 // on all extension definitions, so the note should point to the first
11121 // definition to avoid confusion.
11122 PrevNS = PrevNS->getFirstDecl();
11123
11124 if (PrevNS->isInline())
11125 // The user probably just forgot the 'inline', so suggest that it
11126 // be added back.
11127 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11128 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11129 else
11130 S.Diag(Loc, diag::err_inline_namespace_mismatch);
11131
11132 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11133 *IsInline = PrevNS->isInline();
11134}
11135
11136/// ActOnStartNamespaceDef - This is called at the start of a namespace
11137/// definition.
11138Decl *Sema::ActOnStartNamespaceDef(
11139 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
11140 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
11141 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
11142 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11143 // For anonymous namespace, take the location of the left brace.
11144 SourceLocation Loc = II ? IdentLoc : LBrace;
11145 bool IsInline = InlineLoc.isValid();
11146 bool IsInvalid = false;
11147 bool IsStd = false;
11148 bool AddToKnown = false;
11149 Scope *DeclRegionScope = NamespcScope->getParent();
11150
11151 NamespaceDecl *PrevNS = nullptr;
11152 if (II) {
11153 // C++ [namespace.def]p2:
11154 // The identifier in an original-namespace-definition shall not
11155 // have been previously defined in the declarative region in
11156 // which the original-namespace-definition appears. The
11157 // identifier in an original-namespace-definition is the name of
11158 // the namespace. Subsequently in that declarative region, it is
11159 // treated as an original-namespace-name.
11160 //
11161 // Since namespace names are unique in their scope, and we don't
11162 // look through using directives, just look for any ordinary names
11163 // as if by qualified name lookup.
11164 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11165 ForExternalRedeclaration);
11166 LookupQualifiedName(R, CurContext->getRedeclContext());
11167 NamedDecl *PrevDecl =
11168 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11169 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11170
11171 if (PrevNS) {
11172 // This is an extended namespace definition.
11173 if (IsInline != PrevNS->isInline())
11174 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11175 &IsInline, PrevNS);
11176 } else if (PrevDecl) {
11177 // This is an invalid name redefinition.
11178 Diag(Loc, diag::err_redefinition_different_kind)
11179 << II;
11180 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11181 IsInvalid = true;
11182 // Continue on to push Namespc as current DeclContext and return it.
11183 } else if (II->isStr("std") &&
11184 CurContext->getRedeclContext()->isTranslationUnit()) {
11185 // This is the first "real" definition of the namespace "std", so update
11186 // our cache of the "std" namespace to point at this definition.
11187 PrevNS = getStdNamespace();
11188 IsStd = true;
11189 AddToKnown = !IsInline;
11190 } else {
11191 // We've seen this namespace for the first time.
11192 AddToKnown = !IsInline;
11193 }
11194 } else {
11195 // Anonymous namespaces.
11196
11197 // Determine whether the parent already has an anonymous namespace.
11198 DeclContext *Parent = CurContext->getRedeclContext();
11199 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11200 PrevNS = TU->getAnonymousNamespace();
11201 } else {
11202 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11203 PrevNS = ND->getAnonymousNamespace();
11204 }
11205
11206 if (PrevNS && IsInline != PrevNS->isInline())
11207 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11208 &IsInline, PrevNS);
11209 }
11210
11211 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
11212 StartLoc, Loc, II, PrevNS);
11213 if (IsInvalid)
11214 Namespc->setInvalidDecl();
11215
11216 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11217 AddPragmaAttributes(DeclRegionScope, Namespc);
11218
11219 // FIXME: Should we be merging attributes?
11220 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11221 PushNamespaceVisibilityAttr(Attr, Loc);
11222
11223 if (IsStd)
11224 StdNamespace = Namespc;
11225 if (AddToKnown)
11226 KnownNamespaces[Namespc] = false;
11227
11228 if (II) {
11229 PushOnScopeChains(Namespc, DeclRegionScope);
11230 } else {
11231 // Link the anonymous namespace into its parent.
11232 DeclContext *Parent = CurContext->getRedeclContext();
11233 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11234 TU->setAnonymousNamespace(Namespc);
11235 } else {
11236 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11237 }
11238
11239 CurContext->addDecl(Namespc);
11240
11241 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11242 // behaves as if it were replaced by
11243 // namespace unique { /* empty body */ }
11244 // using namespace unique;
11245 // namespace unique { namespace-body }
11246 // where all occurrences of 'unique' in a translation unit are
11247 // replaced by the same identifier and this identifier differs
11248 // from all other identifiers in the entire program.
11249
11250 // We just create the namespace with an empty name and then add an
11251 // implicit using declaration, just like the standard suggests.
11252 //
11253 // CodeGen enforces the "universally unique" aspect by giving all
11254 // declarations semantically contained within an anonymous
11255 // namespace internal linkage.
11256
11257 if (!PrevNS) {
11258 UD = UsingDirectiveDecl::Create(Context, Parent,
11259 /* 'using' */ LBrace,
11260 /* 'namespace' */ SourceLocation(),
11261 /* qualifier */ NestedNameSpecifierLoc(),
11262 /* identifier */ SourceLocation(),
11263 Namespc,
11264 /* Ancestor */ Parent);
11265 UD->setImplicit();
11266 Parent->addDecl(UD);
11267 }
11268 }
11269
11270 ActOnDocumentableDecl(Namespc);
11271
11272 // Although we could have an invalid decl (i.e. the namespace name is a
11273 // redefinition), push it as current DeclContext and try to continue parsing.
11274 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11275 // for the namespace has the declarations that showed up in that particular
11276 // namespace definition.
11277 PushDeclContext(NamespcScope, Namespc);
11278 return Namespc;
11279}
11280
11281/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11282/// is a namespace alias, returns the namespace it points to.
11283static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11284 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11285 return AD->getNamespace();
11286 return dyn_cast_or_null<NamespaceDecl>(D);
11287}
11288
11289/// ActOnFinishNamespaceDef - This callback is called after a namespace is
11290/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11291void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11292 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11293 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", 11293, __extension__ __PRETTY_FUNCTION__
))
;
11294 Namespc->setRBraceLoc(RBrace);
11295 PopDeclContext();
11296 if (Namespc->hasAttr<VisibilityAttr>())
11297 PopPragmaVisibility(true, RBrace);
11298 // If this namespace contains an export-declaration, export it now.
11299 if (DeferredExportedNamespaces.erase(Namespc))
11300 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11301}
11302
11303CXXRecordDecl *Sema::getStdBadAlloc() const {
11304 return cast_or_null<CXXRecordDecl>(
11305 StdBadAlloc.get(Context.getExternalSource()));
11306}
11307
11308EnumDecl *Sema::getStdAlignValT() const {
11309 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11310}
11311
11312NamespaceDecl *Sema::getStdNamespace() const {
11313 return cast_or_null<NamespaceDecl>(
11314 StdNamespace.get(Context.getExternalSource()));
11315}
11316
11317NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11318 if (!StdExperimentalNamespaceCache) {
11319 if (auto Std = getStdNamespace()) {
11320 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11321 SourceLocation(), LookupNamespaceName);
11322 if (!LookupQualifiedName(Result, Std) ||
11323 !(StdExperimentalNamespaceCache =
11324 Result.getAsSingle<NamespaceDecl>()))
11325 Result.suppressDiagnostics();
11326 }
11327 }
11328 return StdExperimentalNamespaceCache;
11329}
11330
11331namespace {
11332
11333enum UnsupportedSTLSelect {
11334 USS_InvalidMember,
11335 USS_MissingMember,
11336 USS_NonTrivial,
11337 USS_Other
11338};
11339
11340struct InvalidSTLDiagnoser {
11341 Sema &S;
11342 SourceLocation Loc;
11343 QualType TyForDiags;
11344
11345 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11346 const VarDecl *VD = nullptr) {
11347 {
11348 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11349 << TyForDiags << ((int)Sel);
11350 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11351 assert(!Name.empty())(static_cast <bool> (!Name.empty()) ? void (0) : __assert_fail
("!Name.empty()", "clang/lib/Sema/SemaDeclCXX.cpp", 11351, __extension__
__PRETTY_FUNCTION__))
;
11352 D << Name;
11353 }
11354 }
11355 if (Sel == USS_InvalidMember) {
11356 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11357 << VD << VD->getSourceRange();
11358 }
11359 return QualType();
11360 }
11361};
11362} // namespace
11363
11364QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11365 SourceLocation Loc,
11366 ComparisonCategoryUsage Usage) {
11367 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", 11368, __extension__ __PRETTY_FUNCTION__
))
11368 "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", 11368, __extension__ __PRETTY_FUNCTION__
))
;
11369
11370 // Use an elaborated type for diagnostics which has a name containing the
11371 // prepended 'std' namespace but not any inline namespace names.
11372 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11373 auto *NNS =
11374 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11375 return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11376 };
11377
11378 // Check if we've already successfully checked the comparison category type
11379 // before. If so, skip checking it again.
11380 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11381 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11382 // The only thing we need to check is that the type has a reachable
11383 // definition in the current context.
11384 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11385 return QualType();
11386
11387 return Info->getType();
11388 }
11389
11390 // If lookup failed
11391 if (!Info) {
11392 std::string NameForDiags = "std::";
11393 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11394 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11395 << NameForDiags << (int)Usage;
11396 return QualType();
11397 }
11398
11399 assert(Info->Kind == Kind)(static_cast <bool> (Info->Kind == Kind) ? void (0) :
__assert_fail ("Info->Kind == Kind", "clang/lib/Sema/SemaDeclCXX.cpp"
, 11399, __extension__ __PRETTY_FUNCTION__))
;
11400 assert(Info->Record)(static_cast <bool> (Info->Record) ? void (0) : __assert_fail
("Info->Record", "clang/lib/Sema/SemaDeclCXX.cpp", 11400,
__extension__ __PRETTY_FUNCTION__))
;
11401
11402 // Update the Record decl in case we encountered a forward declaration on our
11403 // first pass. FIXME: This is a bit of a hack.
11404 if (Info->Record->hasDefinition())
11405 Info->Record = Info->Record->getDefinition();
11406
11407 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11408 return QualType();
11409
11410 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11411
11412 if (!Info->Record->isTriviallyCopyable())
11413 return UnsupportedSTLError(USS_NonTrivial);
11414
11415 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11416 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11417 // Tolerate empty base classes.
11418 if (Base->isEmpty())
11419 continue;
11420 // Reject STL implementations which have at least one non-empty base.
11421 return UnsupportedSTLError();
11422 }
11423
11424 // Check that the STL has implemented the types using a single integer field.
11425 // This expectation allows better codegen for builtin operators. We require:
11426 // (1) The class has exactly one field.
11427 // (2) The field is an integral or enumeration type.
11428 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11429 if (std::distance(FIt, FEnd) != 1 ||
11430 !FIt->getType()->isIntegralOrEnumerationType()) {
11431 return UnsupportedSTLError();
11432 }
11433
11434 // Build each of the require values and store them in Info.
11435 for (ComparisonCategoryResult CCR :
11436 ComparisonCategories::getPossibleResultsForType(Kind)) {
11437 StringRef MemName = ComparisonCategories::getResultString(CCR);
11438 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11439
11440 if (!ValInfo)
11441 return UnsupportedSTLError(USS_MissingMember, MemName);
11442
11443 VarDecl *VD = ValInfo->VD;
11444 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", 11444, __extension__ __PRETTY_FUNCTION__
))
;
11445
11446 // Attempt to diagnose reasons why the STL definition of this type
11447 // might be foobar, including it failing to be a constant expression.
11448 // TODO Handle more ways the lookup or result can be invalid.
11449 if (!VD->isStaticDataMember() ||
11450 !VD->isUsableInConstantExpressions(Context))
11451 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11452
11453 // Attempt to evaluate the var decl as a constant expression and extract
11454 // the value of its first field as a ICE. If this fails, the STL
11455 // implementation is not supported.
11456 if (!ValInfo->hasValidIntValue())
11457 return UnsupportedSTLError();
11458
11459 MarkVariableReferenced(Loc, VD);
11460 }
11461
11462 // We've successfully built the required types and expressions. Update
11463 // the cache and return the newly cached value.
11464 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11465 return Info->getType();
11466}
11467
11468/// Retrieve the special "std" namespace, which may require us to
11469/// implicitly define the namespace.
11470NamespaceDecl *Sema::getOrCreateStdNamespace() {
11471 if (!StdNamespace) {
11472 // The "std" namespace has not yet been defined, so build one implicitly.
11473 StdNamespace = NamespaceDecl::Create(Context,
11474 Context.getTranslationUnitDecl(),
11475 /*Inline=*/false,
11476 SourceLocation(), SourceLocation(),
11477 &PP.getIdentifierTable().get("std"),
11478 /*PrevDecl=*/nullptr);
11479 getStdNamespace()->setImplicit(true);
11480 }
11481
11482 return getStdNamespace();
11483}
11484
11485bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11486 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", 11487, __extension__ __PRETTY_FUNCTION__
))
11487 "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", 11487, __extension__ __PRETTY_FUNCTION__
))
;
11488
11489 // We're looking for implicit instantiations of
11490 // template <typename E> class std::initializer_list.
11491
11492 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11493 return false;
11494
11495 ClassTemplateDecl *Template = nullptr;
11496 const TemplateArgument *Arguments = nullptr;
11497
11498 if (const RecordType *RT = Ty->getAs<RecordType>()) {
11499
11500 ClassTemplateSpecializationDecl *Specialization =
11501 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11502 if (!Specialization)
11503 return false;
11504
11505 Template = Specialization->getSpecializedTemplate();
11506 Arguments = Specialization->getTemplateArgs().data();
11507 } else if (const TemplateSpecializationType *TST =
11508 Ty->getAs<TemplateSpecializationType>()) {
11509 Template = dyn_cast_or_null<ClassTemplateDecl>(
11510 TST->getTemplateName().getAsTemplateDecl());
11511 Arguments = TST->getArgs();
11512 }
11513 if (!Template)
11514 return false;
11515
11516 if (!StdInitializerList) {
11517 // Haven't recognized std::initializer_list yet, maybe this is it.
11518 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11519 if (TemplateClass->getIdentifier() !=
11520 &PP.getIdentifierTable().get("initializer_list") ||
11521 !getStdNamespace()->InEnclosingNamespaceSetOf(
11522 TemplateClass->getDeclContext()))
11523 return false;
11524 // This is a template called std::initializer_list, but is it the right
11525 // template?
11526 TemplateParameterList *Params = Template->getTemplateParameters();
11527 if (Params->getMinRequiredArguments() != 1)
11528 return false;
11529 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11530 return false;
11531
11532 // It's the right template.
11533 StdInitializerList = Template;
11534 }
11535
11536 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11537 return false;
11538
11539 // This is an instance of std::initializer_list. Find the argument type.
11540 if (Element)
11541 *Element = Arguments[0].getAsType();
11542 return true;
11543}
11544
11545static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11546 NamespaceDecl *Std = S.getStdNamespace();
11547 if (!Std) {
11548 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11549 return nullptr;
11550 }
11551
11552 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11553 Loc, Sema::LookupOrdinaryName);
11554 if (!S.LookupQualifiedName(Result, Std)) {
11555 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11556 return nullptr;
11557 }
11558 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11559 if (!Template) {
11560 Result.suppressDiagnostics();
11561 // We found something weird. Complain about the first thing we found.
11562 NamedDecl *Found = *Result.begin();
11563 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11564 return nullptr;
11565 }
11566
11567 // We found some template called std::initializer_list. Now verify that it's
11568 // correct.
11569 TemplateParameterList *Params = Template->getTemplateParameters();
11570 if (Params->getMinRequiredArguments() != 1 ||
11571 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11572 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11573 return nullptr;
11574 }
11575
11576 return Template;
11577}
11578
11579QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11580 if (!StdInitializerList) {
11581 StdInitializerList = LookupStdInitializerList(*this, Loc);
11582 if (!StdInitializerList)
11583 return QualType();
11584 }
11585
11586 TemplateArgumentListInfo Args(Loc, Loc);
11587 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11588 Context.getTrivialTypeSourceInfo(Element,
11589 Loc)));
11590 return Context.getElaboratedType(
11591 ElaboratedTypeKeyword::ETK_None,
11592 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()),
11593 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11594}
11595
11596bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11597 // C++ [dcl.init.list]p2:
11598 // A constructor is an initializer-list constructor if its first parameter
11599 // is of type std::initializer_list<E> or reference to possibly cv-qualified
11600 // std::initializer_list<E> for some type E, and either there are no other
11601 // parameters or else all other parameters have default arguments.
11602 if (!Ctor->hasOneParamOrDefaultArgs())
11603 return false;
11604
11605 QualType ArgType = Ctor->getParamDecl(0)->getType();
11606 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11607 ArgType = RT->getPointeeType().getUnqualifiedType();
11608
11609 return isStdInitializerList(ArgType, nullptr);
11610}
11611
11612/// Determine whether a using statement is in a context where it will be
11613/// apply in all contexts.
11614static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11615 switch (CurContext->getDeclKind()) {
11616 case Decl::TranslationUnit:
11617 return true;
11618 case Decl::LinkageSpec:
11619 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11620 default:
11621 return false;
11622 }
11623}
11624
11625namespace {
11626
11627// Callback to only accept typo corrections that are namespaces.
11628class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11629public:
11630 bool ValidateCandidate(const TypoCorrection &candidate) override {
11631 if (NamedDecl *ND = candidate.getCorrectionDecl())
11632 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11633 return false;
11634 }
11635
11636 std::unique_ptr<CorrectionCandidateCallback> clone() override {
11637 return std::make_unique<NamespaceValidatorCCC>(*this);
11638 }
11639};
11640
11641}
11642
11643static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11644 CXXScopeSpec &SS,
11645 SourceLocation IdentLoc,
11646 IdentifierInfo *Ident) {
11647 R.clear();
11648 NamespaceValidatorCCC CCC{};
11649 if (TypoCorrection Corrected =
11650 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11651 Sema::CTK_ErrorRecovery)) {
11652 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11653 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11654 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11655 Ident->getName().equals(CorrectedStr);
11656 S.diagnoseTypo(Corrected,
11657 S.PDiag(diag::err_using_directive_member_suggest)
11658 << Ident << DC << DroppedSpecifier << SS.getRange(),
11659 S.PDiag(diag::note_namespace_defined_here));
11660 } else {
11661 S.diagnoseTypo(Corrected,
11662 S.PDiag(diag::err_using_directive_suggest) << Ident,
11663 S.PDiag(diag::note_namespace_defined_here));
11664 }
11665 R.addDecl(Corrected.getFoundDecl());
11666 return true;
11667 }
11668 return false;
11669}
11670
11671Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11672 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11673 SourceLocation IdentLoc,
11674 IdentifierInfo *NamespcName,
11675 const ParsedAttributesView &AttrList) {
11676 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", 11676, __extension__ __PRETTY_FUNCTION__
))
;
11677 assert(NamespcName && "Invalid NamespcName.")(static_cast <bool> (NamespcName && "Invalid NamespcName."
) ? void (0) : __assert_fail ("NamespcName && \"Invalid NamespcName.\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 11677, __extension__ __PRETTY_FUNCTION__
))
;
11678 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", 11678, __extension__ __PRETTY_FUNCTION__
))
;
11679
11680 // This can only happen along a recovery path.
11681 while (S->isTemplateParamScope())
11682 S = S->getParent();
11683 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", 11683, __extension__ __PRETTY_FUNCTION__
))
;
11684
11685 UsingDirectiveDecl *UDir = nullptr;
11686 NestedNameSpecifier *Qualifier = nullptr;
11687 if (SS.isSet())
11688 Qualifier = SS.getScopeRep();
11689
11690 // Lookup namespace name.
11691 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11692 LookupParsedName(R, S, &SS);
11693 if (R.isAmbiguous())
11694 return nullptr;
11695
11696 if (R.empty()) {
11697 R.clear();
11698 // Allow "using namespace std;" or "using namespace ::std;" even if
11699 // "std" hasn't been defined yet, for GCC compatibility.
11700 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11701 NamespcName->isStr("std")) {
11702 Diag(IdentLoc, diag::ext_using_undefined_std);
11703 R.addDecl(getOrCreateStdNamespace());
11704 R.resolveKind();
11705 }
11706 // Otherwise, attempt typo correction.
11707 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11708 }
11709
11710 if (!R.empty()) {
11711 NamedDecl *Named = R.getRepresentativeDecl();
11712 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11713 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", 11713, __extension__ __PRETTY_FUNCTION__
))
;
11714
11715 // The use of a nested name specifier may trigger deprecation warnings.
11716 DiagnoseUseOfDecl(Named, IdentLoc);
11717
11718 // C++ [namespace.udir]p1:
11719 // A using-directive specifies that the names in the nominated
11720 // namespace can be used in the scope in which the
11721 // using-directive appears after the using-directive. During
11722 // unqualified name lookup (3.4.1), the names appear as if they
11723 // were declared in the nearest enclosing namespace which
11724 // contains both the using-directive and the nominated
11725 // namespace. [Note: in this context, "contains" means "contains
11726 // directly or indirectly". ]
11727
11728 // Find enclosing context containing both using-directive and
11729 // nominated namespace.
11730 DeclContext *CommonAncestor = NS;
11731 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11732 CommonAncestor = CommonAncestor->getParent();
11733
11734 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11735 SS.getWithLocInContext(Context),
11736 IdentLoc, Named, CommonAncestor);
11737
11738 if (IsUsingDirectiveInToplevelContext(CurContext) &&
11739 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11740 Diag(IdentLoc, diag::warn_using_directive_in_header);
11741 }
11742
11743 PushUsingDirective(S, UDir);
11744 } else {
11745 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11746 }
11747
11748 if (UDir)
11749 ProcessDeclAttributeList(S, UDir, AttrList);
11750
11751 return UDir;
11752}
11753
11754void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11755 // If the scope has an associated entity and the using directive is at
11756 // namespace or translation unit scope, add the UsingDirectiveDecl into
11757 // its lookup structure so qualified name lookup can find it.
11758 DeclContext *Ctx = S->getEntity();
11759 if (Ctx && !Ctx->isFunctionOrMethod())
11760 Ctx->addDecl(UDir);
11761 else
11762 // Otherwise, it is at block scope. The using-directives will affect lookup
11763 // only to the end of the scope.
11764 S->PushUsingDirective(UDir);
11765}
11766
11767Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11768 SourceLocation UsingLoc,
11769 SourceLocation TypenameLoc, CXXScopeSpec &SS,
11770 UnqualifiedId &Name,
11771 SourceLocation EllipsisLoc,
11772 const ParsedAttributesView &AttrList) {
11773 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", 11773, __extension__ __PRETTY_FUNCTION__
))
;
11774
11775 if (SS.isEmpty()) {
11776 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11777 return nullptr;
11778 }
11779
11780 switch (Name.getKind()) {
11781 case UnqualifiedIdKind::IK_ImplicitSelfParam:
11782 case UnqualifiedIdKind::IK_Identifier:
11783 case UnqualifiedIdKind::IK_OperatorFunctionId:
11784 case UnqualifiedIdKind::IK_LiteralOperatorId:
11785 case UnqualifiedIdKind::IK_ConversionFunctionId:
11786 break;
11787
11788 case UnqualifiedIdKind::IK_ConstructorName:
11789 case UnqualifiedIdKind::IK_ConstructorTemplateId:
11790 // C++11 inheriting constructors.
11791 Diag(Name.getBeginLoc(),
11792 getLangOpts().CPlusPlus11
11793 ? diag::warn_cxx98_compat_using_decl_constructor
11794 : diag::err_using_decl_constructor)
11795 << SS.getRange();
11796
11797 if (getLangOpts().CPlusPlus11) break;
11798
11799 return nullptr;
11800
11801 case UnqualifiedIdKind::IK_DestructorName:
11802 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11803 return nullptr;
11804
11805 case UnqualifiedIdKind::IK_TemplateId:
11806 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11807 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11808 return nullptr;
11809
11810 case UnqualifiedIdKind::IK_DeductionGuideName:
11811 llvm_unreachable("cannot parse qualified deduction guide name")::llvm::llvm_unreachable_internal("cannot parse qualified deduction guide name"
, "clang/lib/Sema/SemaDeclCXX.cpp", 11811)
;
11812 }
11813
11814 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11815 DeclarationName TargetName = TargetNameInfo.getName();
11816 if (!TargetName)
11817 return nullptr;
11818
11819 // Warn about access declarations.
11820 if (UsingLoc.isInvalid()) {
11821 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11822 ? diag::err_access_decl
11823 : diag::warn_access_decl_deprecated)
11824 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11825 }
11826
11827 if (EllipsisLoc.isInvalid()) {
11828 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11829 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11830 return nullptr;
11831 } else {
11832 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11833 !TargetNameInfo.containsUnexpandedParameterPack()) {
11834 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11835 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11836 EllipsisLoc = SourceLocation();
11837 }
11838 }
11839
11840 NamedDecl *UD =
11841 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11842 SS, TargetNameInfo, EllipsisLoc, AttrList,
11843 /*IsInstantiation*/ false,
11844 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
11845 if (UD)
11846 PushOnScopeChains(UD, S, /*AddToContext*/ false);
11847
11848 return UD;
11849}
11850
11851Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
11852 SourceLocation UsingLoc,
11853 SourceLocation EnumLoc,
11854 SourceLocation IdentLoc,
11855 IdentifierInfo &II, CXXScopeSpec *SS) {
11856 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", 11856, __extension__ __PRETTY_FUNCTION__
))
;
11857 ParsedType TypeRep = getTypeName(II, IdentLoc, S, SS);
11858 if (!TypeRep) {
11859 Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS)
11860 ? diag::err_using_enum_is_dependent
11861 : diag::err_unknown_typename)
11862 << II.getName()
11863 << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, IdentLoc);
11864 return nullptr;
11865 }
11866
11867 auto *Enum = dyn_cast_if_present<EnumDecl>(TypeRep.get()->getAsTagDecl());
11868 if (!Enum) {
11869 Diag(IdentLoc, diag::err_using_enum_not_enum) << TypeRep.get();
11870 return nullptr;
11871 }
11872
11873 if (auto *Def = Enum->getDefinition())
11874 Enum = Def;
11875
11876 auto *UD =
11877 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, IdentLoc, Enum);
11878 if (UD)
11879 PushOnScopeChains(UD, S, /*AddToContext*/ false);
11880
11881 return UD;
11882}
11883
11884/// Determine whether a using declaration considers the given
11885/// declarations as "equivalent", e.g., if they are redeclarations of
11886/// the same entity or are both typedefs of the same type.
11887static bool
11888IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11889 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11890 return true;
11891
11892 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11893 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11894 return Context.hasSameType(TD1->getUnderlyingType(),
11895 TD2->getUnderlyingType());
11896
11897 // Two using_if_exists using-declarations are equivalent if both are
11898 // unresolved.
11899 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11900 isa<UnresolvedUsingIfExistsDecl>(D2))
11901 return true;
11902
11903 return false;
11904}
11905
11906
11907/// Determines whether to create a using shadow decl for a particular
11908/// decl, given the set of decls existing prior to this using lookup.
11909bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
11910 const LookupResult &Previous,
11911 UsingShadowDecl *&PrevShadow) {
11912 // Diagnose finding a decl which is not from a base class of the
11913 // current class. We do this now because there are cases where this
11914 // function will silently decide not to build a shadow decl, which
11915 // will pre-empt further diagnostics.
11916 //
11917 // We don't need to do this in C++11 because we do the check once on
11918 // the qualifier.
11919 //
11920 // FIXME: diagnose the following if we care enough:
11921 // struct A { int foo; };
11922 // struct B : A { using A::foo; };
11923 // template <class T> struct C : A {};
11924 // template <class T> struct D : C<T> { using B::foo; } // <---
11925 // This is invalid (during instantiation) in C++03 because B::foo
11926 // resolves to the using decl in B, which is not a base class of D<T>.
11927 // We can't diagnose it immediately because C<T> is an unknown
11928 // specialization. The UsingShadowDecl in D<T> then points directly
11929 // to A::foo, which will look well-formed when we instantiate.
11930 // The right solution is to not collapse the shadow-decl chain.
11931 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
11932 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
11933 DeclContext *OrigDC = Orig->getDeclContext();
11934
11935 // Handle enums and anonymous structs.
11936 if (isa<EnumDecl>(OrigDC))
11937 OrigDC = OrigDC->getParent();
11938 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11939 while (OrigRec->isAnonymousStructOrUnion())
11940 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11941
11942 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11943 if (OrigDC == CurContext) {
11944 Diag(Using->getLocation(),
11945 diag::err_using_decl_nested_name_specifier_is_current_class)
11946 << Using->getQualifierLoc().getSourceRange();
11947 Diag(Orig->getLocation(), diag::note_using_decl_target);
11948 Using->setInvalidDecl();
11949 return true;
11950 }
11951
11952 Diag(Using->getQualifierLoc().getBeginLoc(),
11953 diag::err_using_decl_nested_name_specifier_is_not_base_class)
11954 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
11955 << Using->getQualifierLoc().getSourceRange();
11956 Diag(Orig->getLocation(), diag::note_using_decl_target);
11957 Using->setInvalidDecl();
11958 return true;
11959 }
11960 }
11961
11962 if (Previous.empty()) return false;
11963
11964 NamedDecl *Target = Orig;
11965 if (isa<UsingShadowDecl>(Target))
11966 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11967
11968 // If the target happens to be one of the previous declarations, we
11969 // don't have a conflict.
11970 //
11971 // FIXME: but we might be increasing its access, in which case we
11972 // should redeclare it.
11973 NamedDecl *NonTag = nullptr, *Tag = nullptr;
11974 bool FoundEquivalentDecl = false;
11975 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11976 I != E; ++I) {
11977 NamedDecl *D = (*I)->getUnderlyingDecl();
11978 // We can have UsingDecls in our Previous results because we use the same
11979 // LookupResult for checking whether the UsingDecl itself is a valid
11980 // redeclaration.
11981 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
11982 continue;
11983
11984 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11985 // C++ [class.mem]p19:
11986 // If T is the name of a class, then [every named member other than
11987 // a non-static data member] shall have a name different from T
11988 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11989 !isa<IndirectFieldDecl>(Target) &&
11990 !isa<UnresolvedUsingValueDecl>(Target) &&
11991 DiagnoseClassNameShadow(
11992 CurContext,
11993 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
11994 return true;
11995 }
11996
11997 if (IsEquivalentForUsingDecl(Context, D, Target)) {
11998 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11999 PrevShadow = Shadow;
12000 FoundEquivalentDecl = true;
12001 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
12002 // We don't conflict with an existing using shadow decl of an equivalent
12003 // declaration, but we're not a redeclaration of it.
12004 FoundEquivalentDecl = true;
12005 }
12006
12007 if (isVisible(D))
12008 (isa<TagDecl>(D) ? Tag : NonTag) = D;
12009 }
12010
12011 if (FoundEquivalentDecl)
12012 return false;
12013
12014 // Always emit a diagnostic for a mismatch between an unresolved
12015 // using_if_exists and a resolved using declaration in either direction.
12016 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
12017 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
12018 if (!NonTag && !Tag)
12019 return false;
12020 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12021 Diag(Target->getLocation(), diag::note_using_decl_target);
12022 Diag((NonTag ? NonTag : Tag)->getLocation(),
12023 diag::note_using_decl_conflict);
12024 BUD->setInvalidDecl();
12025 return true;
12026 }
12027
12028 if (FunctionDecl *FD = Target->getAsFunction()) {
12029 NamedDecl *OldDecl = nullptr;
12030 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12031 /*IsForUsingDecl*/ true)) {
12032 case Ovl_Overload:
12033 return false;
12034
12035 case Ovl_NonFunction:
12036 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12037 break;
12038
12039 // We found a decl with the exact signature.
12040 case Ovl_Match:
12041 // If we're in a record, we want to hide the target, so we
12042 // return true (without a diagnostic) to tell the caller not to
12043 // build a shadow decl.
12044 if (CurContext->isRecord())
12045 return true;
12046
12047 // If we're not in a record, this is an error.
12048 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12049 break;
12050 }
12051
12052 Diag(Target->getLocation(), diag::note_using_decl_target);
12053 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12054 BUD->setInvalidDecl();
12055 return true;
12056 }
12057
12058 // Target is not a function.
12059
12060 if (isa<TagDecl>(Target)) {
12061 // No conflict between a tag and a non-tag.
12062 if (!Tag) return false;
12063
12064 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12065 Diag(Target->getLocation(), diag::note_using_decl_target);
12066 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12067 BUD->setInvalidDecl();
12068 return true;
12069 }
12070
12071 // No conflict between a tag and a non-tag.
12072 if (!NonTag) return false;
12073
12074 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12075 Diag(Target->getLocation(), diag::note_using_decl_target);
12076 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12077 BUD->setInvalidDecl();
12078 return true;
12079}
12080
12081/// Determine whether a direct base class is a virtual base class.
12082static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12083 if (!Derived->getNumVBases())
12084 return false;
12085 for (auto &B : Derived->bases())
12086 if (B.getType()->getAsCXXRecordDecl() == Base)
12087 return B.isVirtual();
12088 llvm_unreachable("not a direct base class")::llvm::llvm_unreachable_internal("not a direct base class", "clang/lib/Sema/SemaDeclCXX.cpp"
, 12088)
;
12089}
12090
12091/// Builds a shadow declaration corresponding to a 'using' declaration.
12092UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12093 NamedDecl *Orig,
12094 UsingShadowDecl *PrevDecl) {
12095 // If we resolved to another shadow declaration, just coalesce them.
12096 NamedDecl *Target = Orig;
12097 if (isa<UsingShadowDecl>(Target)) {
12098 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12099 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", 12099, __extension__ __PRETTY_FUNCTION__
))
;
12100 }
12101
12102 NamedDecl *NonTemplateTarget = Target;
12103 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12104 NonTemplateTarget = TargetTD->getTemplatedDecl();
12105
12106 UsingShadowDecl *Shadow;
12107 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12108 UsingDecl *Using = cast<UsingDecl>(BUD);
12109 bool IsVirtualBase =
12110 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12111 Using->getQualifier()->getAsRecordDecl());
12112 Shadow = ConstructorUsingShadowDecl::Create(
12113 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12114 } else {
12115 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12116 Target->getDeclName(), BUD, Target);
12117 }
12118 BUD->addShadowDecl(Shadow);
12119
12120 Shadow->setAccess(BUD->getAccess());
12121 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12122 Shadow->setInvalidDecl();
12123
12124 Shadow->setPreviousDecl(PrevDecl);
12125
12126 if (S)
12127 PushOnScopeChains(Shadow, S);
12128 else
12129 CurContext->addDecl(Shadow);
12130
12131
12132 return Shadow;
12133}
12134
12135/// Hides a using shadow declaration. This is required by the current
12136/// using-decl implementation when a resolvable using declaration in a
12137/// class is followed by a declaration which would hide or override
12138/// one or more of the using decl's targets; for example:
12139///
12140/// struct Base { void foo(int); };
12141/// struct Derived : Base {
12142/// using Base::foo;
12143/// void foo(int);
12144/// };
12145///
12146/// The governing language is C++03 [namespace.udecl]p12:
12147///
12148/// When a using-declaration brings names from a base class into a
12149/// derived class scope, member functions in the derived class
12150/// override and/or hide member functions with the same name and
12151/// parameter types in a base class (rather than conflicting).
12152///
12153/// There are two ways to implement this:
12154/// (1) optimistically create shadow decls when they're not hidden
12155/// by existing declarations, or
12156/// (2) don't create any shadow decls (or at least don't make them
12157/// visible) until we've fully parsed/instantiated the class.
12158/// The problem with (1) is that we might have to retroactively remove
12159/// a shadow decl, which requires several O(n) operations because the
12160/// decl structures are (very reasonably) not designed for removal.
12161/// (2) avoids this but is very fiddly and phase-dependent.
12162void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12163 if (Shadow->getDeclName().getNameKind() ==
12164 DeclarationName::CXXConversionFunctionName)
12165 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12166
12167 // Remove it from the DeclContext...
12168 Shadow->getDeclContext()->removeDecl(Shadow);
12169
12170 // ...and the scope, if applicable...
12171 if (S) {
12172 S->RemoveDecl(Shadow);
12173 IdResolver.RemoveDecl(Shadow);
12174 }
12175
12176 // ...and the using decl.
12177 Shadow->getIntroducer()->removeShadowDecl(Shadow);
12178
12179 // TODO: complain somehow if Shadow was used. It shouldn't
12180 // be possible for this to happen, because...?
12181}
12182
12183/// Find the base specifier for a base class with the given type.
12184static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12185 QualType DesiredBase,
12186 bool &AnyDependentBases) {
12187 // Check whether the named type is a direct base class.
12188 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12189 .getUnqualifiedType();
12190 for (auto &Base : Derived->bases()) {
12191 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12192 if (CanonicalDesiredBase == BaseType)
12193 return &Base;
12194 if (BaseType->isDependentType())
12195 AnyDependentBases = true;
12196 }
12197 return nullptr;
12198}
12199
12200namespace {
12201class UsingValidatorCCC final : public CorrectionCandidateCallback {
12202public:
12203 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12204 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12205 : HasTypenameKeyword(HasTypenameKeyword),
12206 IsInstantiation(IsInstantiation), OldNNS(NNS),
12207 RequireMemberOf(RequireMemberOf) {}
12208
12209 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12210 NamedDecl *ND = Candidate.getCorrectionDecl();
12211
12212 // Keywords are not valid here.
12213 if (!ND || isa<NamespaceDecl>(ND))
12214 return false;
12215
12216 // Completely unqualified names are invalid for a 'using' declaration.
12217 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12218 return false;
12219
12220 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12221 // reject.
12222
12223 if (RequireMemberOf) {
12224 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12225 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12226 // No-one ever wants a using-declaration to name an injected-class-name
12227 // of a base class, unless they're declaring an inheriting constructor.
12228 ASTContext &Ctx = ND->getASTContext();
12229 if (!Ctx.getLangOpts().CPlusPlus11)
12230 return false;
12231 QualType FoundType = Ctx.getRecordType(FoundRecord);
12232
12233 // Check that the injected-class-name is named as a member of its own
12234 // type; we don't want to suggest 'using Derived::Base;', since that
12235 // means something else.
12236 NestedNameSpecifier *Specifier =
12237 Candidate.WillReplaceSpecifier()
12238 ? Candidate.getCorrectionSpecifier()
12239 : OldNNS;
12240 if (!Specifier->getAsType() ||
12241 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12242 return false;
12243
12244 // Check that this inheriting constructor declaration actually names a
12245 // direct base class of the current class.
12246 bool AnyDependentBases = false;
12247 if (!findDirectBaseWithType(RequireMemberOf,
12248 Ctx.getRecordType(FoundRecord),
12249 AnyDependentBases) &&
12250 !AnyDependentBases)
12251 return false;
12252 } else {
12253 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12254 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12255 return false;
12256
12257 // FIXME: Check that the base class member is accessible?
12258 }
12259 } else {
12260 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12261 if (FoundRecord && FoundRecord->isInjectedClassName())
12262 return false;
12263 }
12264
12265 if (isa<TypeDecl>(ND))
12266 return HasTypenameKeyword || !IsInstantiation;
12267
12268 return !HasTypenameKeyword;
12269 }
12270
12271 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12272 return std::make_unique<UsingValidatorCCC>(*this);
12273 }
12274
12275private:
12276 bool HasTypenameKeyword;
12277 bool IsInstantiation;
12278 NestedNameSpecifier *OldNNS;
12279 CXXRecordDecl *RequireMemberOf;
12280};
12281} // end anonymous namespace
12282
12283/// Remove decls we can't actually see from a lookup being used to declare
12284/// shadow using decls.
12285///
12286/// \param S - The scope of the potential shadow decl
12287/// \param Previous - The lookup of a potential shadow decl's name.
12288void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12289 // It is really dumb that we have to do this.
12290 LookupResult::Filter F = Previous.makeFilter();
12291 while (F.hasNext()) {
12292 NamedDecl *D = F.next();
12293 if (!isDeclInScope(D, CurContext, S))
12294 F.erase();
12295 // If we found a local extern declaration that's not ordinarily visible,
12296 // and this declaration is being added to a non-block scope, ignore it.
12297 // We're only checking for scope conflicts here, not also for violations
12298 // of the linkage rules.
12299 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12300 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12301 F.erase();
12302 }
12303 F.done();
12304}
12305
12306/// Builds a using declaration.
12307///
12308/// \param IsInstantiation - Whether this call arises from an
12309/// instantiation of an unresolved using declaration. We treat
12310/// the lookup differently for these declarations.
12311NamedDecl *Sema::BuildUsingDeclaration(
12312 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12313 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12314 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12315 const ParsedAttributesView &AttrList, bool IsInstantiation,
12316 bool IsUsingIfExists) {
12317 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", 12317, __extension__ __PRETTY_FUNCTION__
))
;
12318 SourceLocation IdentLoc = NameInfo.getLoc();
12319 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", 12319, __extension__ __PRETTY_FUNCTION__
))
;
12320
12321 // FIXME: We ignore attributes for now.
12322
12323 // For an inheriting constructor declaration, the name of the using
12324 // declaration is the name of a constructor in this class, not in the
12325 // base class.
12326 DeclarationNameInfo UsingName = NameInfo;
12327 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12328 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12329 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12330 Context.getCanonicalType(Context.getRecordType(RD))));
12331
12332 // Do the redeclaration lookup in the current scope.
12333 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12334 ForVisibleRedeclaration);
12335 Previous.setHideTags(false);
12336 if (S) {
12337 LookupName(Previous, S);
12338
12339 FilterUsingLookup(S, Previous);
12340 } else {
12341 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", 12341, __extension__ __PRETTY_FUNCTION__
))
;
12342 if (CurContext->isRecord())
12343 LookupQualifiedName(Previous, CurContext);
12344 else {
12345 // No redeclaration check is needed here; in non-member contexts we
12346 // diagnosed all possible conflicts with other using-declarations when
12347 // building the template:
12348 //
12349 // For a dependent non-type using declaration, the only valid case is
12350 // if we instantiate to a single enumerator. We check for conflicts
12351 // between shadow declarations we introduce, and we check in the template
12352 // definition for conflicts between a non-type using declaration and any
12353 // other declaration, which together covers all cases.
12354 //
12355 // A dependent typename using declaration will never successfully
12356 // instantiate, since it will always name a class member, so we reject
12357 // that in the template definition.
12358 }
12359 }
12360
12361 // Check for invalid redeclarations.
12362 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12363 SS, IdentLoc, Previous))
12364 return nullptr;
12365
12366 // 'using_if_exists' doesn't make sense on an inherited constructor.
12367 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12368 DeclarationName::CXXConstructorName) {
12369 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12370 return nullptr;
12371 }
12372
12373 DeclContext *LookupContext = computeDeclContext(SS);
12374 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12375 if (!LookupContext || EllipsisLoc.isValid()) {
12376 NamedDecl *D;
12377 // Dependent scope, or an unexpanded pack
12378 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12379 SS, NameInfo, IdentLoc))
12380 return nullptr;
12381
12382 if (HasTypenameKeyword) {
12383 // FIXME: not all declaration name kinds are legal here
12384 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12385 UsingLoc, TypenameLoc,
12386 QualifierLoc,
12387 IdentLoc, NameInfo.getName(),
12388 EllipsisLoc);
12389 } else {
12390 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12391 QualifierLoc, NameInfo, EllipsisLoc);
12392 }
12393 D->setAccess(AS);
12394 CurContext->addDecl(D);
12395 ProcessDeclAttributeList(S, D, AttrList);
12396 return D;
12397 }
12398
12399 auto Build = [&](bool Invalid) {
12400 UsingDecl *UD =
12401 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12402 UsingName, HasTypenameKeyword);
12403 UD->setAccess(AS);
12404 CurContext->addDecl(UD);
12405 ProcessDeclAttributeList(S, UD, AttrList);
12406 UD->setInvalidDecl(Invalid);
12407 return UD;
12408 };
12409 auto BuildInvalid = [&]{ return Build(true); };
12410 auto BuildValid = [&]{ return Build(false); };
12411
12412 if (RequireCompleteDeclContext(SS, LookupContext))
12413 return BuildInvalid();
12414
12415 // Look up the target name.
12416 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12417
12418 // Unlike most lookups, we don't always want to hide tag
12419 // declarations: tag names are visible through the using declaration
12420 // even if hidden by ordinary names, *except* in a dependent context
12421 // where they may be used by two-phase lookup.
12422 if (!IsInstantiation)
12423 R.setHideTags(false);
12424
12425 // For the purposes of this lookup, we have a base object type
12426 // equal to that of the current context.
12427 if (CurContext->isRecord()) {
12428 R.setBaseObjectType(
12429 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12430 }
12431
12432 LookupQualifiedName(R, LookupContext);
12433
12434 // Validate the context, now we have a lookup
12435 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12436 IdentLoc, &R))
12437 return nullptr;
12438
12439 if (R.empty() && IsUsingIfExists)
12440 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12441 UsingName.getName()),
12442 AS_public);
12443
12444 // Try to correct typos if possible. If constructor name lookup finds no
12445 // results, that means the named class has no explicit constructors, and we
12446 // suppressed declaring implicit ones (probably because it's dependent or
12447 // invalid).
12448 if (R.empty() &&
12449 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12450 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12451 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12452 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12453 auto *II = NameInfo.getName().getAsIdentifierInfo();
12454 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12455 CurContext->isStdNamespace() &&
12456 isa<TranslationUnitDecl>(LookupContext) &&
12457 getSourceManager().isInSystemHeader(UsingLoc))
12458 return nullptr;
12459 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12460 dyn_cast<CXXRecordDecl>(CurContext));
12461 if (TypoCorrection Corrected =
12462 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12463 CTK_ErrorRecovery)) {
12464 // We reject candidates where DroppedSpecifier == true, hence the
12465 // literal '0' below.
12466 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12467 << NameInfo.getName() << LookupContext << 0
12468 << SS.getRange());
12469
12470 // If we picked a correction with no attached Decl we can't do anything
12471 // useful with it, bail out.
12472 NamedDecl *ND = Corrected.getCorrectionDecl();
12473 if (!ND)
12474 return BuildInvalid();
12475
12476 // If we corrected to an inheriting constructor, handle it as one.
12477 auto *RD = dyn_cast<CXXRecordDecl>(ND);
12478 if (RD && RD->isInjectedClassName()) {
12479 // The parent of the injected class name is the class itself.
12480 RD = cast<CXXRecordDecl>(RD->getParent());
12481
12482 // Fix up the information we'll use to build the using declaration.
12483 if (Corrected.WillReplaceSpecifier()) {
12484 NestedNameSpecifierLocBuilder Builder;
12485 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12486 QualifierLoc.getSourceRange());
12487 QualifierLoc = Builder.getWithLocInContext(Context);
12488 }
12489
12490 // In this case, the name we introduce is the name of a derived class
12491 // constructor.
12492 auto *CurClass = cast<CXXRecordDecl>(CurContext);
12493 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12494 Context.getCanonicalType(Context.getRecordType(CurClass))));
12495 UsingName.setNamedTypeInfo(nullptr);
12496 for (auto *Ctor : LookupConstructors(RD))
12497 R.addDecl(Ctor);
12498 R.resolveKind();
12499 } else {
12500 // FIXME: Pick up all the declarations if we found an overloaded
12501 // function.
12502 UsingName.setName(ND->getDeclName());
12503 R.addDecl(ND);
12504 }
12505 } else {
12506 Diag(IdentLoc, diag::err_no_member)
12507 << NameInfo.getName() << LookupContext << SS.getRange();
12508 return BuildInvalid();
12509 }
12510 }
12511
12512 if (R.isAmbiguous())
12513 return BuildInvalid();
12514
12515 if (HasTypenameKeyword) {
12516 // If we asked for a typename and got a non-type decl, error out.
12517 if (!R.getAsSingle<TypeDecl>() &&
12518 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12519 Diag(IdentLoc, diag::err_using_typename_non_type);
12520 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12521 Diag((*I)->getUnderlyingDecl()->getLocation(),
12522 diag::note_using_decl_target);
12523 return BuildInvalid();
12524 }
12525 } else {
12526 // If we asked for a non-typename and we got a type, error out,
12527 // but only if this is an instantiation of an unresolved using
12528 // decl. Otherwise just silently find the type name.
12529 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12530 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12531 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12532 return BuildInvalid();
12533 }
12534 }
12535
12536 // C++14 [namespace.udecl]p6:
12537 // A using-declaration shall not name a namespace.
12538 if (R.getAsSingle<NamespaceDecl>()) {
12539 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12540 << SS.getRange();
12541 return BuildInvalid();
12542 }
12543
12544 UsingDecl *UD = BuildValid();
12545
12546 // Some additional rules apply to inheriting constructors.
12547 if (UsingName.getName().getNameKind() ==
12548 DeclarationName::CXXConstructorName) {
12549 // Suppress access diagnostics; the access check is instead performed at the
12550 // point of use for an inheriting constructor.
12551 R.suppressDiagnostics();
12552 if (CheckInheritingConstructorUsingDecl(UD))
12553 return UD;
12554 }
12555
12556 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12557 UsingShadowDecl *PrevDecl = nullptr;
12558 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12559 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12560 }
12561
12562 return UD;
12563}
12564
12565NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12566 SourceLocation UsingLoc,
12567 SourceLocation EnumLoc,
12568 SourceLocation NameLoc,
12569 EnumDecl *ED) {
12570 bool Invalid = false;
12571
12572 if (CurContext->getRedeclContext()->isRecord()) {
12573 /// In class scope, check if this is a duplicate, for better a diagnostic.
12574 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12575 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12576 ForVisibleRedeclaration);
12577
12578 LookupName(Previous, S);
12579
12580 for (NamedDecl *D : Previous)
12581 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12582 if (UED->getEnumDecl() == ED) {
12583 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12584 << SourceRange(EnumLoc, NameLoc);
12585 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12586 Invalid = true;
12587 break;
12588 }
12589 }
12590
12591 if (RequireCompleteEnumDecl(ED, NameLoc))
12592 Invalid = true;
12593
12594 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12595 EnumLoc, NameLoc, ED);
12596 UD->setAccess(AS);
12597 CurContext->addDecl(UD);
12598
12599 if (Invalid) {
12600 UD->setInvalidDecl();
12601 return UD;
12602 }
12603
12604 // Create the shadow decls for each enumerator
12605 for (EnumConstantDecl *EC : ED->enumerators()) {
12606 UsingShadowDecl *PrevDecl = nullptr;
12607 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12608 LookupResult Previous(*this, DNI, LookupOrdinaryName,
12609 ForVisibleRedeclaration);
12610 LookupName(Previous, S);
12611 FilterUsingLookup(S, Previous);
12612
12613 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12614 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12615 }
12616
12617 return UD;
12618}
12619
12620NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12621 ArrayRef<NamedDecl *> Expansions) {
12622 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", 12624, __extension__ __PRETTY_FUNCTION__
))
12623 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", 12624, __extension__ __PRETTY_FUNCTION__
))
12624 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", 12624, __extension__ __PRETTY_FUNCTION__
))
;
12625
12626 auto *UPD =
12627 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12628 UPD->setAccess(InstantiatedFrom->getAccess());
12629 CurContext->addDecl(UPD);
12630 return UPD;
12631}
12632
12633/// Additional checks for a using declaration referring to a constructor name.
12634bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12635 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", 12635, __extension__ __PRETTY_FUNCTION__
))
;
12636
12637 const Type *SourceType = UD->getQualifier()->getAsType();
12638 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", 12639, __extension__ __PRETTY_FUNCTION__
))
12639 "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", 12639, __extension__ __PRETTY_FUNCTION__
))
;
12640 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12641
12642 // Check whether the named type is a direct base class.
12643 bool AnyDependentBases = false;
12644 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12645 AnyDependentBases);
12646 if (!Base && !AnyDependentBases) {
12647 Diag(UD->getUsingLoc(),
12648 diag::err_using_decl_constructor_not_in_direct_base)
12649 << UD->getNameInfo().getSourceRange()
12650 << QualType(SourceType, 0) << TargetClass;
12651 UD->setInvalidDecl();
12652 return true;
12653 }
12654
12655 if (Base)
12656 Base->setInheritConstructors();
12657
12658 return false;
12659}
12660
12661/// Checks that the given using declaration is not an invalid
12662/// redeclaration. Note that this is checking only for the using decl
12663/// itself, not for any ill-formedness among the UsingShadowDecls.
12664bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12665 bool HasTypenameKeyword,
12666 const CXXScopeSpec &SS,
12667 SourceLocation NameLoc,
12668 const LookupResult &Prev) {
12669 NestedNameSpecifier *Qual = SS.getScopeRep();
12670
12671 // C++03 [namespace.udecl]p8:
12672 // C++0x [namespace.udecl]p10:
12673 // A using-declaration is a declaration and can therefore be used
12674 // repeatedly where (and only where) multiple declarations are
12675 // allowed.
12676 //
12677 // That's in non-member contexts.
12678 if (!CurContext->getRedeclContext()->isRecord()) {
12679 // A dependent qualifier outside a class can only ever resolve to an
12680 // enumeration type. Therefore it conflicts with any other non-type
12681 // declaration in the same scope.
12682 // FIXME: How should we check for dependent type-type conflicts at block
12683 // scope?
12684 if (Qual->isDependent() && !HasTypenameKeyword) {
12685 for (auto *D : Prev) {
12686 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12687 bool OldCouldBeEnumerator =
12688 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12689 Diag(NameLoc,
12690 OldCouldBeEnumerator ? diag::err_redefinition
12691 : diag::err_redefinition_different_kind)
12692 << Prev.getLookupName();
12693 Diag(D->getLocation(), diag::note_previous_definition);
12694 return true;
12695 }
12696 }
12697 }
12698 return false;
12699 }
12700
12701 const NestedNameSpecifier *CNNS =
12702 Context.getCanonicalNestedNameSpecifier(Qual);
12703 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12704 NamedDecl *D = *I;
12705
12706 bool DTypename;
12707 NestedNameSpecifier *DQual;
12708 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12709 DTypename = UD->hasTypename();
12710 DQual = UD->getQualifier();
12711 } else if (UnresolvedUsingValueDecl *UD
12712 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12713 DTypename = false;
12714 DQual = UD->getQualifier();
12715 } else if (UnresolvedUsingTypenameDecl *UD
12716 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12717 DTypename = true;
12718 DQual = UD->getQualifier();
12719 } else continue;
12720
12721 // using decls differ if one says 'typename' and the other doesn't.
12722 // FIXME: non-dependent using decls?
12723 if (HasTypenameKeyword != DTypename) continue;
12724
12725 // using decls differ if they name different scopes (but note that
12726 // template instantiation can cause this check to trigger when it
12727 // didn't before instantiation).
12728 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
12729 continue;
12730
12731 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12732 Diag(D->getLocation(), diag::note_using_decl) << 1;
12733 return true;
12734 }
12735
12736 return false;
12737}
12738
12739/// Checks that the given nested-name qualifier used in a using decl
12740/// in the current context is appropriately related to the current
12741/// scope. If an error is found, diagnoses it and returns true.
12742/// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12743/// result of that lookup. UD is likewise nullptr, except when we have an
12744/// already-populated UsingDecl whose shadow decls contain the same information
12745/// (i.e. we're instantiating a UsingDecl with non-dependent scope).
12746bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
12747 const CXXScopeSpec &SS,
12748 const DeclarationNameInfo &NameInfo,
12749 SourceLocation NameLoc,
12750 const LookupResult *R, const UsingDecl *UD) {
12751 DeclContext *NamedContext = computeDeclContext(SS);
12752 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", 12753, __extension__ __PRETTY_FUNCTION__
))
12753 "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", 12753, __extension__ __PRETTY_FUNCTION__
))
;
12754
12755 // C++ 20 permits using an enumerator that does not have a class-hierarchy
12756 // relationship.
12757 bool Cxx20Enumerator = false;
12758 if (NamedContext) {
12759 EnumConstantDecl *EC = nullptr;
12760 if (R)
12761 EC = R->getAsSingle<EnumConstantDecl>();
12762 else if (UD && UD->shadow_size() == 1)
12763 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
12764 if (EC)
12765 Cxx20Enumerator = getLangOpts().CPlusPlus20;
12766
12767 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12768 // C++14 [namespace.udecl]p7:
12769 // A using-declaration shall not name a scoped enumerator.
12770 // C++20 p1099 permits enumerators.
12771 if (EC && R && ED->isScoped())
12772 Diag(SS.getBeginLoc(),
12773 getLangOpts().CPlusPlus20
12774 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12775 : diag::ext_using_decl_scoped_enumerator)
12776 << SS.getRange();
12777
12778 // We want to consider the scope of the enumerator
12779 NamedContext = ED->getDeclContext();
12780 }
12781 }
12782
12783 if (!CurContext->isRecord()) {
12784 // C++03 [namespace.udecl]p3:
12785 // C++0x [namespace.udecl]p8:
12786 // A using-declaration for a class member shall be a member-declaration.
12787 // C++20 [namespace.udecl]p7
12788 // ... other than an enumerator ...
12789
12790 // If we weren't able to compute a valid scope, it might validly be a
12791 // dependent class or enumeration scope. If we have a 'typename' keyword,
12792 // the scope must resolve to a class type.
12793 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
12794 : !HasTypename)
12795 return false; // OK
12796
12797 Diag(NameLoc,
12798 Cxx20Enumerator
12799 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12800 : diag::err_using_decl_can_not_refer_to_class_member)
12801 << SS.getRange();
12802
12803 if (Cxx20Enumerator)
12804 return false; // OK
12805
12806 auto *RD = NamedContext
12807 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12808 : nullptr;
12809 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
12810 // See if there's a helpful fixit
12811
12812 if (!R) {
12813 // We will have already diagnosed the problem on the template
12814 // definition, Maybe we should do so again?
12815 } else if (R->getAsSingle<TypeDecl>()) {
12816 if (getLangOpts().CPlusPlus11) {
12817 // Convert 'using X::Y;' to 'using Y = X::Y;'.
12818 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12819 << 0 // alias declaration
12820 << FixItHint::CreateInsertion(SS.getBeginLoc(),
12821 NameInfo.getName().getAsString() +
12822 " = ");
12823 } else {
12824 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12825 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12826 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12827 << 1 // typedef declaration
12828 << FixItHint::CreateReplacement(UsingLoc, "typedef")
12829 << FixItHint::CreateInsertion(
12830 InsertLoc, " " + NameInfo.getName().getAsString());
12831 }
12832 } else if (R->getAsSingle<VarDecl>()) {
12833 // Don't provide a fixit outside C++11 mode; we don't want to suggest
12834 // repeating the type of the static data member here.
12835 FixItHint FixIt;
12836 if (getLangOpts().CPlusPlus11) {
12837 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12838 FixIt = FixItHint::CreateReplacement(
12839 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12840 }
12841
12842 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12843 << 2 // reference declaration
12844 << FixIt;
12845 } else if (R->getAsSingle<EnumConstantDecl>()) {
12846 // Don't provide a fixit outside C++11 mode; we don't want to suggest
12847 // repeating the type of the enumeration here, and we can't do so if
12848 // the type is anonymous.
12849 FixItHint FixIt;
12850 if (getLangOpts().CPlusPlus11) {
12851 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12852 FixIt = FixItHint::CreateReplacement(
12853 UsingLoc,
12854 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12855 }
12856
12857 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12858 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12859 << FixIt;
12860 }
12861 }
12862
12863 return true; // Fail
12864 }
12865
12866 // If the named context is dependent, we can't decide much.
12867 if (!NamedContext) {
12868 // FIXME: in C++0x, we can diagnose if we can prove that the
12869 // nested-name-specifier does not refer to a base class, which is
12870 // still possible in some cases.
12871
12872 // Otherwise we have to conservatively report that things might be
12873 // okay.
12874 return false;
12875 }
12876
12877 // The current scope is a record.
12878 if (!NamedContext->isRecord()) {
12879 // Ideally this would point at the last name in the specifier,
12880 // but we don't have that level of source info.
12881 Diag(SS.getBeginLoc(),
12882 Cxx20Enumerator
12883 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12884 : diag::err_using_decl_nested_name_specifier_is_not_class)
12885 << SS.getScopeRep() << SS.getRange();
12886
12887 if (Cxx20Enumerator)
12888 return false; // OK
12889
12890 return true;
12891 }
12892
12893 if (!NamedContext->isDependentContext() &&
12894 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12895 return true;
12896
12897 if (getLangOpts().CPlusPlus11) {
12898 // C++11 [namespace.udecl]p3:
12899 // In a using-declaration used as a member-declaration, the
12900 // nested-name-specifier shall name a base class of the class
12901 // being defined.
12902
12903 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12904 cast<CXXRecordDecl>(NamedContext))) {
12905
12906 if (Cxx20Enumerator) {
12907 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12908 << SS.getRange();
12909 return false;
12910 }
12911
12912 if (CurContext == NamedContext) {
12913 Diag(SS.getBeginLoc(),
12914 diag::err_using_decl_nested_name_specifier_is_current_class)
12915 << SS.getRange();
12916 return !getLangOpts().CPlusPlus20;
12917 }
12918
12919 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12920 Diag(SS.getBeginLoc(),
12921 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12922 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
12923 << SS.getRange();
12924 }
12925 return true;
12926 }
12927
12928 return false;
12929 }
12930
12931 // C++03 [namespace.udecl]p4:
12932 // A using-declaration used as a member-declaration shall refer
12933 // to a member of a base class of the class being defined [etc.].
12934
12935 // Salient point: SS doesn't have to name a base class as long as
12936 // lookup only finds members from base classes. Therefore we can
12937 // diagnose here only if we can prove that that can't happen,
12938 // i.e. if the class hierarchies provably don't intersect.
12939
12940 // TODO: it would be nice if "definitely valid" results were cached
12941 // in the UsingDecl and UsingShadowDecl so that these checks didn't
12942 // need to be repeated.
12943
12944 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12945 auto Collect = [&Bases](const CXXRecordDecl *Base) {
12946 Bases.insert(Base);
12947 return true;
12948 };
12949
12950 // Collect all bases. Return false if we find a dependent base.
12951 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12952 return false;
12953
12954 // Returns true if the base is dependent or is one of the accumulated base
12955 // classes.
12956 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12957 return !Bases.count(Base);
12958 };
12959
12960 // Return false if the class has a dependent base or if it or one
12961 // of its bases is present in the base set of the current context.
12962 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12963 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12964 return false;
12965
12966 Diag(SS.getRange().getBegin(),
12967 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12968 << SS.getScopeRep()
12969 << cast<CXXRecordDecl>(CurContext)
12970 << SS.getRange();
12971
12972 return true;
12973}
12974
12975Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12976 MultiTemplateParamsArg TemplateParamLists,
12977 SourceLocation UsingLoc, UnqualifiedId &Name,
12978 const ParsedAttributesView &AttrList,
12979 TypeResult Type, Decl *DeclFromDeclSpec) {
12980 // Skip up to the relevant declaration scope.
12981 while (S->isTemplateParamScope())
12982 S = S->getParent();
12983 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", 12984, __extension__ __PRETTY_FUNCTION__
))
12984 "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", 12984, __extension__ __PRETTY_FUNCTION__
))
;
12985
12986 if (Type.isInvalid())
12987 return nullptr;
12988
12989 bool Invalid = false;
12990 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12991 TypeSourceInfo *TInfo = nullptr;
12992 GetTypeFromParser(Type.get(), &TInfo);
12993
12994 if (DiagnoseClassNameShadow(CurContext, NameInfo))
12995 return nullptr;
12996
12997 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12998 UPPC_DeclarationType)) {
12999 Invalid = true;
13000 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13001 TInfo->getTypeLoc().getBeginLoc());
13002 }
13003
13004 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13005 TemplateParamLists.size()
13006 ? forRedeclarationInCurContext()
13007 : ForVisibleRedeclaration);
13008 LookupName(Previous, S);
13009
13010 // Warn about shadowing the name of a template parameter.
13011 if (Previous.isSingleResult() &&
13012 Previous.getFoundDecl()->isTemplateParameter()) {
13013 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
13014 Previous.clear();
13015 }
13016
13017 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", 13018, __extension__ __PRETTY_FUNCTION__
))
13018 "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", 13018, __extension__ __PRETTY_FUNCTION__
))
;
13019 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
13020 Name.StartLocation,
13021 Name.Identifier, TInfo);
13022
13023 NewTD->setAccess(AS);
13024
13025 if (Invalid)
13026 NewTD->setInvalidDecl();
13027
13028 ProcessDeclAttributeList(S, NewTD, AttrList);
13029 AddPragmaAttributes(S, NewTD);
13030
13031 CheckTypedefForVariablyModifiedType(S, NewTD);
13032 Invalid |= NewTD->isInvalidDecl();
13033
13034 bool Redeclaration = false;
13035
13036 NamedDecl *NewND;
13037 if (TemplateParamLists.size()) {
13038 TypeAliasTemplateDecl *OldDecl = nullptr;
13039 TemplateParameterList *OldTemplateParams = nullptr;
13040
13041 if (TemplateParamLists.size() != 1) {
13042 Diag(UsingLoc, diag::err_alias_template_extra_headers)
13043 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13044 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13045 }
13046 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13047
13048 // Check that we can declare a template here.
13049 if (CheckTemplateDeclScope(S, TemplateParams))
13050 return nullptr;
13051
13052 // Only consider previous declarations in the same scope.
13053 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13054 /*ExplicitInstantiationOrSpecialization*/false);
13055 if (!Previous.empty()) {
13056 Redeclaration = true;
13057
13058 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13059 if (!OldDecl && !Invalid) {
13060 Diag(UsingLoc, diag::err_redefinition_different_kind)
13061 << Name.Identifier;
13062
13063 NamedDecl *OldD = Previous.getRepresentativeDecl();
13064 if (OldD->getLocation().isValid())
13065 Diag(OldD->getLocation(), diag::note_previous_definition);
13066
13067 Invalid = true;
13068 }
13069
13070 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13071 if (TemplateParameterListsAreEqual(TemplateParams,
13072 OldDecl->getTemplateParameters(),
13073 /*Complain=*/true,
13074 TPL_TemplateMatch))
13075 OldTemplateParams =
13076 OldDecl->getMostRecentDecl()->getTemplateParameters();
13077 else
13078 Invalid = true;
13079
13080 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13081 if (!Invalid &&
13082 !Context.hasSameType(OldTD->getUnderlyingType(),
13083 NewTD->getUnderlyingType())) {
13084 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13085 // but we can't reasonably accept it.
13086 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13087 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13088 if (OldTD->getLocation().isValid())
13089 Diag(OldTD->getLocation(), diag::note_previous_definition);
13090 Invalid = true;
13091 }
13092 }
13093 }
13094
13095 // Merge any previous default template arguments into our parameters,
13096 // and check the parameter list.
13097 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13098 TPC_TypeAliasTemplate))
13099 return nullptr;
13100
13101 TypeAliasTemplateDecl *NewDecl =
13102 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13103 Name.Identifier, TemplateParams,
13104 NewTD);
13105 NewTD->setDescribedAliasTemplate(NewDecl);
13106
13107 NewDecl->setAccess(AS);
13108
13109 if (Invalid)
13110 NewDecl->setInvalidDecl();
13111 else if (OldDecl) {
13112 NewDecl->setPreviousDecl(OldDecl);
13113 CheckRedeclarationInModule(NewDecl, OldDecl);
13114 }
13115
13116 NewND = NewDecl;
13117 } else {
13118 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13119 setTagNameForLinkagePurposes(TD, NewTD);
13120 handleTagNumbering(TD, S);
13121 }
13122 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13123 NewND = NewTD;
13124 }
13125
13126 PushOnScopeChains(NewND, S);
13127 ActOnDocumentableDecl(NewND);
13128 return NewND;
13129}
13130
13131Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13132 SourceLocation AliasLoc,
13133 IdentifierInfo *Alias, CXXScopeSpec &SS,
13134 SourceLocation IdentLoc,
13135 IdentifierInfo *Ident) {
13136
13137 // Lookup the namespace name.
13138 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13139 LookupParsedName(R, S, &SS);
13140
13141 if (R.isAmbiguous())
13142 return nullptr;
13143
13144 if (R.empty()) {
13145 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13146 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13147 return nullptr;
13148 }
13149 }
13150 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", 13150, __extension__ __PRETTY_FUNCTION__
))
;
13151 NamedDecl *ND = R.getRepresentativeDecl();
13152
13153 // Check if we have a previous declaration with the same name.
13154 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13155 ForVisibleRedeclaration);
13156 LookupName(PrevR, S);
13157
13158 // Check we're not shadowing a template parameter.
13159 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13160 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13161 PrevR.clear();
13162 }
13163
13164 // Filter out any other lookup result from an enclosing scope.
13165 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13166 /*AllowInlineNamespace*/false);
13167
13168 // Find the previous declaration and check that we can redeclare it.
13169 NamespaceAliasDecl *Prev = nullptr;
13170 if (PrevR.isSingleResult()) {
13171 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13172 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13173 // We already have an alias with the same name that points to the same
13174 // namespace; check that it matches.
13175 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13176 Prev = AD;
13177 } else if (isVisible(PrevDecl)) {
13178 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13179 << Alias;
13180 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13181 << AD->getNamespace();
13182 return nullptr;
13183 }
13184 } else if (isVisible(PrevDecl)) {
13185 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13186 ? diag::err_redefinition
13187 : diag::err_redefinition_different_kind;
13188 Diag(AliasLoc, DiagID) << Alias;
13189 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13190 return nullptr;
13191 }
13192 }
13193
13194 // The use of a nested name specifier may trigger deprecation warnings.
13195 DiagnoseUseOfDecl(ND, IdentLoc);
13196
13197 NamespaceAliasDecl *AliasDecl =
13198 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13199 Alias, SS.getWithLocInContext(Context),
13200 IdentLoc, ND);
13201 if (Prev)
13202 AliasDecl->setPreviousDecl(Prev);
13203
13204 PushOnScopeChains(AliasDecl, S);
13205 return AliasDecl;
13206}
13207
13208namespace {
13209struct SpecialMemberExceptionSpecInfo
13210 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13211 SourceLocation Loc;
13212 Sema::ImplicitExceptionSpecification ExceptSpec;
13213
13214 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13215 Sema::CXXSpecialMember CSM,
13216 Sema::InheritedConstructorInfo *ICI,
13217 SourceLocation Loc)
13218 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13219
13220 bool visitBase(CXXBaseSpecifier *Base);
13221 bool visitField(FieldDecl *FD);
13222
13223 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13224 unsigned Quals);
13225
13226 void visitSubobjectCall(Subobject Subobj,
13227 Sema::SpecialMemberOverloadResult SMOR);
13228};
13229}
13230
13231bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13232 auto *RT = Base->getType()->getAs<RecordType>();
13233 if (!RT)
13234 return false;
13235
13236 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13237 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13238 if (auto *BaseCtor = SMOR.getMethod()) {
13239 visitSubobjectCall(Base, BaseCtor);
13240 return false;
13241 }
13242
13243 visitClassSubobject(BaseClass, Base, 0);
13244 return false;
13245}
13246
13247bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13248 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13249 Expr *E = FD->getInClassInitializer();
13250 if (!E)
13251 // FIXME: It's a little wasteful to build and throw away a
13252 // CXXDefaultInitExpr here.
13253 // FIXME: We should have a single context note pointing at Loc, and
13254 // this location should be MD->getLocation() instead, since that's
13255 // the location where we actually use the default init expression.
13256 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13257 if (E)
13258 ExceptSpec.CalledExpr(E);
13259 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13260 ->getAs<RecordType>()) {
13261 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13262 FD->getType().getCVRQualifiers());
13263 }
13264 return false;
13265}
13266
13267void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13268 Subobject Subobj,
13269 unsigned Quals) {
13270 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13271 bool IsMutable = Field && Field->isMutable();
13272 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13273}
13274
13275void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13276 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13277 // Note, if lookup fails, it doesn't matter what exception specification we
13278 // choose because the special member will be deleted.
13279 if (CXXMethodDecl *MD = SMOR.getMethod())
13280 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13281}
13282
13283bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13284 llvm::APSInt Result;
13285 ExprResult Converted = CheckConvertedConstantExpression(
13286 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13287 ExplicitSpec.setExpr(Converted.get());
13288 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13289 ExplicitSpec.setKind(Result.getBoolValue()
13290 ? ExplicitSpecKind::ResolvedTrue
13291 : ExplicitSpecKind::ResolvedFalse);
13292 return true;
13293 }
13294 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13295 return false;
13296}
13297
13298ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13299 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13300 if (!ExplicitExpr->isTypeDependent())
13301 tryResolveExplicitSpecifier(ES);
13302 return ES;
13303}
13304
13305static Sema::ImplicitExceptionSpecification
13306ComputeDefaultedSpecialMemberExceptionSpec(
13307 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13308 Sema::InheritedConstructorInfo *ICI) {
13309 ComputingExceptionSpec CES(S, MD, Loc);
13310
13311 CXXRecordDecl *ClassDecl = MD->getParent();
13312
13313 // C++ [except.spec]p14:
13314 // An implicitly declared special member function (Clause 12) shall have an
13315 // exception-specification. [...]
13316 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13317 if (ClassDecl->isInvalidDecl())
13318 return Info.ExceptSpec;
13319
13320 // FIXME: If this diagnostic fires, we're probably missing a check for
13321 // attempting to resolve an exception specification before it's known
13322 // at a higher level.
13323 if (S.RequireCompleteType(MD->getLocation(),
13324 S.Context.getRecordType(ClassDecl),
13325 diag::err_exception_spec_incomplete_type))
13326 return Info.ExceptSpec;
13327
13328 // C++1z [except.spec]p7:
13329 // [Look for exceptions thrown by] a constructor selected [...] to
13330 // initialize a potentially constructed subobject,
13331 // C++1z [except.spec]p8:
13332 // The exception specification for an implicitly-declared destructor, or a
13333 // destructor without a noexcept-specifier, is potentially-throwing if and
13334 // only if any of the destructors for any of its potentially constructed
13335 // subojects is potentially throwing.
13336 // FIXME: We respect the first rule but ignore the "potentially constructed"
13337 // in the second rule to resolve a core issue (no number yet) that would have
13338 // us reject:
13339 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13340 // struct B : A {};
13341 // struct C : B { void f(); };
13342 // ... due to giving B::~B() a non-throwing exception specification.
13343 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13344 : Info.VisitAllBases);
13345
13346 return Info.ExceptSpec;
13347}
13348
13349namespace {
13350/// RAII object to register a special member as being currently declared.
13351struct DeclaringSpecialMember {
13352 Sema &S;
13353 Sema::SpecialMemberDecl D;
13354 Sema::ContextRAII SavedContext;
13355 bool WasAlreadyBeingDeclared;
13356
13357 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13358 : S(S), D(RD, CSM), SavedContext(S, RD) {
13359 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13360 if (WasAlreadyBeingDeclared)
13361 // This almost never happens, but if it does, ensure that our cache
13362 // doesn't contain a stale result.
13363 S.SpecialMemberCache.clear();
13364 else {
13365 // Register a note to be produced if we encounter an error while
13366 // declaring the special member.
13367 Sema::CodeSynthesisContext Ctx;
13368 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13369 // FIXME: We don't have a location to use here. Using the class's
13370 // location maintains the fiction that we declare all special members
13371 // with the class, but (1) it's not clear that lying about that helps our
13372 // users understand what's going on, and (2) there may be outer contexts
13373 // on the stack (some of which are relevant) and printing them exposes
13374 // our lies.
13375 Ctx.PointOfInstantiation = RD->getLocation();
13376 Ctx.Entity = RD;
13377 Ctx.SpecialMember = CSM;
13378 S.pushCodeSynthesisContext(Ctx);
13379 }
13380 }
13381 ~DeclaringSpecialMember() {
13382 if (!WasAlreadyBeingDeclared) {
13383 S.SpecialMembersBeingDeclared.erase(D);
13384 S.popCodeSynthesisContext();
13385 }
13386 }
13387
13388 /// Are we already trying to declare this special member?
13389 bool isAlreadyBeingDeclared() const {
13390 return WasAlreadyBeingDeclared;
13391 }
13392};
13393}
13394
13395void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13396 // Look up any existing declarations, but don't trigger declaration of all
13397 // implicit special members with this name.
13398 DeclarationName Name = FD->getDeclName();
13399 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13400 ForExternalRedeclaration);
13401 for (auto *D : FD->getParent()->lookup(Name))
13402 if (auto *Acceptable = R.getAcceptableDecl(D))
13403 R.addDecl(Acceptable);
13404 R.resolveKind();
13405 R.suppressDiagnostics();
13406
13407 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13408 FD->isThisDeclarationADefinition());
13409}
13410
13411void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13412 QualType ResultTy,
13413 ArrayRef<QualType> Args) {
13414 // Build an exception specification pointing back at this constructor.
13415 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13416
13417 LangAS AS = getDefaultCXXMethodAddrSpace();
13418 if (AS != LangAS::Default) {
13419 EPI.TypeQuals.addAddressSpace(AS);
13420 }
13421
13422 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13423 SpecialMem->setType(QT);
13424
13425 // During template instantiation of implicit special member functions we need
13426 // a reliable TypeSourceInfo for the function prototype in order to allow
13427 // functions to be substituted.
13428 if (inTemplateInstantiation() &&
13429 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13430 TypeSourceInfo *TSI =
13431 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13432 SpecialMem->setTypeSourceInfo(TSI);
13433 }
13434}
13435
13436CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13437 CXXRecordDecl *ClassDecl) {
13438 // C++ [class.ctor]p5:
13439 // A default constructor for a class X is a constructor of class X
13440 // that can be called without an argument. If there is no
13441 // user-declared constructor for class X, a default constructor is
13442 // implicitly declared. An implicitly-declared default constructor
13443 // is an inline public member of its class.
13444 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", 13445, __extension__ __PRETTY_FUNCTION__
))
13445 "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", 13445, __extension__ __PRETTY_FUNCTION__
))
;
13446
13447 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13448 if (DSM.isAlreadyBeingDeclared())
13449 return nullptr;
13450
13451 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13452 CXXDefaultConstructor,
13453 false);
13454
13455 // Create the actual constructor declaration.
13456 CanQualType ClassType
13457 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13458 SourceLocation ClassLoc = ClassDecl->getLocation();
13459 DeclarationName Name
13460 = Context.DeclarationNames.getCXXConstructorName(ClassType);
13461 DeclarationNameInfo NameInfo(Name, ClassLoc);
13462 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13463 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13464 /*TInfo=*/nullptr, ExplicitSpecifier(),
13465 getCurFPFeatures().isFPConstrained(),
13466 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13467 Constexpr ? ConstexprSpecKind::Constexpr
13468 : ConstexprSpecKind::Unspecified);
13469 DefaultCon->setAccess(AS_public);
13470 DefaultCon->setDefaulted();
13471
13472 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13473
13474 if (getLangOpts().CUDA)
13475 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13476 DefaultCon,
13477 /* ConstRHS */ false,
13478 /* Diagnose */ false);
13479
13480 // We don't need to use SpecialMemberIsTrivial here; triviality for default
13481 // constructors is easy to compute.
13482 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13483
13484 // Note that we have declared this constructor.
13485 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13486
13487 Scope *S = getScopeForContext(ClassDecl);
13488 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13489
13490 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13491 SetDeclDeleted(DefaultCon, ClassLoc);
13492
13493 if (S)
13494 PushOnScopeChains(DefaultCon, S, false);
13495 ClassDecl->addDecl(DefaultCon);
13496
13497 return DefaultCon;
13498}
13499
13500void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13501 CXXConstructorDecl *Constructor) {
13502 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", 13505, __extension__ __PRETTY_FUNCTION__
))
13503 !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", 13505, __extension__ __PRETTY_FUNCTION__
))
13504 !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", 13505, __extension__ __PRETTY_FUNCTION__
))
13505 "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", 13505, __extension__ __PRETTY_FUNCTION__
))
;
13506 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13507 return;
13508
13509 CXXRecordDecl *ClassDecl = Constructor->getParent();
13510 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", 13510, __extension__ __PRETTY_FUNCTION__
))
;
13511
13512 SynthesizedFunctionScope Scope(*this, Constructor);
13513
13514 // The exception specification is needed because we are defining the
13515 // function.
13516 ResolveExceptionSpec(CurrentLocation,
13517 Constructor->getType()->castAs<FunctionProtoType>());
13518 MarkVTableUsed(CurrentLocation, ClassDecl);
13519
13520 // Add a context note for diagnostics produced after this point.
13521 Scope.addContextNote(CurrentLocation);
13522
13523 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13524 Constructor->setInvalidDecl();
13525 return;
13526 }
13527
13528 SourceLocation Loc = Constructor->getEndLoc().isValid()
13529 ? Constructor->getEndLoc()
13530 : Constructor->getLocation();
13531 Constructor->setBody(new (Context) CompoundStmt(Loc));
13532 Constructor->markUsed(Context);
13533
13534 if (ASTMutationListener *L = getASTMutationListener()) {
13535 L->CompletedImplicitDefinition(Constructor);
13536 }
13537
13538 DiagnoseUninitializedFields(*this, Constructor);
13539}
13540
13541void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13542 // Perform any delayed checks on exception specifications.
13543 CheckDelayedMemberExceptionSpecs();
13544}
13545
13546/// Find or create the fake constructor we synthesize to model constructing an
13547/// object of a derived class via a constructor of a base class.
13548CXXConstructorDecl *
13549Sema::findInheritingConstructor(SourceLocation Loc,
13550 CXXConstructorDecl *BaseCtor,
13551 ConstructorUsingShadowDecl *Shadow) {
13552 CXXRecordDecl *Derived = Shadow->getParent();
13553 SourceLocation UsingLoc = Shadow->getLocation();
13554
13555 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13556 // For now we use the name of the base class constructor as a member of the
13557 // derived class to indicate a (fake) inherited constructor name.
13558 DeclarationName Name = BaseCtor->getDeclName();
13559
13560 // Check to see if we already have a fake constructor for this inherited
13561 // constructor call.
13562 for (NamedDecl *Ctor : Derived->lookup(Name))
13563 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13564 ->getInheritedConstructor()
13565 .getConstructor(),
13566 BaseCtor))
13567 return cast<CXXConstructorDecl>(Ctor);
13568
13569 DeclarationNameInfo NameInfo(Name, UsingLoc);
13570 TypeSourceInfo *TInfo =
13571 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13572 FunctionProtoTypeLoc ProtoLoc =
13573 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13574
13575 // Check the inherited constructor is valid and find the list of base classes
13576 // from which it was inherited.
13577 InheritedConstructorInfo ICI(*this, Loc, Shadow);
13578
13579 bool Constexpr =
13580 BaseCtor->isConstexpr() &&
13581 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13582 false, BaseCtor, &ICI);
13583
13584 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13585 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13586 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13587 /*isInline=*/true,
13588 /*isImplicitlyDeclared=*/true,
13589 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13590 InheritedConstructor(Shadow, BaseCtor),
13591 BaseCtor->getTrailingRequiresClause());
13592 if (Shadow->isInvalidDecl())
13593 DerivedCtor->setInvalidDecl();
13594
13595 // Build an unevaluated exception specification for this fake constructor.
13596 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13597 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13598 EPI.ExceptionSpec.Type = EST_Unevaluated;
13599 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13600 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13601 FPT->getParamTypes(), EPI));
13602
13603 // Build the parameter declarations.
13604 SmallVector<ParmVarDecl *, 16> ParamDecls;
13605 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13606 TypeSourceInfo *TInfo =
13607 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13608 ParmVarDecl *PD = ParmVarDecl::Create(
13609 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13610 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13611 PD->setScopeInfo(0, I);
13612 PD->setImplicit();
13613 // Ensure attributes are propagated onto parameters (this matters for
13614 // format, pass_object_size, ...).
13615 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13616 ParamDecls.push_back(PD);
13617 ProtoLoc.setParam(I, PD);
13618 }
13619
13620 // Set up the new constructor.
13621 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", 13621, __extension__ __PRETTY_FUNCTION__
))
;
13622 DerivedCtor->setAccess(BaseCtor->getAccess());
13623 DerivedCtor->setParams(ParamDecls);
13624 Derived->addDecl(DerivedCtor);
13625
13626 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13627 SetDeclDeleted(DerivedCtor, UsingLoc);
13628
13629 return DerivedCtor;
13630}
13631
13632void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13633 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13634 Ctor->getInheritedConstructor().getShadowDecl());
13635 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13636 /*Diagnose*/true);
13637}
13638
13639void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13640 CXXConstructorDecl *Constructor) {
13641 CXXRecordDecl *ClassDecl = Constructor->getParent();
13642 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", 13644, __extension__ __PRETTY_FUNCTION__
))
13643 !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", 13644, __extension__ __PRETTY_FUNCTION__
))
13644 !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", 13644, __extension__ __PRETTY_FUNCTION__
))
;
13645 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13646 return;
13647
13648 // Initializations are performed "as if by a defaulted default constructor",
13649 // so enter the appropriate scope.
13650 SynthesizedFunctionScope Scope(*this, Constructor);
13651
13652 // The exception specification is needed because we are defining the
13653 // function.
13654 ResolveExceptionSpec(CurrentLocation,
13655 Constructor->getType()->castAs<FunctionProtoType>());
13656 MarkVTableUsed(CurrentLocation, ClassDecl);
13657
13658 // Add a context note for diagnostics produced after this point.
13659 Scope.addContextNote(CurrentLocation);
13660
13661 ConstructorUsingShadowDecl *Shadow =
13662 Constructor->getInheritedConstructor().getShadowDecl();
13663 CXXConstructorDecl *InheritedCtor =
13664 Constructor->getInheritedConstructor().getConstructor();
13665
13666 // [class.inhctor.init]p1:
13667 // initialization proceeds as if a defaulted default constructor is used to
13668 // initialize the D object and each base class subobject from which the
13669 // constructor was inherited
13670
13671 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13672 CXXRecordDecl *RD = Shadow->getParent();
13673 SourceLocation InitLoc = Shadow->getLocation();
13674
13675 // Build explicit initializers for all base classes from which the
13676 // constructor was inherited.
13677 SmallVector<CXXCtorInitializer*, 8> Inits;
13678 for (bool VBase : {false, true}) {
13679 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13680 if (B.isVirtual() != VBase)
13681 continue;
13682
13683 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13684 if (!BaseRD)
13685 continue;
13686
13687 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13688 if (!BaseCtor.first)
13689 continue;
13690
13691 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13692 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13693 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13694
13695 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13696 Inits.push_back(new (Context) CXXCtorInitializer(
13697 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13698 SourceLocation()));
13699 }
13700 }
13701
13702 // We now proceed as if for a defaulted default constructor, with the relevant
13703 // initializers replaced.
13704
13705 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13706 Constructor->setInvalidDecl();
13707 return;
13708 }
13709
13710 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13711 Constructor->markUsed(Context);
13712
13713 if (ASTMutationListener *L = getASTMutationListener()) {
13714 L->CompletedImplicitDefinition(Constructor);
13715 }
13716
13717 DiagnoseUninitializedFields(*this, Constructor);
13718}
13719
13720CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13721 // C++ [class.dtor]p2:
13722 // If a class has no user-declared destructor, a destructor is
13723 // declared implicitly. An implicitly-declared destructor is an
13724 // inline public member of its class.
13725 assert(ClassDecl->needsImplicitDestructor())(static_cast <bool> (ClassDecl->needsImplicitDestructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitDestructor()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 13725, __extension__ __PRETTY_FUNCTION__
))
;
13726
13727 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13728 if (DSM.isAlreadyBeingDeclared())
13729 return nullptr;
13730
13731 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13732 CXXDestructor,
13733 false);
13734
13735 // Create the actual destructor declaration.
13736 CanQualType ClassType
13737 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13738 SourceLocation ClassLoc = ClassDecl->getLocation();
13739 DeclarationName Name
13740 = Context.DeclarationNames.getCXXDestructorName(ClassType);
13741 DeclarationNameInfo NameInfo(Name, ClassLoc);
13742 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
13743 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
13744 getCurFPFeatures().isFPConstrained(),
13745 /*isInline=*/true,
13746 /*isImplicitlyDeclared=*/true,
13747 Constexpr ? ConstexprSpecKind::Constexpr
13748 : ConstexprSpecKind::Unspecified);
13749 Destructor->setAccess(AS_public);
13750 Destructor->setDefaulted();
13751
13752 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13753
13754 if (getLangOpts().CUDA)
13755 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13756 Destructor,
13757 /* ConstRHS */ false,
13758 /* Diagnose */ false);
13759
13760 // We don't need to use SpecialMemberIsTrivial here; triviality for
13761 // destructors is easy to compute.
13762 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13763 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13764 ClassDecl->hasTrivialDestructorForCall());
13765
13766 // Note that we have declared this destructor.
13767 ++getASTContext().NumImplicitDestructorsDeclared;
13768
13769 Scope *S = getScopeForContext(ClassDecl);
13770 CheckImplicitSpecialMemberDeclaration(S, Destructor);
13771
13772 // We can't check whether an implicit destructor is deleted before we complete
13773 // the definition of the class, because its validity depends on the alignment
13774 // of the class. We'll check this from ActOnFields once the class is complete.
13775 if (ClassDecl->isCompleteDefinition() &&
13776 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13777 SetDeclDeleted(Destructor, ClassLoc);
13778
13779 // Introduce this destructor into its scope.
13780 if (S)
13781 PushOnScopeChains(Destructor, S, false);
13782 ClassDecl->addDecl(Destructor);
13783
13784 return Destructor;
13785}
13786
13787void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13788 CXXDestructorDecl *Destructor) {
13789 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", 13792, __extension__ __PRETTY_FUNCTION__
))
13790 !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", 13792, __extension__ __PRETTY_FUNCTION__
))
13791 !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", 13792, __extension__ __PRETTY_FUNCTION__
))
13792 "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", 13792, __extension__ __PRETTY_FUNCTION__
))
;
13793 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13794 return;
13795
13796 CXXRecordDecl *ClassDecl = Destructor->getParent();
13797 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", 13797, __extension__ __PRETTY_FUNCTION__
))
;
13798
13799 SynthesizedFunctionScope Scope(*this, Destructor);
13800
13801 // The exception specification is needed because we are defining the
13802 // function.
13803 ResolveExceptionSpec(CurrentLocation,
13804 Destructor->getType()->castAs<FunctionProtoType>());
13805 MarkVTableUsed(CurrentLocation, ClassDecl);
13806
13807 // Add a context note for diagnostics produced after this point.
13808 Scope.addContextNote(CurrentLocation);
13809
13810 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13811 Destructor->getParent());
13812
13813 if (CheckDestructor(Destructor)) {
13814 Destructor->setInvalidDecl();
13815 return;
13816 }
13817
13818 SourceLocation Loc = Destructor->getEndLoc().isValid()
13819 ? Destructor->getEndLoc()
13820 : Destructor->getLocation();
13821 Destructor->setBody(new (Context) CompoundStmt(Loc));
13822 Destructor->markUsed(Context);
13823
13824 if (ASTMutationListener *L = getASTMutationListener()) {
13825 L->CompletedImplicitDefinition(Destructor);
13826 }
13827}
13828
13829void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13830 CXXDestructorDecl *Destructor) {
13831 if (Destructor->isInvalidDecl())
13832 return;
13833
13834 CXXRecordDecl *ClassDecl = Destructor->getParent();
13835 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", 13836, __extension__ __PRETTY_FUNCTION__
))
13836 "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", 13836, __extension__ __PRETTY_FUNCTION__
))
;
13837 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", 13838, __extension__ __PRETTY_FUNCTION__
))
13838 "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", 13838, __extension__ __PRETTY_FUNCTION__
))
;
13839
13840 SynthesizedFunctionScope Scope(*this, Destructor);
13841
13842 // Add a context note for diagnostics produced after this point.
13843 Scope.addContextNote(CurrentLocation);
13844
13845 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13846}
13847
13848/// Perform any semantic analysis which needs to be delayed until all
13849/// pending class member declarations have been parsed.
13850void Sema::ActOnFinishCXXMemberDecls() {
13851 // If the context is an invalid C++ class, just suppress these checks.
13852 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13853 if (Record->isInvalidDecl()) {
13854 DelayedOverridingExceptionSpecChecks.clear();
13855 DelayedEquivalentExceptionSpecChecks.clear();
13856 return;
13857 }
13858 checkForMultipleExportedDefaultConstructors(*this, Record);
13859 }
13860}
13861
13862void Sema::ActOnFinishCXXNonNestedClass() {
13863 referenceDLLExportedClassMethods();
13864
13865 if (!DelayedDllExportMemberFunctions.empty()) {
13866 SmallVector<CXXMethodDecl*, 4> WorkList;
13867 std::swap(DelayedDllExportMemberFunctions, WorkList);
13868 for (CXXMethodDecl *M : WorkList) {
13869 DefineDefaultedFunction(*this, M, M->getLocation());
13870
13871 // Pass the method to the consumer to get emitted. This is not necessary
13872 // for explicit instantiation definitions, as they will get emitted
13873 // anyway.
13874 if (M->getParent()->getTemplateSpecializationKind() !=
13875 TSK_ExplicitInstantiationDefinition)
13876 ActOnFinishInlineFunctionDef(M);
13877 }
13878 }
13879}
13880
13881void Sema::referenceDLLExportedClassMethods() {
13882 if (!DelayedDllExportClasses.empty()) {
13883 // Calling ReferenceDllExportedMembers might cause the current function to
13884 // be called again, so use a local copy of DelayedDllExportClasses.
13885 SmallVector<CXXRecordDecl *, 4> WorkList;
13886 std::swap(DelayedDllExportClasses, WorkList);
13887 for (CXXRecordDecl *Class : WorkList)
13888 ReferenceDllExportedMembers(*this, Class);
13889 }
13890}
13891
13892void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13893 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", 13894, __extension__ __PRETTY_FUNCTION__
))
13894 "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", 13894, __extension__ __PRETTY_FUNCTION__
))
;
13895
13896 if (Destructor->isDependentContext())
13897 return;
13898
13899 // C++11 [class.dtor]p3:
13900 // A declaration of a destructor that does not have an exception-
13901 // specification is implicitly considered to have the same exception-
13902 // specification as an implicit declaration.
13903 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13904 if (DtorType->hasExceptionSpec())
13905 return;
13906
13907 // Replace the destructor's type, building off the existing one. Fortunately,
13908 // the only thing of interest in the destructor type is its extended info.
13909 // The return and arguments are fixed.
13910 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13911 EPI.ExceptionSpec.Type = EST_Unevaluated;
13912 EPI.ExceptionSpec.SourceDecl = Destructor;
13913 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13914
13915 // FIXME: If the destructor has a body that could throw, and the newly created
13916 // spec doesn't allow exceptions, we should emit a warning, because this
13917 // change in behavior can break conforming C++03 programs at runtime.
13918 // However, we don't have a body or an exception specification yet, so it
13919 // needs to be done somewhere else.
13920}
13921
13922namespace {
13923/// An abstract base class for all helper classes used in building the
13924// copy/move operators. These classes serve as factory functions and help us
13925// avoid using the same Expr* in the AST twice.
13926class ExprBuilder {
13927 ExprBuilder(const ExprBuilder&) = delete;
13928 ExprBuilder &operator=(const ExprBuilder&) = delete;
13929
13930protected:
13931 static Expr *assertNotNull(Expr *E) {
13932 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", 13932, __extension__ __PRETTY_FUNCTION__
))
;
13933 return E;
13934 }
13935
13936public:
13937 ExprBuilder() {}
13938 virtual ~ExprBuilder() {}
13939
13940 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13941};
13942
13943class RefBuilder: public ExprBuilder {
13944 VarDecl *Var;
13945 QualType VarType;
13946
13947public:
13948 Expr *build(Sema &S, SourceLocation Loc) const override {
13949 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13950 }
13951
13952 RefBuilder(VarDecl *Var, QualType VarType)
13953 : Var(Var), VarType(VarType) {}
13954};
13955
13956class ThisBuilder: public ExprBuilder {
13957public:
13958 Expr *build(Sema &S, SourceLocation Loc) const override {
13959 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13960 }
13961};
13962
13963class CastBuilder: public ExprBuilder {
13964 const ExprBuilder &Builder;
13965 QualType Type;
13966 ExprValueKind Kind;
13967 const CXXCastPath &Path;
13968
13969public:
13970 Expr *build(Sema &S, SourceLocation Loc) const override {
13971 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13972 CK_UncheckedDerivedToBase, Kind,
13973 &Path).get());
13974 }
13975
13976 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13977 const CXXCastPath &Path)
13978 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13979};
13980
13981class DerefBuilder: public ExprBuilder {
13982 const ExprBuilder &Builder;
13983
13984public:
13985 Expr *build(Sema &S, SourceLocation Loc) const override {
13986 return assertNotNull(
13987 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13988 }
13989
13990 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13991};
13992
13993class MemberBuilder: public ExprBuilder {
13994 const ExprBuilder &Builder;
13995 QualType Type;
13996 CXXScopeSpec SS;
13997 bool IsArrow;
13998 LookupResult &MemberLookup;
13999
14000public:
14001 Expr *build(Sema &S, SourceLocation Loc) const override {
14002 return assertNotNull(S.BuildMemberReferenceExpr(
14003 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
14004 nullptr, MemberLookup, nullptr, nullptr).get());
14005 }
14006
14007 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14008 LookupResult &MemberLookup)
14009 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14010 MemberLookup(MemberLookup) {}
14011};
14012
14013class MoveCastBuilder: public ExprBuilder {
14014 const ExprBuilder &Builder;
14015
14016public:
14017 Expr *build(Sema &S, SourceLocation Loc) const override {
14018 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
14019 }
14020
14021 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14022};
14023
14024class LvalueConvBuilder: public ExprBuilder {
14025 const ExprBuilder &Builder;
14026
14027public:
14028 Expr *build(Sema &S, SourceLocation Loc) const override {
14029 return assertNotNull(
14030 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14031 }
14032
14033 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14034};
14035
14036class SubscriptBuilder: public ExprBuilder {
14037 const ExprBuilder &Base;
14038 const ExprBuilder &Index;
14039
14040public:
14041 Expr *build(Sema &S, SourceLocation Loc) const override {
14042 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14043 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14044 }
14045
14046 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14047 : Base(Base), Index(Index) {}
14048};
14049
14050} // end anonymous namespace
14051
14052/// When generating a defaulted copy or move assignment operator, if a field
14053/// should be copied with __builtin_memcpy rather than via explicit assignments,
14054/// do so. This optimization only applies for arrays of scalars, and for arrays
14055/// of class type where the selected copy/move-assignment operator is trivial.
14056static StmtResult
14057buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14058 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14059 // Compute the size of the memory buffer to be copied.
14060 QualType SizeType = S.Context.getSizeType();
14061 llvm::APInt Size(S.Context.getTypeSize(SizeType),
14062 S.Context.getTypeSizeInChars(T).getQuantity());
14063
14064 // Take the address of the field references for "from" and "to". We
14065 // directly construct UnaryOperators here because semantic analysis
14066 // does not permit us to take the address of an xvalue.
14067 Expr *From = FromB.build(S, Loc);
14068 From = UnaryOperator::Create(
14069 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14070 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14071 Expr *To = ToB.build(S, Loc);
14072 To = UnaryOperator::Create(
14073 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14074 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14075
14076 const Type *E = T->getBaseElementTypeUnsafe();
14077 bool NeedsCollectableMemCpy =
14078 E->isRecordType() &&
14079 E->castAs<RecordType>()->getDecl()->hasObjectMember();
14080
14081 // Create a reference to the __builtin_objc_memmove_collectable function
14082 StringRef MemCpyName = NeedsCollectableMemCpy ?
14083 "__builtin_objc_memmove_collectable" :
14084 "__builtin_memcpy";
14085 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14086 Sema::LookupOrdinaryName);
14087 S.LookupName(R, S.TUScope, true);
14088
14089 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14090 if (!MemCpy)
14091 // Something went horribly wrong earlier, and we will have complained
14092 // about it.
14093 return StmtError();
14094
14095 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14096 VK_PRValue, Loc, nullptr);
14097 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", 14097, __extension__ __PRETTY_FUNCTION__
))
;
14098
14099 Expr *CallArgs[] = {
14100 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14101 };
14102 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14103 Loc, CallArgs, Loc);
14104
14105 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", 14105, __extension__ __PRETTY_FUNCTION__
))
;
14106 return Call.getAs<Stmt>();
14107}
14108
14109/// Builds a statement that copies/moves the given entity from \p From to
14110/// \c To.
14111///
14112/// This routine is used to copy/move the members of a class with an
14113/// implicitly-declared copy/move assignment operator. When the entities being
14114/// copied are arrays, this routine builds for loops to copy them.
14115///
14116/// \param S The Sema object used for type-checking.
14117///
14118/// \param Loc The location where the implicit copy/move is being generated.
14119///
14120/// \param T The type of the expressions being copied/moved. Both expressions
14121/// must have this type.
14122///
14123/// \param To The expression we are copying/moving to.
14124///
14125/// \param From The expression we are copying/moving from.
14126///
14127/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14128/// Otherwise, it's a non-static member subobject.
14129///
14130/// \param Copying Whether we're copying or moving.
14131///
14132/// \param Depth Internal parameter recording the depth of the recursion.
14133///
14134/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14135/// if a memcpy should be used instead.
14136static StmtResult
14137buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14138 const ExprBuilder &To, const ExprBuilder &From,
14139 bool CopyingBaseSubobject, bool Copying,
14140 unsigned Depth = 0) {
14141 // C++11 [class.copy]p28:
14142 // Each subobject is assigned in the manner appropriate to its type:
14143 //
14144 // - if the subobject is of class type, as if by a call to operator= with
14145 // the subobject as the object expression and the corresponding
14146 // subobject of x as a single function argument (as if by explicit
14147 // qualification; that is, ignoring any possible virtual overriding
14148 // functions in more derived classes);
14149 //
14150 // C++03 [class.copy]p13:
14151 // - if the subobject is of class type, the copy assignment operator for
14152 // the class is used (as if by explicit qualification; that is,
14153 // ignoring any possible virtual overriding functions in more derived
14154 // classes);
14155 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14156 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14157
14158 // Look for operator=.
14159 DeclarationName Name
14160 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14161 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14162 S.LookupQualifiedName(OpLookup, ClassDecl, false);
14163
14164 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14165 // operator.
14166 if (!S.getLangOpts().CPlusPlus11) {
14167 LookupResult::Filter F = OpLookup.makeFilter();
14168 while (F.hasNext()) {
14169 NamedDecl *D = F.next();
14170 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14171 if (Method->isCopyAssignmentOperator() ||
14172 (!Copying && Method->isMoveAssignmentOperator()))
14173 continue;
14174
14175 F.erase();
14176 }
14177 F.done();
14178 }
14179
14180 // Suppress the protected check (C++ [class.protected]) for each of the
14181 // assignment operators we found. This strange dance is required when
14182 // we're assigning via a base classes's copy-assignment operator. To
14183 // ensure that we're getting the right base class subobject (without
14184 // ambiguities), we need to cast "this" to that subobject type; to
14185 // ensure that we don't go through the virtual call mechanism, we need
14186 // to qualify the operator= name with the base class (see below). However,
14187 // this means that if the base class has a protected copy assignment
14188 // operator, the protected member access check will fail. So, we
14189 // rewrite "protected" access to "public" access in this case, since we
14190 // know by construction that we're calling from a derived class.
14191 if (CopyingBaseSubobject) {
14192 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14193 L != LEnd; ++L) {
14194 if (L.getAccess() == AS_protected)
14195 L.setAccess(AS_public);
14196 }
14197 }
14198
14199 // Create the nested-name-specifier that will be used to qualify the
14200 // reference to operator=; this is required to suppress the virtual
14201 // call mechanism.
14202 CXXScopeSpec SS;
14203 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14204 SS.MakeTrivial(S.Context,
14205 NestedNameSpecifier::Create(S.Context, nullptr, false,
14206 CanonicalT),
14207 Loc);
14208
14209 // Create the reference to operator=.
14210 ExprResult OpEqualRef
14211 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14212 SS, /*TemplateKWLoc=*/SourceLocation(),
14213 /*FirstQualifierInScope=*/nullptr,
14214 OpLookup,
14215 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14216 /*SuppressQualifierCheck=*/true);
14217 if (OpEqualRef.isInvalid())
14218 return StmtError();
14219
14220 // Build the call to the assignment operator.
14221
14222 Expr *FromInst = From.build(S, Loc);
14223 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14224 OpEqualRef.getAs<Expr>(),
14225 Loc, FromInst, Loc);
14226 if (Call.isInvalid())
14227 return StmtError();
14228
14229 // If we built a call to a trivial 'operator=' while copying an array,
14230 // bail out. We'll replace the whole shebang with a memcpy.
14231 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14232 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14233 return StmtResult((Stmt*)nullptr);
14234
14235 // Convert to an expression-statement, and clean up any produced
14236 // temporaries.
14237 return S.ActOnExprStmt(Call);
14238 }
14239
14240 // - if the subobject is of scalar type, the built-in assignment
14241 // operator is used.
14242 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14243 if (!ArrayTy) {
14244 ExprResult Assignment = S.CreateBuiltinBinOp(
14245 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14246 if (Assignment.isInvalid())
14247 return StmtError();
14248 return S.ActOnExprStmt(Assignment);
14249 }
14250
14251 // - if the subobject is an array, each element is assigned, in the
14252 // manner appropriate to the element type;
14253
14254 // Construct a loop over the array bounds, e.g.,
14255 //
14256 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14257 //
14258 // that will copy each of the array elements.
14259 QualType SizeType = S.Context.getSizeType();
14260
14261 // Create the iteration variable.
14262 IdentifierInfo *IterationVarName = nullptr;
14263 {
14264 SmallString<8> Str;
14265 llvm::raw_svector_ostream OS(Str);
14266 OS << "__i" << Depth;
14267 IterationVarName = &S.Context.Idents.get(OS.str());
14268 }
14269 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14270 IterationVarName, SizeType,
14271 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14272 SC_None);
14273
14274 // Initialize the iteration variable to zero.
14275 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14276 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14277
14278 // Creates a reference to the iteration variable.
14279 RefBuilder IterationVarRef(IterationVar, SizeType);
14280 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14281
14282 // Create the DeclStmt that holds the iteration variable.
14283 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14284
14285 // Subscript the "from" and "to" expressions with the iteration variable.
14286 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14287 MoveCastBuilder FromIndexMove(FromIndexCopy);
14288 const ExprBuilder *FromIndex;
14289 if (Copying)
14290 FromIndex = &FromIndexCopy;
14291 else
14292 FromIndex = &FromIndexMove;
14293
14294 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14295
14296 // Build the copy/move for an individual element of the array.
14297 StmtResult Copy =
14298 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14299 ToIndex, *FromIndex, CopyingBaseSubobject,
14300 Copying, Depth + 1);
14301 // Bail out if copying fails or if we determined that we should use memcpy.
14302 if (Copy.isInvalid() || !Copy.get())
14303 return Copy;
14304
14305 // Create the comparison against the array bound.
14306 llvm::APInt Upper
14307 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14308 Expr *Comparison = BinaryOperator::Create(
14309 S.Context, IterationVarRefRVal.build(S, Loc),
14310 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14311 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14312 S.CurFPFeatureOverrides());
14313
14314 // Create the pre-increment of the iteration variable. We can determine
14315 // whether the increment will overflow based on the value of the array
14316 // bound.
14317 Expr *Increment = UnaryOperator::Create(
14318 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14319 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14320
14321 // Construct the loop that copies all elements of this array.
14322 return S.ActOnForStmt(
14323 Loc, Loc, InitStmt,
14324 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14325 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14326}
14327
14328static StmtResult
14329buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14330 const ExprBuilder &To, const ExprBuilder &From,
14331 bool CopyingBaseSubobject, bool Copying) {
14332 // Maybe we should use a memcpy?
14333 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14334 T.isTriviallyCopyableType(S.Context))
14335 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14336
14337 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14338 CopyingBaseSubobject,
14339 Copying, 0));
14340
14341 // If we ended up picking a trivial assignment operator for an array of a
14342 // non-trivially-copyable class type, just emit a memcpy.
14343 if (!Result.isInvalid() && !Result.get())
14344 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14345
14346 return Result;
14347}
14348
14349CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14350 // Note: The following rules are largely analoguous to the copy
14351 // constructor rules. Note that virtual bases are not taken into account
14352 // for determining the argument type of the operator. Note also that
14353 // operators taking an object instead of a reference are allowed.
14354 assert(ClassDecl->needsImplicitCopyAssignment())(static_cast <bool> (ClassDecl->needsImplicitCopyAssignment
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitCopyAssignment()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 14354, __extension__ __PRETTY_FUNCTION__
))
;
14355
14356 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14357 if (DSM.isAlreadyBeingDeclared())
14358 return nullptr;
14359
14360 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14361 LangAS AS = getDefaultCXXMethodAddrSpace();
14362 if (AS != LangAS::Default)
14363 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14364 QualType RetType = Context.getLValueReferenceType(ArgType);
14365 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14366 if (Const)
14367 ArgType = ArgType.withConst();
14368
14369 ArgType = Context.getLValueReferenceType(ArgType);
14370
14371 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14372 CXXCopyAssignment,
14373 Const);
14374
14375 // An implicitly-declared copy assignment operator is an inline public
14376 // member of its class.
14377 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14378 SourceLocation ClassLoc = ClassDecl->getLocation();
14379 DeclarationNameInfo NameInfo(Name, ClassLoc);
14380 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14381 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14382 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14383 getCurFPFeatures().isFPConstrained(),
14384 /*isInline=*/true,
14385 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14386 SourceLocation());
14387 CopyAssignment->setAccess(AS_public);
14388 CopyAssignment->setDefaulted();
14389 CopyAssignment->setImplicit();
14390
14391 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14392
14393 if (getLangOpts().CUDA)
14394 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14395 CopyAssignment,
14396 /* ConstRHS */ Const,
14397 /* Diagnose */ false);
14398
14399 // Add the parameter to the operator.
14400 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14401 ClassLoc, ClassLoc,
14402 /*Id=*/nullptr, ArgType,
14403 /*TInfo=*/nullptr, SC_None,
14404 nullptr);
14405 CopyAssignment->setParams(FromParam);
14406
14407 CopyAssignment->setTrivial(
14408 ClassDecl->needsOverloadResolutionForCopyAssignment()
14409 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14410 : ClassDecl->hasTrivialCopyAssignment());
14411
14412 // Note that we have added this copy-assignment operator.
14413 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14414
14415 Scope *S = getScopeForContext(ClassDecl);
14416 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14417
14418 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14419 ClassDecl->setImplicitCopyAssignmentIsDeleted();
14420 SetDeclDeleted(CopyAssignment, ClassLoc);
14421 }
14422
14423 if (S)
14424 PushOnScopeChains(CopyAssignment, S, false);
14425 ClassDecl->addDecl(CopyAssignment);
14426
14427 return CopyAssignment;
14428}
14429
14430/// Diagnose an implicit copy operation for a class which is odr-used, but
14431/// which is deprecated because the class has a user-declared copy constructor,
14432/// copy assignment operator, or destructor.
14433static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14434 assert(CopyOp->isImplicit())(static_cast <bool> (CopyOp->isImplicit()) ? void (0
) : __assert_fail ("CopyOp->isImplicit()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 14434, __extension__ __PRETTY_FUNCTION__))
;
14435
14436 CXXRecordDecl *RD = CopyOp->getParent();
14437 CXXMethodDecl *UserDeclaredOperation = nullptr;
14438
14439 if (RD->hasUserDeclaredDestructor()) {
14440 UserDeclaredOperation = RD->getDestructor();
14441 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14442 RD->hasUserDeclaredCopyConstructor()) {
14443 // Find any user-declared copy constructor.
14444 for (auto *I : RD->ctors()) {
14445 if (I->isCopyConstructor()) {
14446 UserDeclaredOperation = I;
14447 break;
14448 }
14449 }
14450 assert(UserDeclaredOperation)(static_cast <bool> (UserDeclaredOperation) ? void (0) :
__assert_fail ("UserDeclaredOperation", "clang/lib/Sema/SemaDeclCXX.cpp"
, 14450, __extension__ __PRETTY_FUNCTION__))
;
14451 } else if (isa<CXXConstructorDecl>(CopyOp) &&
14452 RD->hasUserDeclaredCopyAssignment()) {
14453 // Find any user-declared move assignment operator.
14454 for (auto *I : RD->methods()) {
14455 if (I->isCopyAssignmentOperator()) {
14456 UserDeclaredOperation = I;
14457 break;
14458 }
14459 }
14460 assert(UserDeclaredOperation)(static_cast <bool> (UserDeclaredOperation) ? void (0) :
__assert_fail ("UserDeclaredOperation", "clang/lib/Sema/SemaDeclCXX.cpp"
, 14460, __extension__ __PRETTY_FUNCTION__))
;
14461 }
14462
14463 if (UserDeclaredOperation) {
14464 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14465 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14466 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14467 unsigned DiagID =
14468 (UDOIsUserProvided && UDOIsDestructor)
14469 ? diag::warn_deprecated_copy_with_user_provided_dtor
14470 : (UDOIsUserProvided && !UDOIsDestructor)
14471 ? diag::warn_deprecated_copy_with_user_provided_copy
14472 : (!UDOIsUserProvided && UDOIsDestructor)
14473 ? diag::warn_deprecated_copy_with_dtor
14474 : diag::warn_deprecated_copy;
14475 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14476 << RD << IsCopyAssignment;
14477 }
14478}
14479
14480void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14481 CXXMethodDecl *CopyAssignOperator) {
14482 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", 14487, __extension__ __PRETTY_FUNCTION__
))
14483 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", 14487, __extension__ __PRETTY_FUNCTION__
))
14484 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", 14487, __extension__ __PRETTY_FUNCTION__
))
14485 !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", 14487, __extension__ __PRETTY_FUNCTION__
))
14486 !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", 14487, __extension__ __PRETTY_FUNCTION__
))
14487 "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", 14487, __extension__ __PRETTY_FUNCTION__
))
;
14488 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14489 return;
14490
14491 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14492 if (ClassDecl->isInvalidDecl()) {
14493 CopyAssignOperator->setInvalidDecl();
14494 return;
14495 }
14496
14497 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14498
14499 // The exception specification is needed because we are defining the
14500 // function.
14501 ResolveExceptionSpec(CurrentLocation,
14502 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14503
14504 // Add a context note for diagnostics produced after this point.
14505 Scope.addContextNote(CurrentLocation);
14506
14507 // C++11 [class.copy]p18:
14508 // The [definition of an implicitly declared copy assignment operator] is
14509 // deprecated if the class has a user-declared copy constructor or a
14510 // user-declared destructor.
14511 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14512 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14513
14514 // C++0x [class.copy]p30:
14515 // The implicitly-defined or explicitly-defaulted copy assignment operator
14516 // for a non-union class X performs memberwise copy assignment of its
14517 // subobjects. The direct base classes of X are assigned first, in the
14518 // order of their declaration in the base-specifier-list, and then the
14519 // immediate non-static data members of X are assigned, in the order in
14520 // which they were declared in the class definition.
14521
14522 // The statements that form the synthesized function body.
14523 SmallVector<Stmt*, 8> Statements;
14524
14525 // The parameter for the "other" object, which we are copying from.
14526 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14527 Qualifiers OtherQuals = Other->getType().getQualifiers();
14528 QualType OtherRefType = Other->getType();
14529 if (const LValueReferenceType *OtherRef
14530 = OtherRefType->getAs<LValueReferenceType>()) {
14531 OtherRefType = OtherRef->getPointeeType();
14532 OtherQuals = OtherRefType.getQualifiers();
14533 }
14534
14535 // Our location for everything implicitly-generated.
14536 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14537 ? CopyAssignOperator->getEndLoc()
14538 : CopyAssignOperator->getLocation();
14539
14540 // Builds a DeclRefExpr for the "other" object.
14541 RefBuilder OtherRef(Other, OtherRefType);
14542
14543 // Builds the "this" pointer.
14544 ThisBuilder This;
14545
14546 // Assign base classes.
14547 bool Invalid = false;
14548 for (auto &Base : ClassDecl->bases()) {
14549 // Form the assignment:
14550 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14551 QualType BaseType = Base.getType().getUnqualifiedType();
14552 if (!BaseType->isRecordType()) {
14553 Invalid = true;
14554 continue;
14555 }
14556
14557 CXXCastPath BasePath;
14558 BasePath.push_back(&Base);
14559
14560 // Construct the "from" expression, which is an implicit cast to the
14561 // appropriately-qualified base type.
14562 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14563 VK_LValue, BasePath);
14564
14565 // Dereference "this".
14566 DerefBuilder DerefThis(This);
14567 CastBuilder To(DerefThis,
14568 Context.getQualifiedType(
14569 BaseType, CopyAssignOperator->getMethodQualifiers()),
14570 VK_LValue, BasePath);
14571
14572 // Build the copy.
14573 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14574 To, From,
14575 /*CopyingBaseSubobject=*/true,
14576 /*Copying=*/true);
14577 if (Copy.isInvalid()) {
14578 CopyAssignOperator->setInvalidDecl();
14579 return;
14580 }
14581
14582 // Success! Record the copy.
14583 Statements.push_back(Copy.getAs<Expr>());
14584 }
14585
14586 // Assign non-static members.
14587 for (auto *Field : ClassDecl->fields()) {
14588 // FIXME: We should form some kind of AST representation for the implied
14589 // memcpy in a union copy operation.
14590 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14591 continue;
14592
14593 if (Field->isInvalidDecl()) {
14594 Invalid = true;
14595 continue;
14596 }
14597
14598 // Check for members of reference type; we can't copy those.
14599 if (Field->getType()->isReferenceType()) {
14600 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14601 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14602 Diag(Field->getLocation(), diag::note_declared_at);
14603 Invalid = true;
14604 continue;
14605 }
14606
14607 // Check for members of const-qualified, non-class type.
14608 QualType BaseType = Context.getBaseElementType(Field->getType());
14609 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14610 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14611 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14612 Diag(Field->getLocation(), diag::note_declared_at);
14613 Invalid = true;
14614 continue;
14615 }
14616
14617 // Suppress assigning zero-width bitfields.
14618 if (Field->isZeroLengthBitField(Context))
14619 continue;
14620
14621 QualType FieldType = Field->getType().getNonReferenceType();
14622 if (FieldType->isIncompleteArrayType()) {
14623 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", 14624, __extension__ __PRETTY_FUNCTION__
))
14624 "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", 14624, __extension__ __PRETTY_FUNCTION__
))
;
14625 continue;
14626 }
14627
14628 // Build references to the field in the object we're copying from and to.
14629 CXXScopeSpec SS; // Intentionally empty
14630 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14631 LookupMemberName);
14632 MemberLookup.addDecl(Field);
14633 MemberLookup.resolveKind();
14634
14635 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14636
14637 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14638
14639 // Build the copy of this field.
14640 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14641 To, From,
14642 /*CopyingBaseSubobject=*/false,
14643 /*Copying=*/true);
14644 if (Copy.isInvalid()) {
14645 CopyAssignOperator->setInvalidDecl();
14646 return;
14647 }
14648
14649 // Success! Record the copy.
14650 Statements.push_back(Copy.getAs<Stmt>());
14651 }
14652
14653 if (!Invalid) {
14654 // Add a "return *this;"
14655 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14656
14657 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14658 if (Return.isInvalid())
14659 Invalid = true;
14660 else
14661 Statements.push_back(Return.getAs<Stmt>());
14662 }
14663
14664 if (Invalid) {
14665 CopyAssignOperator->setInvalidDecl();
14666 return;
14667 }
14668
14669 StmtResult Body;
14670 {
14671 CompoundScopeRAII CompoundScope(*this);
14672 Body = ActOnCompoundStmt(Loc, Loc, Statements,
14673 /*isStmtExpr=*/false);
14674 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", 14674, __extension__ __PRETTY_FUNCTION__
))
;
14675 }
14676 CopyAssignOperator->setBody(Body.getAs<Stmt>());
14677 CopyAssignOperator->markUsed(Context);
14678
14679 if (ASTMutationListener *L = getASTMutationListener()) {
14680 L->CompletedImplicitDefinition(CopyAssignOperator);
14681 }
14682}
14683
14684CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14685 assert(ClassDecl->needsImplicitMoveAssignment())(static_cast <bool> (ClassDecl->needsImplicitMoveAssignment
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitMoveAssignment()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 14685, __extension__ __PRETTY_FUNCTION__
))
;
14686
14687 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14688 if (DSM.isAlreadyBeingDeclared())
14689 return nullptr;
14690
14691 // Note: The following rules are largely analoguous to the move
14692 // constructor rules.
14693
14694 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14695 LangAS AS = getDefaultCXXMethodAddrSpace();
14696 if (AS != LangAS::Default)
14697 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14698 QualType RetType = Context.getLValueReferenceType(ArgType);
14699 ArgType = Context.getRValueReferenceType(ArgType);
14700
14701 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14702 CXXMoveAssignment,
14703 false);
14704
14705 // An implicitly-declared move assignment operator is an inline public
14706 // member of its class.
14707 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14708 SourceLocation ClassLoc = ClassDecl->getLocation();
14709 DeclarationNameInfo NameInfo(Name, ClassLoc);
14710 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14711 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14712 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14713 getCurFPFeatures().isFPConstrained(),
14714 /*isInline=*/true,
14715 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14716 SourceLocation());
14717 MoveAssignment->setAccess(AS_public);
14718 MoveAssignment->setDefaulted();
14719 MoveAssignment->setImplicit();
14720
14721 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14722
14723 if (getLangOpts().CUDA)
14724 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14725 MoveAssignment,
14726 /* ConstRHS */ false,
14727 /* Diagnose */ false);
14728
14729 // Add the parameter to the operator.
14730 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14731 ClassLoc, ClassLoc,
14732 /*Id=*/nullptr, ArgType,
14733 /*TInfo=*/nullptr, SC_None,
14734 nullptr);
14735 MoveAssignment->setParams(FromParam);
14736
14737 MoveAssignment->setTrivial(
14738 ClassDecl->needsOverloadResolutionForMoveAssignment()
14739 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14740 : ClassDecl->hasTrivialMoveAssignment());
14741
14742 // Note that we have added this copy-assignment operator.
14743 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14744
14745 Scope *S = getScopeForContext(ClassDecl);
14746 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14747
14748 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14749 ClassDecl->setImplicitMoveAssignmentIsDeleted();
14750 SetDeclDeleted(MoveAssignment, ClassLoc);
14751 }
14752
14753 if (S)
14754 PushOnScopeChains(MoveAssignment, S, false);
14755 ClassDecl->addDecl(MoveAssignment);
14756
14757 return MoveAssignment;
14758}
14759
14760/// Check if we're implicitly defining a move assignment operator for a class
14761/// with virtual bases. Such a move assignment might move-assign the virtual
14762/// base multiple times.
14763static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14764 SourceLocation CurrentLocation) {
14765 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", 14765, __extension__ __PRETTY_FUNCTION__
))
;
14766
14767 // Only a virtual base could get implicitly move-assigned multiple times.
14768 // Only a non-trivial move assignment can observe this. We only want to
14769 // diagnose if we implicitly define an assignment operator that assigns
14770 // two base classes, both of which move-assign the same virtual base.
14771 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14772 Class->getNumBases() < 2)
14773 return;
14774
14775 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14776 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14777 VBaseMap VBases;
14778
14779 for (auto &BI : Class->bases()) {
14780 Worklist.push_back(&BI);
14781 while (!Worklist.empty()) {
14782 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14783 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14784
14785 // If the base has no non-trivial move assignment operators,
14786 // we don't care about moves from it.
14787 if (!Base->hasNonTrivialMoveAssignment())
14788 continue;
14789
14790 // If there's nothing virtual here, skip it.
14791 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14792 continue;
14793
14794 // If we're not actually going to call a move assignment for this base,
14795 // or the selected move assignment is trivial, skip it.
14796 Sema::SpecialMemberOverloadResult SMOR =
14797 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14798 /*ConstArg*/false, /*VolatileArg*/false,
14799 /*RValueThis*/true, /*ConstThis*/false,
14800 /*VolatileThis*/false);
14801 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14802 !SMOR.getMethod()->isMoveAssignmentOperator())
14803 continue;
14804
14805 if (BaseSpec->isVirtual()) {
14806 // We're going to move-assign this virtual base, and its move
14807 // assignment operator is not trivial. If this can happen for
14808 // multiple distinct direct bases of Class, diagnose it. (If it
14809 // only happens in one base, we'll diagnose it when synthesizing
14810 // that base class's move assignment operator.)
14811 CXXBaseSpecifier *&Existing =
14812 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14813 .first->second;
14814 if (Existing && Existing != &BI) {
14815 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14816 << Class << Base;
14817 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14818 << (Base->getCanonicalDecl() ==
14819 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14820 << Base << Existing->getType() << Existing->getSourceRange();
14821 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14822 << (Base->getCanonicalDecl() ==
14823 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14824 << Base << BI.getType() << BaseSpec->getSourceRange();
14825
14826 // Only diagnose each vbase once.
14827 Existing = nullptr;
14828 }
14829 } else {
14830 // Only walk over bases that have defaulted move assignment operators.
14831 // We assume that any user-provided move assignment operator handles
14832 // the multiple-moves-of-vbase case itself somehow.
14833 if (!SMOR.getMethod()->isDefaulted())
14834 continue;
14835
14836 // We're going to move the base classes of Base. Add them to the list.
14837 llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
14838 }
14839 }
14840 }
14841}
14842
14843void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14844 CXXMethodDecl *MoveAssignOperator) {
14845 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", 14850, __extension__ __PRETTY_FUNCTION__
))
14846 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", 14850, __extension__ __PRETTY_FUNCTION__
))
14847 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", 14850, __extension__ __PRETTY_FUNCTION__
))
14848 !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", 14850, __extension__ __PRETTY_FUNCTION__
))
14849 !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", 14850, __extension__ __PRETTY_FUNCTION__
))
14850 "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", 14850, __extension__ __PRETTY_FUNCTION__
))
;
14851 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14852 return;
14853
14854 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14855 if (ClassDecl->isInvalidDecl()) {
14856 MoveAssignOperator->setInvalidDecl();
14857 return;
14858 }
14859
14860 // C++0x [class.copy]p28:
14861 // The implicitly-defined or move assignment operator for a non-union class
14862 // X performs memberwise move assignment of its subobjects. The direct base
14863 // classes of X are assigned first, in the order of their declaration in the
14864 // base-specifier-list, and then the immediate non-static data members of X
14865 // are assigned, in the order in which they were declared in the class
14866 // definition.
14867
14868 // Issue a warning if our implicit move assignment operator will move
14869 // from a virtual base more than once.
14870 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14871
14872 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14873
14874 // The exception specification is needed because we are defining the
14875 // function.
14876 ResolveExceptionSpec(CurrentLocation,
14877 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14878
14879 // Add a context note for diagnostics produced after this point.
14880 Scope.addContextNote(CurrentLocation);
14881
14882 // The statements that form the synthesized function body.
14883 SmallVector<Stmt*, 8> Statements;
14884
14885 // The parameter for the "other" object, which we are move from.
14886 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14887 QualType OtherRefType =
14888 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14889
14890 // Our location for everything implicitly-generated.
14891 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14892 ? MoveAssignOperator->getEndLoc()
14893 : MoveAssignOperator->getLocation();
14894
14895 // Builds a reference to the "other" object.
14896 RefBuilder OtherRef(Other, OtherRefType);
14897 // Cast to rvalue.
14898 MoveCastBuilder MoveOther(OtherRef);
14899
14900 // Builds the "this" pointer.
14901 ThisBuilder This;
14902
14903 // Assign base classes.
14904 bool Invalid = false;
14905 for (auto &Base : ClassDecl->bases()) {
14906 // C++11 [class.copy]p28:
14907 // It is unspecified whether subobjects representing virtual base classes
14908 // are assigned more than once by the implicitly-defined copy assignment
14909 // operator.
14910 // FIXME: Do not assign to a vbase that will be assigned by some other base
14911 // class. For a move-assignment, this can result in the vbase being moved
14912 // multiple times.
14913
14914 // Form the assignment:
14915 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14916 QualType BaseType = Base.getType().getUnqualifiedType();
14917 if (!BaseType->isRecordType()) {
14918 Invalid = true;
14919 continue;
14920 }
14921
14922 CXXCastPath BasePath;
14923 BasePath.push_back(&Base);
14924
14925 // Construct the "from" expression, which is an implicit cast to the
14926 // appropriately-qualified base type.
14927 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14928
14929 // Dereference "this".
14930 DerefBuilder DerefThis(This);
14931
14932 // Implicitly cast "this" to the appropriately-qualified base type.
14933 CastBuilder To(DerefThis,
14934 Context.getQualifiedType(
14935 BaseType, MoveAssignOperator->getMethodQualifiers()),
14936 VK_LValue, BasePath);
14937
14938 // Build the move.
14939 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14940 To, From,
14941 /*CopyingBaseSubobject=*/true,
14942 /*Copying=*/false);
14943 if (Move.isInvalid()) {
14944 MoveAssignOperator->setInvalidDecl();
14945 return;
14946 }
14947
14948 // Success! Record the move.
14949 Statements.push_back(Move.getAs<Expr>());
14950 }
14951
14952 // Assign non-static members.
14953 for (auto *Field : ClassDecl->fields()) {
14954 // FIXME: We should form some kind of AST representation for the implied
14955 // memcpy in a union copy operation.
14956 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14957 continue;
14958
14959 if (Field->isInvalidDecl()) {
14960 Invalid = true;
14961 continue;
14962 }
14963
14964 // Check for members of reference type; we can't move those.
14965 if (Field->getType()->isReferenceType()) {
14966 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14967 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14968 Diag(Field->getLocation(), diag::note_declared_at);
14969 Invalid = true;
14970 continue;
14971 }
14972
14973 // Check for members of const-qualified, non-class type.
14974 QualType BaseType = Context.getBaseElementType(Field->getType());
14975 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14976 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14977 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14978 Diag(Field->getLocation(), diag::note_declared_at);
14979 Invalid = true;
14980 continue;
14981 }
14982
14983 // Suppress assigning zero-width bitfields.
14984 if (Field->isZeroLengthBitField(Context))
14985 continue;
14986
14987 QualType FieldType = Field->getType().getNonReferenceType();
14988 if (FieldType->isIncompleteArrayType()) {
14989 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", 14990, __extension__ __PRETTY_FUNCTION__
))
14990 "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", 14990, __extension__ __PRETTY_FUNCTION__
))
;
14991 continue;
14992 }
14993
14994 // Build references to the field in the object we're copying from and to.
14995 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14996 LookupMemberName);
14997 MemberLookup.addDecl(Field);
14998 MemberLookup.resolveKind();
14999 MemberBuilder From(MoveOther, OtherRefType,
15000 /*IsArrow=*/false, MemberLookup);
15001 MemberBuilder To(This, getCurrentThisType(),
15002 /*IsArrow=*/true, MemberLookup);
15003
15004 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", 15006, __extension__ __PRETTY_FUNCTION__
))
15005 "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", 15006, __extension__ __PRETTY_FUNCTION__
))
15006 "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", 15006, __extension__ __PRETTY_FUNCTION__
))
;
15007
15008 // Build the move of this field.
15009 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
15010 To, From,
15011 /*CopyingBaseSubobject=*/false,
15012 /*Copying=*/false);
15013 if (Move.isInvalid()) {
15014 MoveAssignOperator->setInvalidDecl();
15015 return;
15016 }
15017
15018 // Success! Record the copy.
15019 Statements.push_back(Move.getAs<Stmt>());
15020 }
15021
15022 if (!Invalid) {
15023 // Add a "return *this;"
15024 ExprResult ThisObj =
15025 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
15026
15027 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
15028 if (Return.isInvalid())
15029 Invalid = true;
15030 else
15031 Statements.push_back(Return.getAs<Stmt>());
15032 }
15033
15034 if (Invalid) {
15035 MoveAssignOperator->setInvalidDecl();
15036 return;
15037 }
15038
15039 StmtResult Body;
15040 {
15041 CompoundScopeRAII CompoundScope(*this);
15042 Body = ActOnCompoundStmt(Loc, Loc, Statements,
15043 /*isStmtExpr=*/false);
15044 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", 15044, __extension__ __PRETTY_FUNCTION__
))
;
15045 }
15046 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15047 MoveAssignOperator->markUsed(Context);
15048
15049 if (ASTMutationListener *L = getASTMutationListener()) {
15050 L->CompletedImplicitDefinition(MoveAssignOperator);
15051 }
15052}
15053
15054CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15055 CXXRecordDecl *ClassDecl) {
15056 // C++ [class.copy]p4:
15057 // If the class definition does not explicitly declare a copy
15058 // constructor, one is declared implicitly.
15059 assert(ClassDecl->needsImplicitCopyConstructor())(static_cast <bool> (ClassDecl->needsImplicitCopyConstructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitCopyConstructor()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15059, __extension__ __PRETTY_FUNCTION__
))
;
15060
15061 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15062 if (DSM.isAlreadyBeingDeclared())
15063 return nullptr;
15064
15065 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15066 QualType ArgType = ClassType;
15067 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15068 if (Const)
15069 ArgType = ArgType.withConst();
15070
15071 LangAS AS = getDefaultCXXMethodAddrSpace();
15072 if (AS != LangAS::Default)
15073 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15074
15075 ArgType = Context.getLValueReferenceType(ArgType);
15076
15077 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15078 CXXCopyConstructor,
15079 Const);
15080
15081 DeclarationName Name
15082 = Context.DeclarationNames.getCXXConstructorName(
15083 Context.getCanonicalType(ClassType));
15084 SourceLocation ClassLoc = ClassDecl->getLocation();
15085 DeclarationNameInfo NameInfo(Name, ClassLoc);
15086
15087 // An implicitly-declared copy constructor is an inline public
15088 // member of its class.
15089 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15090 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15091 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15092 /*isInline=*/true,
15093 /*isImplicitlyDeclared=*/true,
15094 Constexpr ? ConstexprSpecKind::Constexpr
15095 : ConstexprSpecKind::Unspecified);
15096 CopyConstructor->setAccess(AS_public);
15097 CopyConstructor->setDefaulted();
15098
15099 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15100
15101 if (getLangOpts().CUDA)
15102 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15103 CopyConstructor,
15104 /* ConstRHS */ Const,
15105 /* Diagnose */ false);
15106
15107 // During template instantiation of special member functions we need a
15108 // reliable TypeSourceInfo for the parameter types in order to allow functions
15109 // to be substituted.
15110 TypeSourceInfo *TSI = nullptr;
15111 if (inTemplateInstantiation() && ClassDecl->isLambda())
15112 TSI = Context.getTrivialTypeSourceInfo(ArgType);
15113
15114 // Add the parameter to the constructor.
15115 ParmVarDecl *FromParam =
15116 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15117 /*IdentifierInfo=*/nullptr, ArgType,
15118 /*TInfo=*/TSI, SC_None, nullptr);
15119 CopyConstructor->setParams(FromParam);
15120
15121 CopyConstructor->setTrivial(
15122 ClassDecl->needsOverloadResolutionForCopyConstructor()
15123 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15124 : ClassDecl->hasTrivialCopyConstructor());
15125
15126 CopyConstructor->setTrivialForCall(
15127 ClassDecl->hasAttr<TrivialABIAttr>() ||
15128 (ClassDecl->needsOverloadResolutionForCopyConstructor()
15129 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15130 TAH_ConsiderTrivialABI)
15131 : ClassDecl->hasTrivialCopyConstructorForCall()));
15132
15133 // Note that we have declared this constructor.
15134 ++getASTContext().NumImplicitCopyConstructorsDeclared;
15135
15136 Scope *S = getScopeForContext(ClassDecl);
15137 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15138
15139 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15140 ClassDecl->setImplicitCopyConstructorIsDeleted();
15141 SetDeclDeleted(CopyConstructor, ClassLoc);
15142 }
15143
15144 if (S)
15145 PushOnScopeChains(CopyConstructor, S, false);
15146 ClassDecl->addDecl(CopyConstructor);
15147
15148 return CopyConstructor;
15149}
15150
15151void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15152 CXXConstructorDecl *CopyConstructor) {
15153 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", 15157, __extension__ __PRETTY_FUNCTION__
))
15154 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", 15157, __extension__ __PRETTY_FUNCTION__
))
15155 !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", 15157, __extension__ __PRETTY_FUNCTION__
))
15156 !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", 15157, __extension__ __PRETTY_FUNCTION__
))
15157 "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", 15157, __extension__ __PRETTY_FUNCTION__
))
;
15158 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15159 return;
15160
15161 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15162 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", 15162, __extension__ __PRETTY_FUNCTION__
))
;
15163
15164 SynthesizedFunctionScope Scope(*this, CopyConstructor);
15165
15166 // The exception specification is needed because we are defining the
15167 // function.
15168 ResolveExceptionSpec(CurrentLocation,
15169 CopyConstructor->getType()->castAs<FunctionProtoType>());
15170 MarkVTableUsed(CurrentLocation, ClassDecl);
15171
15172 // Add a context note for diagnostics produced after this point.
15173 Scope.addContextNote(CurrentLocation);
15174
15175 // C++11 [class.copy]p7:
15176 // The [definition of an implicitly declared copy constructor] is
15177 // deprecated if the class has a user-declared copy assignment operator
15178 // or a user-declared destructor.
15179 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15180 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15181
15182 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15183 CopyConstructor->setInvalidDecl();
15184 } else {
15185 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15186 ? CopyConstructor->getEndLoc()
15187 : CopyConstructor->getLocation();
15188 Sema::CompoundScopeRAII CompoundScope(*this);
15189 CopyConstructor->setBody(
15190 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
15191 CopyConstructor->markUsed(Context);
15192 }
15193
15194 if (ASTMutationListener *L = getASTMutationListener()) {
15195 L->CompletedImplicitDefinition(CopyConstructor);
15196 }
15197}
15198
15199CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15200 CXXRecordDecl *ClassDecl) {
15201 assert(ClassDecl->needsImplicitMoveConstructor())(static_cast <bool> (ClassDecl->needsImplicitMoveConstructor
()) ? void (0) : __assert_fail ("ClassDecl->needsImplicitMoveConstructor()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15201, __extension__ __PRETTY_FUNCTION__
))
;
15202
15203 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15204 if (DSM.isAlreadyBeingDeclared())
15205 return nullptr;
15206
15207 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15208
15209 QualType ArgType = ClassType;
15210 LangAS AS = getDefaultCXXMethodAddrSpace();
15211 if (AS != LangAS::Default)
15212 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15213 ArgType = Context.getRValueReferenceType(ArgType);
15214
15215 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15216 CXXMoveConstructor,
15217 false);
15218
15219 DeclarationName Name
15220 = Context.DeclarationNames.getCXXConstructorName(
15221 Context.getCanonicalType(ClassType));
15222 SourceLocation ClassLoc = ClassDecl->getLocation();
15223 DeclarationNameInfo NameInfo(Name, ClassLoc);
15224
15225 // C++11 [class.copy]p11:
15226 // An implicitly-declared copy/move constructor is an inline public
15227 // member of its class.
15228 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15229 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15230 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15231 /*isInline=*/true,
15232 /*isImplicitlyDeclared=*/true,
15233 Constexpr ? ConstexprSpecKind::Constexpr
15234 : ConstexprSpecKind::Unspecified);
15235 MoveConstructor->setAccess(AS_public);
15236 MoveConstructor->setDefaulted();
15237
15238 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15239
15240 if (getLangOpts().CUDA)
15241 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15242 MoveConstructor,
15243 /* ConstRHS */ false,
15244 /* Diagnose */ false);
15245
15246 // Add the parameter to the constructor.
15247 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15248 ClassLoc, ClassLoc,
15249 /*IdentifierInfo=*/nullptr,
15250 ArgType, /*TInfo=*/nullptr,
15251 SC_None, nullptr);
15252 MoveConstructor->setParams(FromParam);
15253
15254 MoveConstructor->setTrivial(
15255 ClassDecl->needsOverloadResolutionForMoveConstructor()
15256 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15257 : ClassDecl->hasTrivialMoveConstructor());
15258
15259 MoveConstructor->setTrivialForCall(
15260 ClassDecl->hasAttr<TrivialABIAttr>() ||
15261 (ClassDecl->needsOverloadResolutionForMoveConstructor()
15262 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15263 TAH_ConsiderTrivialABI)
15264 : ClassDecl->hasTrivialMoveConstructorForCall()));
15265
15266 // Note that we have declared this constructor.
15267 ++getASTContext().NumImplicitMoveConstructorsDeclared;
15268
15269 Scope *S = getScopeForContext(ClassDecl);
15270 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15271
15272 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15273 ClassDecl->setImplicitMoveConstructorIsDeleted();
15274 SetDeclDeleted(MoveConstructor, ClassLoc);
15275 }
15276
15277 if (S)
15278 PushOnScopeChains(MoveConstructor, S, false);
15279 ClassDecl->addDecl(MoveConstructor);
15280
15281 return MoveConstructor;
15282}
15283
15284void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15285 CXXConstructorDecl *MoveConstructor) {
15286 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", 15290, __extension__ __PRETTY_FUNCTION__
))
15287 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", 15290, __extension__ __PRETTY_FUNCTION__
))
15288 !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", 15290, __extension__ __PRETTY_FUNCTION__
))
15289 !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", 15290, __extension__ __PRETTY_FUNCTION__
))
15290 "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", 15290, __extension__ __PRETTY_FUNCTION__
))
;
15291 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15292 return;
15293
15294 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15295 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", 15295, __extension__ __PRETTY_FUNCTION__
))
;
15296
15297 SynthesizedFunctionScope Scope(*this, MoveConstructor);
15298
15299 // The exception specification is needed because we are defining the
15300 // function.
15301 ResolveExceptionSpec(CurrentLocation,
15302 MoveConstructor->getType()->castAs<FunctionProtoType>());
15303 MarkVTableUsed(CurrentLocation, ClassDecl);
15304
15305 // Add a context note for diagnostics produced after this point.
15306 Scope.addContextNote(CurrentLocation);
15307
15308 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15309 MoveConstructor->setInvalidDecl();
15310 } else {
15311 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15312 ? MoveConstructor->getEndLoc()
15313 : MoveConstructor->getLocation();
15314 Sema::CompoundScopeRAII CompoundScope(*this);
15315 MoveConstructor->setBody(ActOnCompoundStmt(
15316 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
15317 MoveConstructor->markUsed(Context);
15318 }
15319
15320 if (ASTMutationListener *L = getASTMutationListener()) {
15321 L->CompletedImplicitDefinition(MoveConstructor);
15322 }
15323}
15324
15325bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15326 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15327}
15328
15329void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15330 SourceLocation CurrentLocation,
15331 CXXConversionDecl *Conv) {
15332 SynthesizedFunctionScope Scope(*this, Conv);
15333 assert(!Conv->getReturnType()->isUndeducedType())(static_cast <bool> (!Conv->getReturnType()->isUndeducedType
()) ? void (0) : __assert_fail ("!Conv->getReturnType()->isUndeducedType()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15333, __extension__ __PRETTY_FUNCTION__
))
;
15334
15335 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15336 CallingConv CC =
15337 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15338
15339 CXXRecordDecl *Lambda = Conv->getParent();
15340 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15341 FunctionDecl *Invoker =
15342 CallOp->isStatic() ? CallOp : Lambda->getLambdaStaticInvoker(CC);
15343
15344 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15345 CallOp = InstantiateFunctionDeclaration(
15346 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15347 if (!CallOp)
15348 return;
15349
15350 if (CallOp != Invoker) {
15351 Invoker = InstantiateFunctionDeclaration(
15352 Invoker->getDescribedFunctionTemplate(), TemplateArgs,
15353 CurrentLocation);
15354 if (!Invoker)
15355 return;
15356 }
15357 }
15358
15359 if (CallOp->isInvalidDecl())
15360 return;
15361
15362 // Mark the call operator referenced (and add to pending instantiations
15363 // if necessary).
15364 // For both the conversion and static-invoker template specializations
15365 // we construct their body's in this function, so no need to add them
15366 // to the PendingInstantiations.
15367 MarkFunctionReferenced(CurrentLocation, CallOp);
15368
15369 if (Invoker != CallOp) {
15370 // Fill in the __invoke function with a dummy implementation. IR generation
15371 // will fill in the actual details. Update its type in case it contained
15372 // an 'auto'.
15373 Invoker->markUsed(Context);
15374 Invoker->setReferenced();
15375 Invoker->setType(Conv->getReturnType()->getPointeeType());
15376 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15377 }
15378
15379 // Construct the body of the conversion function { return __invoke; }.
15380 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue,
15381 Conv->getLocation());
15382 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", 15382, __extension__ __PRETTY_FUNCTION__
))
;
15383 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15384 Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(),
15385 Conv->getLocation(), Conv->getLocation()));
15386 Conv->markUsed(Context);
15387 Conv->setReferenced();
15388
15389 if (ASTMutationListener *L = getASTMutationListener()) {
15390 L->CompletedImplicitDefinition(Conv);
15391 if (Invoker != CallOp)
15392 L->CompletedImplicitDefinition(Invoker);
15393 }
15394}
15395
15396void Sema::DefineImplicitLambdaToBlockPointerConversion(
15397 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
15398 assert(!Conv->getParent()->isGenericLambda())(static_cast <bool> (!Conv->getParent()->isGenericLambda
()) ? void (0) : __assert_fail ("!Conv->getParent()->isGenericLambda()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15398, __extension__ __PRETTY_FUNCTION__
))
;
15399
15400 SynthesizedFunctionScope Scope(*this, Conv);
15401
15402 // Copy-initialize the lambda object as needed to capture it.
15403 Expr *This = ActOnCXXThis(CurrentLocation).get();
15404 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15405
15406 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15407 Conv->getLocation(),
15408 Conv, DerefThis);
15409
15410 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15411 // behavior. Note that only the general conversion function does this
15412 // (since it's unusable otherwise); in the case where we inline the
15413 // block literal, it has block literal lifetime semantics.
15414 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15415 BuildBlock = ImplicitCastExpr::Create(
15416 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15417 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15418
15419 if (BuildBlock.isInvalid()) {
15420 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15421 Conv->setInvalidDecl();
15422 return;
15423 }
15424
15425 // Create the return statement that returns the block from the conversion
15426 // function.
15427 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15428 if (Return.isInvalid()) {
15429 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15430 Conv->setInvalidDecl();
15431 return;
15432 }
15433
15434 // Set the body of the conversion function.
15435 Stmt *ReturnS = Return.get();
15436 Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(),
15437 Conv->getLocation(), Conv->getLocation()));
15438 Conv->markUsed(Context);
15439
15440 // We're done; notify the mutation listener, if any.
15441 if (ASTMutationListener *L = getASTMutationListener()) {
15442 L->CompletedImplicitDefinition(Conv);
15443 }
15444}
15445
15446/// Determine whether the given list arguments contains exactly one
15447/// "real" (non-default) argument.
15448static bool hasOneRealArgument(MultiExprArg Args) {
15449 switch (Args.size()) {
15450 case 0:
15451 return false;
15452
15453 default:
15454 if (!Args[1]->isDefaultArgument())
15455 return false;
15456
15457 [[fallthrough]];
15458 case 1:
15459 return !Args[0]->isDefaultArgument();
15460 }
15461
15462 return false;
15463}
15464
15465ExprResult
15466Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15467 NamedDecl *FoundDecl,
15468 CXXConstructorDecl *Constructor,
15469 MultiExprArg ExprArgs,
15470 bool HadMultipleCandidates,
15471 bool IsListInitialization,
15472 bool IsStdInitListInitialization,
15473 bool RequiresZeroInit,
15474 unsigned ConstructKind,
15475 SourceRange ParenRange) {
15476 bool Elidable = false;
15477
15478 // C++0x [class.copy]p34:
15479 // When certain criteria are met, an implementation is allowed to
15480 // omit the copy/move construction of a class object, even if the
15481 // copy/move constructor and/or destructor for the object have
15482 // side effects. [...]
15483 // - when a temporary class object that has not been bound to a
15484 // reference (12.2) would be copied/moved to a class object
15485 // with the same cv-unqualified type, the copy/move operation
15486 // can be omitted by constructing the temporary object
15487 // directly into the target of the omitted copy/move
15488 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15489 // FIXME: Converting constructors should also be accepted.
15490 // But to fix this, the logic that digs down into a CXXConstructExpr
15491 // to find the source object needs to handle it.
15492 // Right now it assumes the source object is passed directly as the
15493 // first argument.
15494 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15495 Expr *SubExpr = ExprArgs[0];
15496 // FIXME: Per above, this is also incorrect if we want to accept
15497 // converting constructors, as isTemporaryObject will
15498 // reject temporaries with different type from the
15499 // CXXRecord itself.
15500 Elidable = SubExpr->isTemporaryObject(
15501 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15502 }
15503
15504 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15505 FoundDecl, Constructor,
15506 Elidable, ExprArgs, HadMultipleCandidates,
15507 IsListInitialization,
15508 IsStdInitListInitialization, RequiresZeroInit,
15509 ConstructKind, ParenRange);
15510}
15511
15512ExprResult
15513Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15514 NamedDecl *FoundDecl,
15515 CXXConstructorDecl *Constructor,
15516 bool Elidable,
15517 MultiExprArg ExprArgs,
15518 bool HadMultipleCandidates,
15519 bool IsListInitialization,
15520 bool IsStdInitListInitialization,
15521 bool RequiresZeroInit,
15522 unsigned ConstructKind,
15523 SourceRange ParenRange) {
15524 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15525 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15526 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15527 return ExprError();
15528 }
15529
15530 return BuildCXXConstructExpr(
15531 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15532 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15533 RequiresZeroInit, ConstructKind, ParenRange);
15534}
15535
15536/// BuildCXXConstructExpr - Creates a complete call to a constructor,
15537/// including handling of its default argument expressions.
15538ExprResult
15539Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15540 CXXConstructorDecl *Constructor,
15541 bool Elidable,
15542 MultiExprArg ExprArgs,
15543 bool HadMultipleCandidates,
15544 bool IsListInitialization,
15545 bool IsStdInitListInitialization,
15546 bool RequiresZeroInit,
15547 unsigned ConstructKind,
15548 SourceRange ParenRange) {
15549 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", 15552, __extension__ __PRETTY_FUNCTION__
))
15550 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", 15552, __extension__ __PRETTY_FUNCTION__
))
15551 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", 15552, __extension__ __PRETTY_FUNCTION__
))
15552 "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", 15552, __extension__ __PRETTY_FUNCTION__
))
;
15553 MarkFunctionReferenced(ConstructLoc, Constructor);
15554 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15555 return ExprError();
15556 if (getLangOpts().SYCLIsDevice &&
15557 !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15558 return ExprError();
15559
15560 return CheckForImmediateInvocation(
15561 CXXConstructExpr::Create(
15562 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15563 HadMultipleCandidates, IsListInitialization,
15564 IsStdInitListInitialization, RequiresZeroInit,
15565 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15566 ParenRange),
15567 Constructor);
15568}
15569
15570ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15571 assert(Field->hasInClassInitializer())(static_cast <bool> (Field->hasInClassInitializer())
? void (0) : __assert_fail ("Field->hasInClassInitializer()"
, "clang/lib/Sema/SemaDeclCXX.cpp", 15571, __extension__ __PRETTY_FUNCTION__
))
;
15572
15573 // If we already have the in-class initializer nothing needs to be done.
15574 if (Field->getInClassInitializer())
15575 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15576
15577 // If we might have already tried and failed to instantiate, don't try again.
15578 if (Field->isInvalidDecl())
15579 return ExprError();
15580
15581 // Maybe we haven't instantiated the in-class initializer. Go check the
15582 // pattern FieldDecl to see if it has one.
15583 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15584
15585 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15586 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15587 DeclContext::lookup_result Lookup =
15588 ClassPattern->lookup(Field->getDeclName());
15589
15590 FieldDecl *Pattern = nullptr;
15591 for (auto *L : Lookup) {
15592 if (isa<FieldDecl>(L)) {
15593 Pattern = cast<FieldDecl>(L);
15594 break;
15595 }
15596 }
15597 assert(Pattern && "We must have set the Pattern!")(static_cast <bool> (Pattern && "We must have set the Pattern!"
) ? void (0) : __assert_fail ("Pattern && \"We must have set the Pattern!\""
, "clang/lib/Sema/SemaDeclCXX.cpp", 15597, __extension__ __PRETTY_FUNCTION__
))
;
15598
15599 if (!Pattern->hasInClassInitializer() ||
15600 InstantiateInClassInitializer(Loc, Field, Pattern,
15601 getTemplateInstantiationArgs(Field))) {
15602 // Don't diagnose this again.
15603 Field->setInvalidDecl();
15604 return ExprError();
15605 }
15606 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15607 }
15608
15609 // DR1351:
15610 // If the brace-or-equal-initializer of a non-static data member
15611 // invokes a defaulted default constructor of its class or of an
15612 // enclosing class in a potentially evaluated subexpression, the
15613 // program is ill-formed.
15614 //
15615 // This resolution is unworkable: the exception specification of the
15616 // default constructor can be needed in an unevaluated context, in
15617 // particular, in the operand of a noexcept-expression, and we can be
15618 // unable to compute an exception specification for an enclosed class.
15619 //
15620 // Any attempt to resolve the exception specification of a defaulted default
15621 // constructor before the initializer is lexically complete will ultimately
15622 // come here at which point we can diagnose it.
15623 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15624 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15625 << OutermostClass << Field;
15626 Diag(Field->getEndLoc(),
15627 diag::note_default_member_initializer_not_yet_parsed);
15628 // Recover by marking the field invalid, unless we're in a SFINAE context.
15629 if (!isSFINAEContext())
15630 Field->setInvalidDecl();
15631 return ExprError();
15632}
15633
15634void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15635 if (VD->isInvalidDecl()) return;
15636 // If initializing the variable failed, don't also diagnose problems with
15637 // the destructor, they're likely related.
15638 if (VD->getInit() && VD->getInit()->containsErrors())
15639 return;
15640
15641 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15642 if (ClassDecl->isInvalidDecl()) return;
15643 if (ClassDecl->hasIrrelevantDestructor()) return;
15644 if (ClassDecl->isDependentContext()) return;
15645
15646 if (VD->isNoDestroy(getASTContext()))
15647 return;
15648
15649 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15650
15651 // If this is an array, we'll require the destructor during initialization, so
15652 // we can skip over this. We still want to emit exit-time destructor warnings
15653 // though.
15654 if (!VD->getType()->isArrayType()) {
15655 MarkFunctionReferenced(VD->getLocation(), Destructor);
15656 CheckDestructorAccess(VD->getLocation(), Destructor,
15657 PDiag(diag::err_access_dtor_var)
15658 << VD->getDeclName() << VD->getType());
15659 DiagnoseUseOfDecl(Destructor, VD->getLocation());
15660 }
15661
15662 if (Destructor->isTrivial()) return;
15663
15664 // If the destructor is constexpr, check whether the variable has constant
15665 // destruction now.
15666 if (Destructor->isConstexpr()) {
15667 bool HasConstantInit = false;
15668 if (VD->getInit() && !VD->getInit()->isValueDependent())
15669 HasConstantInit = VD->evaluateValue();
15670 SmallVector<PartialDiagnosticAt, 8> Notes;
15671 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15672 HasConstantInit) {
15673 Diag(VD->getLocation(),
15674 diag::err_constexpr_var_requires_const_destruction) << VD;
15675 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15676 Diag(Notes[I].first, Notes[I].second);
15677 }
15678 }
15679
15680 if (!VD->hasGlobalStorage()) return;
15681
15682 // Emit warning for non-trivial dtor in global scope (a real global,
15683 // class-static, function-static).
15684 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15685
15686 // TODO: this should be re-enabled for static locals by !CXAAtExit
15687 if (!VD->isStaticLocal())
15688 Diag(VD->getLocation(), diag::warn_global_destructor);
15689}
15690
15691/// Given a constructor and the set of arguments provided for the
15692/// constructor, convert the arguments and add any required default arguments
15693/// to form a proper call to this constructor.
15694///
15695/// \returns true if an error occurred, false otherwise.
15696bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15697 QualType DeclInitType, MultiExprArg ArgsPtr,
15698 SourceLocation Loc,
15699 SmallVectorImpl<Expr *> &ConvertedArgs,
15700 bool AllowExplicit,
15701 bool IsListInitialization) {
15702 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15703 unsigned NumArgs = ArgsPtr.size();
15704 Expr **Args = ArgsPtr.data();
15705
15706 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15707 unsigned NumParams = Proto->getNumParams();
15708
15709 // If too few arguments are available, we'll fill in the rest with defaults.
15710 if (NumArgs < NumParams)
15711 ConvertedArgs.reserve(NumParams);
15712 else
15713 ConvertedArgs.reserve(NumArgs);
15714
15715 VariadicCallType CallType =
15716 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15717 SmallVector<Expr *, 8> AllArgs;
15718 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15719 Proto, 0,
15720 llvm::makeArrayRef(Args, NumArgs),
15721 AllArgs,
15722 CallType, AllowExplicit,
15723 IsListInitialization);
15724 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15725
15726 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15727
15728 CheckConstructorCall(Constructor, DeclInitType,
15729 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15730 Proto, Loc);
15731
15732 return Invalid;
15733}
15734
15735static inline bool
15736CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15737 const FunctionDecl *FnDecl) {
15738 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15739 if (isa<NamespaceDecl>(DC)) {
15740 return SemaRef.Diag(FnDecl->getLocation(),
15741 diag::err_operator_new_delete_declared_in_namespace)
15742 << FnDecl->getDeclName();
15743 }
15744
15745 if (isa<TranslationUnitDecl>(DC) &&
15746 FnDecl->getStorageClass() == SC_Static) {
15747 return SemaRef.Diag(FnDecl->getLocation(),
15748 diag::err_operator_new_delete_declared_static)
15749 << FnDecl->getDeclName();
15750 }
15751
15752 return false;
15753}
15754
15755static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15756 const PointerType *PtrTy) {
15757 auto &Ctx = SemaRef.Context;
15758 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15759 PtrQuals.removeAddressSpace();
15760 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15761 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15762}
15763
15764static inline bool
15765CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15766 CanQualType ExpectedResultType,
15767 CanQualType ExpectedFirstParamType,
15768 unsigned DependentParamTypeDiag,
15769 unsigned InvalidParamTypeDiag) {
15770 QualType ResultType =
15771 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15772
15773 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15774 // The operator is valid on any address space for OpenCL.
15775 // Drop address space from actual and expected result types.
15776 if (const auto *PtrTy = ResultType->getAs<PointerType>())
15777 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15778
15779 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15780 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15781 }
15782
15783 // Check that the result type is what we expect.
15784 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15785 // Reject even if the type is dependent; an operator delete function is
15786 // required to have a non-dependent result type.
15787 return SemaRef.Diag(
15788 FnDecl->getLocation(),
15789 ResultType->isDependentType()
15790 ? diag::err_operator_new_delete_dependent_result_type
15791 : diag::err_operator_new_delete_invalid_result_type)
15792 << FnDecl->getDeclName() << ExpectedResultType;
15793 }
15794
15795 // A function template must have at least 2 parameters.
15796 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15797 return SemaRef.Diag(FnDecl->getLocation(),
15798 diag::err_operator_new_delete_template_too_few_parameters)
15799 << FnDecl->getDeclName();
15800
15801 // The function decl must have at least 1 parameter.
15802 if (FnDecl->getNumParams() == 0)
15803 return SemaRef.Diag(FnDecl->getLocation(),
15804 diag::err_operator_new_delete_too_few_parameters)
15805 << FnDecl->getDeclName();
15806
15807 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15808 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15809 // The operator is valid on any address space for OpenCL.
15810 // Drop address space from actual and expected first parameter types.
15811 if (const auto *PtrTy =
15812 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15813 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15814
15815 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15816 ExpectedFirstParamType =
15817 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15818 }
15819
15820 // Check that the first parameter type is what we expect.
15821 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15822 ExpectedFirstParamType) {
15823 // The first parameter type is not allowed to be dependent. As a tentative
15824 // DR resolution, we allow a dependent parameter type if it is the right
15825 // type anyway, to allow destroying operator delete in class templates.
15826 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15827 ? DependentParamTypeDiag
15828 : InvalidParamTypeDiag)
15829 << FnDecl->getDeclName() << ExpectedFirstParamType;
15830 }
15831
15832 return false;
15833}
15834
15835static bool
15836CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15837 // C++ [basic.stc.dynamic.allocation]p1:
15838 // A program is ill-formed if an allocation function is declared in a
15839 // namespace scope other than global scope or declared static in global
15840 // scope.
15841 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15842 return true;
15843
15844 CanQualType SizeTy =
15845 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15846
15847 // C++ [basic.stc.dynamic.allocation]p1:
15848 // The return type shall be void*. The first parameter shall have type
15849 // std::size_t.
15850 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15851 SizeTy,
15852 diag::err_operator_new_dependent_param_type,
15853 diag::err_operator_new_param_type))
15854 return true;
15855
15856 // C++ [basic.stc.dynamic.allocation]p1:
15857 // The first parameter shall not have an associated default argument.
15858 if (FnDecl->getParamDecl(0)->hasDefaultArg())
15859 return SemaRef.Diag(FnDecl->getLocation(),
15860 diag::err_operator_new_default_arg)
15861 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15862
15863 return false;
15864}
15865
15866static bool
15867CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15868 // C++ [basic.stc.dynamic.deallocation]p1:
15869 // A program is ill-formed if deallocation functions are declared in a
15870 // namespace scope other than global scope or declared static in global
15871 // scope.
15872 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15873 return true;
15874
15875 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15876
15877 // C++ P0722:
15878 // Within a class C, the first parameter of a destroying operator delete
15879 // shall be of type C *. The first parameter of any other deallocation
15880 // function shall be of type void *.
15881 CanQualType ExpectedFirstParamType =
15882 MD && MD->isDestroyingOperatorDelete()
15883 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15884 SemaRef.Context.getRecordType(MD->getParent())))
15885 : SemaRef.Context.VoidPtrTy;
15886
15887 // C++ [basic.stc.dynamic.deallocation]p2:
15888 // Each deallocation function shall return void
15889 if (CheckOperatorNewDeleteTypes(
15890 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15891 diag::err_operator_delete_dependent_param_type,
15892 diag::err_operator_delete_param_type))
15893 return true;
15894
15895 // C++ P0722:
15896 // A destroying operator delete shall be a usual deallocation function.
15897 if (MD && !MD->getParent()->isDependentContext() &&
15898 MD->isDestroyingOperatorDelete() &&
15899 !SemaRef.isUsualDeallocationFunction(MD)) {
15900 SemaRef.Diag(MD->getLocation(),
15901 diag::err_destroying_operator_delete_not_usual);
15902 return true;
15903 }
15904
15905 return false;
15906}
15907
15908/// CheckOverloadedOperatorDeclaration - Check whether the declaration
15909/// of this overloaded operator is well-formed. If so, returns false;
15910/// otherwise, emits appropriate diagnostics and returns true.
15911bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15912 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", 15913, __extension__ __PRETTY_FUNCTION__
))
15913 "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", 15913, __extension__ __PRETTY_FUNCTION__
))
;
15914
15915 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15916
15917 // C++ [over.oper]p5:
15918 // The allocation and deallocation functions, operator new,
15919 // operator new[], operator delete and operator delete[], are
15920 // described completely in 3.7.3. The attributes and restrictions
15921 // found in the rest of this subclause do not apply to them unless
15922 // explicitly stated in 3.7.3.
15923 if (Op == OO_Delete || Op == OO_Array_Delete)
15924 return CheckOperatorDeleteDeclaration(*this, FnDecl);
15925
15926 if (Op == OO_New || Op == OO_Array_New)
15927 return CheckOperatorNewDeclaration(*this, FnDecl);
15928
15929 // C++ [over.oper]p7:
15930 // An operator function shall either be a member function or
15931 // be a non-member function and have at least one parameter
15932 // whose type is a class, a reference to a class, an enumeration,
15933 // or a reference to an enumeration.
15934 // Note: Before C++23, a member function could not be static. The only member
15935 // function allowed to be static is the call operator function.
15936 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15937 if (MethodDecl->isStatic()) {
15938 if (Op == OO_Call)
15939 Diag(FnDecl->getLocation(),
15940 (LangOpts.CPlusPlus2b ? diag::ext_operator_overload_static
15941 : diag::err_call_operator_overload_static))
15942 << FnDecl;
15943 else
15944 return Diag(FnDecl->getLocation(), diag::err_operator_overload_static)
15945 << FnDecl;
15946 }
15947 } else {
15948 bool ClassOrEnumParam = false;
15949 for (auto *Param : FnDecl->parameters()) {
15950 QualType ParamType = Param->getType().getNonReferenceType();
15951 if (ParamType->isDependentType() || ParamType->isRecordType() ||
15952 ParamType->isEnumeralType()) {
15953 ClassOrEnumParam = true;
15954 break;
15955 }
15956 }
15957
15958 if (!ClassOrEnumParam)
15959 return Diag(FnDecl->getLocation(),
15960 diag::err_operator_overload_needs_class_or_enum)
15961 << FnDecl->getDeclName();
15962 }
15963
15964 // C++ [over.oper]p8:
15965 // An operator function cannot have default arguments (8.3.6),
15966 // except where explicitly stated below.
15967 //
15968 // Only the function-call operator (C++ [over.call]p1) and the subscript
15969 // operator (CWG2507) allow default arguments.
15970 if (Op != OO_Call) {
15971 ParmVarDecl *FirstDefaultedParam = nullptr;
15972 for (auto *Param : FnDecl->parameters()) {
15973 if (Param->hasDefaultArg()) {
15974 FirstDefaultedParam = Param;
15975 break;
15976 }
15977 }
15978 if (FirstDefaultedParam) {
15979 if (Op == OO_Subscript) {
15980 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15981 ? diag::ext_subscript_overload
15982 : diag::error_subscript_overload)
15983 << FnDecl->getDeclName() << 1
15984 << FirstDefaultedParam->getDefaultArgRange();
15985 } else {
15986 return Diag(FirstDefaultedParam->getLocation(),
15987 diag::err_operator_overload_default_arg)
15988 << FnDecl->getDeclName()
15989 << FirstDefaultedParam->getDefaultArgRange();
15990 }
15991 }
15992 }
15993
15994 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15995 { false, false, false }
15996#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15997 , { Unary, Binary, MemberOnly }
15998#include "clang/Basic/OperatorKinds.def"
15999 };
16000
16001 bool CanBeUnaryOperator = OperatorUses[Op][0];
16002 bool CanBeBinaryOperator = OperatorUses[Op][1];
16003 bool MustBeMemberOperator = OperatorUses[Op][2];
16004
16005 // C++ [over.oper]p8:
16006 // [...] Operator functions cannot have more or fewer parameters
16007 // than the number required for the corresponding operator, as
16008 // described in the rest of this subclause.
16009 unsigned NumParams = FnDecl->getNumParams()
16010 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
16011 if (Op != OO_Call && Op != OO_Subscript &&
16012 ((NumParams == 1 && !CanBeUnaryOperator) ||
16013 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
16014 (NumParams > 2))) {
16015 // We have the wrong number of parameters.
16016 unsigned ErrorKind;
16017 if (CanBeUnaryOperator && CanBeBinaryOperator) {
16018 ErrorKind = 2; // 2 -> unary or binary.
16019 } else if (CanBeUnaryOperator) {
16020 ErrorKind = 0; // 0 -> unary
16021 } else {
16022 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", 16023, __extension__ __PRETTY_FUNCTION__
))
16023 "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", 16023, __extension__ __PRETTY_FUNCTION__
))
;
16024 ErrorKind = 1; // 1 -> binary
16025 }
16026 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
16027 << FnDecl->getDeclName() << NumParams << ErrorKind;
16028 }
16029
16030 if (Op == OO_Subscript && NumParams != 2) {
16031 Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
16032 ? diag::ext_subscript_overload
16033 : diag::error_subscript_overload)
16034 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
16035 }
16036
16037 // Overloaded operators other than operator() and operator[] cannot be
16038 // variadic.
16039 if (Op != OO_Call &&
16040 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16041 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16042 << FnDecl->getDeclName();
16043 }
16044
16045 // Some operators must be member functions.
16046 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16047 return Diag(FnDecl->getLocation(),
16048 diag::err_operator_overload_must_be_member)
16049 << FnDecl->getDeclName();
16050 }
16051
16052 // C++ [over.inc]p1:
16053 // The user-defined function called operator++ implements the
16054 // prefix and postfix ++ operator. If this function is a member
16055 // function with no parameters, or a non-member function with one
16056 // parameter of class or enumeration type, it defines the prefix
16057 // increment operator ++ for objects of that type. If the function
16058 // is a member function with one parameter (which shall be of type
16059 // int) or a non-member function with two parameters (the second
16060 // of which shall be of type int), it defines the postfix
16061 // increment operator ++ for objects of that type.
16062 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16063 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16064 QualType ParamType = LastParam->getType();
16065
16066 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16067 !ParamType->isDependentType())
16068 return Diag(LastParam->getLocation(),
16069 diag::err_operator_overload_post_incdec_must_be_int)
16070 << LastParam->getType() << (Op == OO_MinusMinus);
16071 }
16072
16073 return false;
16074}
16075
16076static bool
16077checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16078 FunctionTemplateDecl *TpDecl) {
16079 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16080
16081 // Must have one or two template parameters.
16082 if (TemplateParams->size() == 1) {
16083 NonTypeTemplateParmDecl *PmDecl =
16084 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16085
16086 // The template parameter must be a char parameter pack.
16087 if (PmDecl && PmDecl->isTemplateParameterPack() &&
16088 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16089 return false;
16090
16091 // C++20 [over.literal]p5:
16092 // A string literal operator template is a literal operator template
16093 // whose template-parameter-list comprises a single non-type
16094 // template-parameter of class type.
16095 //
16096 // As a DR resolution, we also allow placeholders for deduced class
16097 // template specializations.
16098 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16099 !PmDecl->isTemplateParameterPack() &&
16100 (PmDecl->getType()->isRecordType() ||
16101 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16102 return false;
16103 } else if (TemplateParams->size() == 2) {
16104 TemplateTypeParmDecl *PmType =
16105 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16106 NonTypeTemplateParmDecl *PmArgs =
16107 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16108
16109 // The second template parameter must be a parameter pack with the
16110 // first template parameter as its type.
16111 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16112 PmArgs->isTemplateParameterPack()) {
16113 const TemplateTypeParmType *TArgs =
16114 PmArgs->getType()->getAs<TemplateTypeParmType>();
16115 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16116 TArgs->getIndex() == PmType->getIndex()) {
16117 if (!SemaRef.inTemplateInstantiation())
16118 SemaRef.Diag(TpDecl->getLocation(),
16119 diag::ext_string_literal_operator_template);
16120 return false;
16121 }
16122 }
16123 }
16124
16125 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16126 diag::err_literal_operator_template)
16127 << TpDecl->getTemplateParameters()->getSourceRange();
16128 return true;
16129}
16130
16131/// CheckLiteralOperatorDeclaration - Check whether the declaration
16132/// of this literal operator function is well-formed. If so, returns
16133/// false; otherwise, emits appropriate diagnostics and returns true.
16134bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16135 if (isa<CXXMethodDecl>(FnDecl)) {
16136 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16137 << FnDecl->getDeclName();
16138 return true;
16139 }
16140
16141 if (FnDecl->isExternC()) {
16142 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16143 if (const LinkageSpecDecl *LSD =
16144 FnDecl->getDeclContext()->getExternCContext())
16145 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16146 return true;
16147 }
16148
16149 // This might be the definition of a literal operator template.
16150 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16151
16152 // This might be a specialization of a literal operator template.
16153 if (!TpDecl)
16154 TpDecl = FnDecl->getPrimaryTemplate();
16155
16156 // template <char...> type operator "" name() and
16157 // template <class T, T...> type operator "" name() are the only valid
16158 // template signatures, and the only valid signatures with no parameters.
16159 //
16160 // C++20 also allows template <SomeClass T> type operator "" name().
16161 if (TpDecl) {
16162 if (FnDecl->param_size() != 0) {
16163 Diag(FnDecl->getLocation(),
16164 diag::err_literal_operator_template_with_params);
16165 return true;
16166 }
16167
16168 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16169 return true;
16170
16171 } else if (FnDecl->param_size() == 1) {
16172 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16173
16174 QualType ParamType = Param->getType().getUnqualifiedType();
16175
16176 // Only unsigned long long int, long double, any character type, and const
16177 // char * are allowed as the only parameters.
16178 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16179 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16180 Context.hasSameType(ParamType, Context.CharTy) ||
16181 Context.hasSameType(ParamType, Context.WideCharTy) ||
16182 Context.hasSameType(ParamType, Context.Char8Ty) ||
16183 Context.hasSameType(ParamType, Context.Char16Ty) ||
16184 Context.hasSameType(ParamType, Context.Char32Ty)) {
16185 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16186 QualType InnerType = Ptr->getPointeeType();
16187
16188 // Pointer parameter must be a const char *.
16189 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16190 Context.CharTy) &&
16191 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16192 Diag(Param->getSourceRange().getBegin(),
16193 diag::err_literal_operator_param)
16194 << ParamType << "'const char *'" << Param->getSourceRange();
16195 return true;
16196 }
16197
16198 } else if (ParamType->isRealFloatingType()) {
16199 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16200 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16201 return true;
16202
16203 } else if (ParamType->isIntegerType()) {
16204 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16205 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16206 return true;
16207
16208 } else {
16209 Diag(Param->getSourceRange().getBegin(),
16210 diag::err_literal_operator_invalid_param)
16211 << ParamType << Param->getSourceRange();
16212 return true;
16213 }
16214
16215 } else if (FnDecl->param_size() == 2) {
16216 FunctionDecl::param_iterator Param = FnDecl->param_begin();
16217
16218 // First, verify that the first parameter is correct.
16219
16220 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16221
16222 // Two parameter function must have a pointer to const as a
16223 // first parameter; let's strip those qualifiers.
16224 const PointerType *PT = FirstParamType->getAs<PointerType>();
16225
16226 if (!PT) {
16227 Diag((*Param)->getSourceRange().getBegin(),
16228 diag::err_literal_operator_param)
16229 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16230 return true;
16231 }
16232
16233 QualType PointeeType = PT->getPointeeType();
16234 // First parameter must be const
16235 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16236 Diag((*Param)->getSourceRange().getBegin(),
16237 diag::err_literal_operator_param)
16238 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16239 return true;
16240 }
16241
16242 QualType InnerType = PointeeType.getUnqualifiedType();
16243 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16244 // const char32_t* are allowed as the first parameter to a two-parameter
16245 // function
16246 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16247 Context.hasSameType(InnerType, Context.WideCharTy) ||
16248 Context.hasSameType(InnerType, Context.Char8Ty) ||
16249 Context.hasSameType(InnerType, Context.Char16Ty) ||
16250 Context.hasSameType(InnerType, Context.Char32Ty))) {
16251 Diag((*Param)->getSourceRange().getBegin(),
16252 diag::err_literal_operator_param)
16253 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16254 return true;
16255 }
16256
16257 // Move on to the second and final parameter.
16258 ++Param;
16259
16260 // The second parameter must be a std::size_t.
16261 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16262 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16263 Diag((*Param)->getSourceRange().getBegin(),
16264 diag::err_literal_operator_param)
16265 << SecondParamType << Context.getSizeType()
16266 << (*Param)->getSourceRange();
16267 return true;
16268 }
16269 } else {
16270 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16271 return true;
16272 }
16273
16274 // Parameters are good.
16275
16276 // A parameter-declaration-clause containing a default argument is not
16277 // equivalent to any of the permitted forms.
16278 for (auto *Param : FnDecl->parameters()) {
16279 if (Param->hasDefaultArg()) {
16280 Diag(Param->getDefaultArgRange().getBegin(),
16281 diag::err_literal_operator_default_argument)
16282 << Param->getDefaultArgRange();
16283 break;
16284 }
16285 }
16286
16287 StringRef LiteralName
16288 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
16289 if (LiteralName[0] != '_' &&
16290 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16291 // C++11 [usrlit.suffix]p1:
16292 // Literal suffix identifiers that do not start with an underscore
16293 // are reserved for future standardization.
16294 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16295 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
16296 }
16297
16298 return false;
16299}
16300
16301/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16302/// linkage specification, including the language and (if present)
16303/// the '{'. ExternLoc is the location of the 'extern', Lang is the
16304/// language string literal. LBraceLoc, if valid, provides the location of
16305/// the '{' brace. Otherwise, this linkage specification does not
16306/// have any braces.
16307Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16308 Expr *LangStr,
16309 SourceLocation LBraceLoc) {
16310 StringLiteral *Lit = cast<StringLiteral>(LangStr);
16311 if (!Lit->isOrdinary()) {
16312 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16313 << LangStr->getSourceRange();
16314 return nullptr;
16315 }
16316
16317 StringRef Lang = Lit->getString();
16318 LinkageSpecDecl::LanguageIDs Language;
16319 if (Lang == "C")
16320 Language = LinkageSpecDecl::lang_c;
16321 else if (Lang == "C++")
16322 Language = LinkageSpecDecl::lang_cxx;
16323 else {
16324 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16325 << LangStr->getSourceRange();
16326 return nullptr;
16327 }
16328
16329 // FIXME: Add all the various semantics of linkage specifications
16330
16331 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16332 LangStr->getExprLoc(), Language,
16333 LBraceLoc.isValid());
16334
16335 /// C++ [module.unit]p7.2.3
16336 /// - Otherwise, if the declaration
16337 /// - ...
16338 /// - ...
16339 /// - appears within a linkage-specification,
16340 /// it is attached to the global module.
16341 ///
16342 /// If the declaration is already in global module fragment, we don't
16343 /// need to attach it again.
16344 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16345 Module *GlobalModule =
16346 PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true);
16347 /// According to [module.reach]p3.2,
16348 /// The declaration in global module fragment is reachable if it is not
16349 /// discarded. And the discarded declaration should be deleted. So it
16350 /// doesn't matter mark the declaration in global module fragment as
16351 /// reachable here.
16352 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
16353 D->setLocalOwningModule(GlobalModule);
16354 }
16355
16356 CurContext->addDecl(D);
16357 PushDeclContext(S, D);
16358 return D;
16359}
16360
16361/// ActOnFinishLinkageSpecification - Complete the definition of
16362/// the C++ linkage specification LinkageSpec. If RBraceLoc is
16363/// valid, it's the position of the closing '}' brace in a linkage
16364/// specification that uses braces.
16365Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16366 Decl *LinkageSpec,
16367 SourceLocation RBraceLoc) {
16368 if (RBraceLoc.isValid()) {
16369 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16370 LSDecl->setRBraceLoc(RBraceLoc);
16371 }
16372
16373 // If the current module doesn't has Parent, it implies that the
16374 // LinkageSpec isn't in the module created by itself. So we don't
16375 // need to pop it.
16376 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16377 getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent)
16378 PopGlobalModuleFragment();
16379
16380 PopDeclContext();
16381 return LinkageSpec;
16382}
16383
16384Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16385 const ParsedAttributesView &AttrList,
16386 SourceLocation SemiLoc) {
16387 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16388 // Attribute declarations appertain to empty declaration so we handle
16389 // them here.
16390 ProcessDeclAttributeList(S, ED, AttrList);
16391
16392 CurContext->addDecl(ED);
16393 return ED;
16394}
16395
16396/// Perform semantic analysis for the variable declaration that
16397/// occurs within a C++ catch clause, returning the newly-created
16398/// variable.
16399VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16400 TypeSourceInfo *TInfo,
16401 SourceLocation StartLoc,
16402 SourceLocation Loc,
16403 IdentifierInfo *Name) {
16404 bool Invalid = false;
16405 QualType ExDeclType = TInfo->getType();
16406
16407 // Arrays and functions decay.
16408 if (ExDeclType->isArrayType())
16409 ExDeclType = Context.getArrayDecayedType(ExDeclType);
16410 else if (ExDeclType->isFunctionType())
16411 ExDeclType = Context.getPointerType(ExDeclType);
16412
16413 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16414 // The exception-declaration shall not denote a pointer or reference to an
16415 // incomplete type, other than [cv] void*.
16416 // N2844 forbids rvalue references.
16417 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16418 Diag(Loc, diag::err_catch_rvalue_ref);
16419 Invalid = true;
16420 }
16421
16422 if (ExDeclType->isVariablyModifiedType()) {
16423 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16424 Invalid = true;
16425 }
16426
16427 QualType BaseType = ExDeclType;
16428 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16429 unsigned DK = diag::err_catch_incomplete;
16430 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16431 BaseType = Ptr->getPointeeType();
16432 Mode = 1;
16433 DK = diag::err_catch_incomplete_ptr;
16434 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16435 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16436 BaseType = Ref->getPointeeType();
16437 Mode = 2;
16438 DK = diag::err_catch_incomplete_ref;
16439 }
16440 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16441 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16442 Invalid = true;
16443
16444 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16445 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16446 Invalid = true;
16447 }
16448
16449 if (!Invalid && !ExDeclType->isDependentType() &&
16450 RequireNonAbstractType(Loc, ExDeclType,
16451 diag::err_abstract_type_in_decl,
16452 AbstractVariableType))
16453 Invalid = true;
16454
16455 // Only the non-fragile NeXT runtime currently supports C++ catches
16456 // of ObjC types, and no runtime supports catching ObjC types by value.
16457 if (!Invalid && getLangOpts().ObjC) {
16458 QualType T = ExDeclType;
16459 if (const ReferenceType *RT = T->getAs<ReferenceType>())
16460 T = RT->getPointeeType();
16461
16462 if (T->isObjCObjectType()) {
16463 Diag(Loc, diag::err_objc_object_catch);
16464 Invalid = true;
16465 } else if (T->isObjCObjectPointerType()) {
16466 // FIXME: should this be a test for macosx-fragile specifically?
16467 if (getLangOpts().ObjCRuntime.isFragile())
16468 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16469 }
16470 }
16471
16472 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16473 ExDeclType, TInfo, SC_None);
16474 ExDecl->setExceptionVariable(true);
16475
16476 // In ARC, infer 'retaining' for variables of retainable type.
16477 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16478 Invalid = true;
16479
16480 if (!Invalid && !ExDeclType->isDependentType()) {
16481 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16482 // Insulate this from anything else we might currently be parsing.
16483 EnterExpressionEvaluationContext scope(
16484 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16485
16486 // C++ [except.handle]p16:
16487 // The object declared in an exception-declaration or, if the
16488 // exception-declaration does not specify a name, a temporary (12.2) is
16489 // copy-initialized (8.5) from the exception object. [...]
16490 // The object is destroyed when the handler exits, after the destruction
16491 // of any automatic objects initialized within the handler.
16492 //
16493 // We just pretend to initialize the object with itself, then make sure
16494 // it can be destroyed later.
16495 QualType initType = Context.getExceptionObjectType(ExDeclType);
16496
16497 InitializedEntity entity =
16498 InitializedEntity::InitializeVariable(ExDecl);
16499 InitializationKind initKind =
16500 InitializationKind::CreateCopy(Loc, SourceLocation());
16501
16502 Expr *opaqueValue =
16503 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16504 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16505 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16506 if (result.isInvalid())
16507 Invalid = true;
16508 else {
16509 // If the constructor used was non-trivial, set this as the
16510 // "initializer".
16511 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16512 if (!construct->getConstructor()->isTrivial()) {
16513 Expr *init = MaybeCreateExprWithCleanups(construct);
16514 ExDecl->setInit(init);
16515 }
16516
16517 // And make sure it's destructable.
16518 FinalizeVarWithDestructor(ExDecl, recordType);
16519 }
16520 }
16521 }
16522
16523 if (Invalid)
16524 ExDecl->setInvalidDecl();
16525
16526 return ExDecl;
16527}
16528
16529/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16530/// handler.
16531Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16532 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16533 bool Invalid = D.isInvalidType();
16534
16535 // Check for unexpanded parameter packs.
16536 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16537 UPPC_ExceptionType)) {
16538 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16539 D.getIdentifierLoc());
16540 Invalid = true;
16541 }
16542
16543 IdentifierInfo *II = D.getIdentifier();
16544 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16545 LookupOrdinaryName,
16546 ForVisibleRedeclaration)) {
16547 // The scope should be freshly made just for us. There is just no way
16548 // it contains any previous declaration, except for function parameters in
16549 // a function-try-block's catch statement.
16550 assert(!S->isDeclScope(PrevDecl))(static_cast <bool> (!S->isDeclScope(PrevDecl)) ? void
(0) : __assert_fail ("!S->isDeclScope(PrevDecl)", "clang/lib/Sema/SemaDeclCXX.cpp"
, 16550, __extension__ __PRETTY_FUNCTION__))
;
16551 if (isDeclInScope(PrevDecl, CurContext, S)) {
16552 Diag(D.getIdentifierLoc(), diag::err_redefinition)
16553 << D.getIdentifier();
16554 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16555 Invalid = true;
16556 } else if (PrevDecl->isTemplateParameter())
16557 // Maybe we will complain about the shadowed template parameter.
16558 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16559 }
16560
16561 if (D.getCXXScopeSpec().isSet() && !Invalid) {
16562 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16563 << D.getCXXScopeSpec().getRange();
16564 Invalid = true;
16565 }
16566
16567 VarDecl *ExDecl = BuildExceptionDeclaration(
16568 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16569 if (Invalid)
16570 ExDecl->setInvalidDecl();
16571
16572 // Add the exception declaration into this scope.
16573 if (II)
16574 PushOnScopeChains(ExDecl, S);
16575 else
16576 CurContext->addDecl(ExDecl);
16577
16578 ProcessDeclAttributes(S, ExDecl, D);
16579 return ExDecl;
16580}
16581
16582Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16583 Expr *AssertExpr,
16584 Expr *AssertMessageExpr,
16585 SourceLocation RParenLoc) {
16586 StringLiteral *AssertMessage =
16587 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16588
16589 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16590 return nullptr;
16591
16592 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16593 AssertMessage, RParenLoc, false);
16594}
16595
16596/// Convert \V to a string we can present to the user in a diagnostic
16597/// \T is the type of the expression that has been evaluated into \V
16598static bool ConvertAPValueToString(const APValue &V, QualType T,
16599 SmallVectorImpl<char> &Str) {
16600 if (!V.hasValue())
16601 return false;
16602
16603 switch (V.getKind()) {
16604 case APValue::ValueKind::Int:
16605 if (T->isBooleanType()) {
16606 // Bools are reduced to ints during evaluation, but for
16607 // diagnostic purposes we want to print them as
16608 // true or false.
16609 int64_t BoolValue = V.getInt().getExtValue();
16610 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", 16611, __extension__ __PRETTY_FUNCTION__
))
16611 "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", 16611, __extension__ __PRETTY_FUNCTION__
))
;
16612 llvm::raw_svector_ostream OS(Str);
16613 OS << (BoolValue ? "true" : "false");
16614 } else if (T->isCharType()) {
16615 // Same is true for chars.
16616 Str.push_back('\'');
16617 Str.push_back(V.getInt().getExtValue());
16618 Str.push_back('\'');
16619 } else
16620 V.getInt().toString(Str);
16621
16622 break;
16623
16624 case APValue::ValueKind::Float:
16625 V.getFloat().toString(Str);
16626 break;
16627
16628 case APValue::ValueKind::LValue:
16629 if (V.isNullPointer()) {
16630 llvm::raw_svector_ostream OS(Str);
16631 OS << "nullptr";
16632 } else
16633 return false;
16634 break;
16635
16636 case APValue::ValueKind::ComplexFloat: {
16637 llvm::raw_svector_ostream OS(Str);
16638 OS << '(';
16639 V.getComplexFloatReal().toString(Str);
16640 OS << " + ";
16641 V.getComplexFloatImag().toString(Str);
16642 OS << "i)";
16643 } break;
16644
16645 case APValue::ValueKind::ComplexInt: {
16646 llvm::raw_svector_ostream OS(Str);
16647 OS << '(';
16648 V.getComplexIntReal().toString(Str);
16649 OS << " + ";
16650 V.getComplexIntImag().toString(Str);
16651 OS << "i)";
16652 } break;
16653
16654 default:
16655 return false;
16656 }
16657
16658 return true;
16659}
16660
16661/// Some Expression types are not useful to print notes about,
16662/// e.g. literals and values that have already been expanded
16663/// before such as int-valued template parameters.
16664static bool UsefulToPrintExpr(const Expr *E) {
16665 E = E->IgnoreParenImpCasts();
16666 // Literals are pretty easy for humans to understand.
16667 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
16668 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(E))
16669 return false;
16670
16671 // These have been substituted from template parameters
16672 // and appear as literals in the static assert error.
16673 if (isa<SubstNonTypeTemplateParmExpr>(E))
16674 return false;
16675
16676 // -5 is also simple to understand.
16677 if (const auto *UnaryOp = dyn_cast_or_null<UnaryOperator>(E))
16678 return UsefulToPrintExpr(UnaryOp->getSubExpr());
16679
16680 // Ignore nested binary operators. This could be a FIXME for improvements
16681 // to the diagnostics in the future.
16682 if (isa<BinaryOperator>(E))
16683 return false;
16684
16685 return true;
16686}
16687
16688/// Try to print more useful information about a failed static_assert
16689/// with expression \E
16690void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
16691 if (const auto *Op = dyn_cast_or_null<BinaryOperator>(E)) {
16692 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
16693 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
16694
16695 // Ignore comparisons of boolean expressions with a boolean literal.
16696 if ((isa<CXXBoolLiteralExpr>(LHS) && RHS->getType()->isBooleanType()) ||
16697 (isa<CXXBoolLiteralExpr>(RHS) && LHS->getType()->isBooleanType()))
16698 return;
16699
16700 // Don't print obvious expressions.
16701 if (!UsefulToPrintExpr(LHS) && !UsefulToPrintExpr(RHS))
16702 return;
16703
16704 struct {
16705 const clang::Expr *Cond;
16706 Expr::EvalResult Result;
16707 SmallString<12> ValueString;
16708 bool Print;
16709 } DiagSide[2] = {{LHS, Expr::EvalResult(), {}, false},
16710 {RHS, Expr::EvalResult(), {}, false}};
16711 for (unsigned I = 0; I < 2; I++) {
16712 const Expr *Side = DiagSide[I].Cond;
16713
16714 Side->EvaluateAsRValue(DiagSide[I].Result, Context, true);
16715
16716 DiagSide[I].Print = ConvertAPValueToString(
16717 DiagSide[I].Result.Val, Side->getType(), DiagSide[I].ValueString);
16718 }
16719 if (DiagSide[0].Print && DiagSide[1].Print) {
16720 Diag(Op->getExprLoc(), diag::note_expr_evaluates_to)
16721 << DiagSide[0].ValueString << Op->getOpcodeStr()
16722 << DiagSide[1].ValueString << Op->getSourceRange();
16723 }
16724 }
16725}
16726
16727Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16728 Expr *AssertExpr,
16729 StringLiteral *AssertMessage,
16730 SourceLocation RParenLoc,
16731 bool Failed) {
16732 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", 16732, __extension__ __PRETTY_FUNCTION__
))
;
16733 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16734 !Failed) {
16735 // In a static_assert-declaration, the constant-expression shall be a
16736 // constant expression that can be contextually converted to bool.
16737 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16738 if (Converted.isInvalid())
16739 Failed = true;
16740
16741 ExprResult FullAssertExpr =
16742 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16743 /*DiscardedValue*/ false,
16744 /*IsConstexpr*/ true);
16745 if (FullAssertExpr.isInvalid())
16746 Failed = true;
16747 else
16748 AssertExpr = FullAssertExpr.get();
16749
16750 llvm::APSInt Cond;
16751 Expr *BaseExpr = AssertExpr;
16752 AllowFoldKind FoldKind = NoFold;
16753
16754 if (!getLangOpts().CPlusPlus) {
16755 // In C mode only allow folding and strip the implicit conversion
16756 // to the type of the first _Static_assert argument that would
16757 // otherwise suppress diagnostics for arguments that convert to int.
16758 FoldKind = AllowFold;
16759 BaseExpr = BaseExpr->IgnoreImpCasts();
16760 }
16761
16762 if (!Failed && VerifyIntegerConstantExpression(
16763 BaseExpr, &Cond,
16764 diag::err_static_assert_expression_is_not_constant,
16765 FoldKind).isInvalid())
16766 Failed = true;
16767
16768 if (!Failed && !Cond) {
16769 SmallString<256> MsgBuffer;
16770 llvm::raw_svector_ostream Msg(MsgBuffer);
16771 if (AssertMessage) {
16772 const auto *MsgStr = cast<StringLiteral>(AssertMessage);
16773 if (MsgStr->isOrdinary())
16774 Msg << MsgStr->getString();
16775 else
16776 MsgStr->printPretty(Msg, nullptr, getPrintingPolicy());
16777 }
16778
16779 Expr *InnerCond = nullptr;
16780 std::string InnerCondDescription;
16781 std::tie(InnerCond, InnerCondDescription) =
16782 findFailedBooleanCondition(Converted.get());
16783 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16784 // Drill down into concept specialization expressions to see why they
16785 // weren't satisfied.
16786 Diag(StaticAssertLoc, diag::err_static_assert_failed)
16787 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16788 ConstraintSatisfaction Satisfaction;
16789 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16790 DiagnoseUnsatisfiedConstraint(Satisfaction);
16791 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16792 && !isa<IntegerLiteral>(InnerCond)) {
16793 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16794 << InnerCondDescription << !AssertMessage
16795 << Msg.str() << InnerCond->getSourceRange();
16796 DiagnoseStaticAssertDetails(InnerCond);
16797 } else {
16798 Diag(StaticAssertLoc, diag::err_static_assert_failed)
16799 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16800 }
16801 Failed = true;
16802 }
16803 } else {
16804 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16805 /*DiscardedValue*/false,
16806 /*IsConstexpr*/true);
16807 if (FullAssertExpr.isInvalid())
16808 Failed = true;
16809 else
16810 AssertExpr = FullAssertExpr.get();
16811 }
16812
16813 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16814 AssertExpr, AssertMessage, RParenLoc,
16815 Failed);
16816
16817 CurContext->addDecl(Decl);
16818 return Decl;
16819}
16820
16821/// Perform semantic analysis of the given friend type declaration.
16822///
16823/// \returns A friend declaration that.
16824FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16825 SourceLocation FriendLoc,
16826 TypeSourceInfo *TSInfo) {
16827 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", 16827, __extension__ __PRETTY_FUNCTION__
))
;
16828
16829 QualType T = TSInfo->getType();
16830 SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
16831
16832 // C++03 [class.friend]p2:
16833 // An elaborated-type-specifier shall be used in a friend declaration
16834 // for a class.*
16835 //
16836 // * The class-key of the elaborated-type-specifier is required.
16837 if (!CodeSynthesisContexts.empty()) {
16838 // Do not complain about the form of friend template types during any kind
16839 // of code synthesis. For template instantiation, we will have complained
16840 // when the template was defined.
16841 } else {
16842 if (!T->isElaboratedTypeSpecifier()) {
16843 // If we evaluated the type to a record type, suggest putting
16844 // a tag in front.
16845 if (const RecordType *RT = T->getAs<RecordType>()) {
16846 RecordDecl *RD = RT->getDecl();
16847
16848 SmallString<16> InsertionText(" ");
16849 InsertionText += RD->getKindName();
16850
16851 Diag(TypeRange.getBegin(),
16852 getLangOpts().CPlusPlus11 ?
16853 diag::warn_cxx98_compat_unelaborated_friend_type :
16854 diag::ext_unelaborated_friend_type)
16855 << (unsigned) RD->getTagKind()
16856 << T
16857 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16858 InsertionText);
16859 } else {
16860 Diag(FriendLoc,
16861 getLangOpts().CPlusPlus11 ?
16862 diag::warn_cxx98_compat_nonclass_type_friend :
16863 diag::ext_nonclass_type_friend)
16864 << T
16865 << TypeRange;
16866 }
16867 } else if (T->getAs<EnumType>()) {
16868 Diag(FriendLoc,
16869 getLangOpts().CPlusPlus11 ?
16870 diag::warn_cxx98_compat_enum_friend :
16871 diag::ext_enum_friend)
16872 << T
16873 << TypeRange;
16874 }
16875
16876 // C++11 [class.friend]p3:
16877 // A friend declaration that does not declare a function shall have one
16878 // of the following forms:
16879 // friend elaborated-type-specifier ;
16880 // friend simple-type-specifier ;
16881 // friend typename-specifier ;
16882 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16883 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16884 }
16885
16886 // If the type specifier in a friend declaration designates a (possibly
16887 // cv-qualified) class type, that class is declared as a friend; otherwise,
16888 // the friend declaration is ignored.
16889 return FriendDecl::Create(Context, CurContext,
16890 TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16891 FriendLoc);
16892}
16893
16894/// Handle a friend tag declaration where the scope specifier was
16895/// templated.
16896Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16897 unsigned TagSpec, SourceLocation TagLoc,
16898 CXXScopeSpec &SS, IdentifierInfo *Name,
16899 SourceLocation NameLoc,
16900 const ParsedAttributesView &Attr,
16901 MultiTemplateParamsArg TempParamLists) {
16902 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16903
16904 bool IsMemberSpecialization = false;
16905 bool Invalid = false;
16906
16907 if (TemplateParameterList *TemplateParams =
16908 MatchTemplateParametersToScopeSpecifier(
16909 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16910 IsMemberSpecialization, Invalid)) {
16911 if (TemplateParams->size() > 0) {
16912 // This is a declaration of a class template.
16913 if (Invalid)
16914 return nullptr;
16915
16916 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16917 NameLoc, Attr, TemplateParams, AS_public,
16918 /*ModulePrivateLoc=*/SourceLocation(),
16919 FriendLoc, TempParamLists.size() - 1,
16920 TempParamLists.data()).get();
16921 } else {
16922 // The "template<>" header is extraneous.
16923 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16924 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16925 IsMemberSpecialization = true;
16926 }
16927 }
16928
16929 if (Invalid) return nullptr;
16930
16931 bool isAllExplicitSpecializations = true;
16932 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16933 if (TempParamLists[I]->size()) {
16934 isAllExplicitSpecializations = false;
16935 break;
16936 }
16937 }
16938
16939 // FIXME: don't ignore attributes.
16940
16941 // If it's explicit specializations all the way down, just forget
16942 // about the template header and build an appropriate non-templated
16943 // friend. TODO: for source fidelity, remember the headers.
16944 if (isAllExplicitSpecializations) {
16945 if (SS.isEmpty()) {
16946 bool Owned = false;
16947 bool IsDependent = false;
16948 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16949 Attr, AS_public,
16950 /*ModulePrivateLoc=*/SourceLocation(),
16951 MultiTemplateParamsArg(), Owned, IsDependent,
16952 /*ScopedEnumKWLoc=*/SourceLocation(),
16953 /*ScopedEnumUsesClassTag=*/false,
16954 /*UnderlyingType=*/TypeResult(),
16955 /*IsTypeSpecifier=*/false,
16956 /*IsTemplateParamOrArg=*/false);
16957 }
16958
16959 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16960 ElaboratedTypeKeyword Keyword
16961 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16962 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16963 *Name, NameLoc);
16964 if (T.isNull())
16965 return nullptr;
16966
16967 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16968 if (isa<DependentNameType>(T)) {
16969 DependentNameTypeLoc TL =
16970 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16971 TL.setElaboratedKeywordLoc(TagLoc);
16972 TL.setQualifierLoc(QualifierLoc);
16973 TL.setNameLoc(NameLoc);
16974 } else {
16975 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16976 TL.setElaboratedKeywordLoc(TagLoc);
16977 TL.setQualifierLoc(QualifierLoc);
16978 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16979 }
16980
16981 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16982 TSI, FriendLoc, TempParamLists);
16983 Friend->setAccess(AS_public);
16984 CurContext->addDecl(Friend);
16985 return Friend;
16986 }
16987
16988 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", 16988, __extension__ __PRETTY_FUNCTION__
))
;
16989
16990
16991
16992 // Handle the case of a templated-scope friend class. e.g.
16993 // template <class T> class A<T>::B;
16994 // FIXME: we don't support these right now.
16995 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16996 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16997 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16998 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16999 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
17000 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
17001 TL.setElaboratedKeywordLoc(TagLoc);
17002 TL.setQualifierLoc(SS.getWithLocInContext(Context));
17003 TL.setNameLoc(NameLoc);
17004
17005 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
17006 TSI, FriendLoc, TempParamLists);
17007 Friend->setAccess(AS_public);
17008 Friend->setUnsupportedFriend(true);
17009 CurContext->addDecl(Friend);
17010 return Friend;
17011}
17012
17013/// Handle a friend type declaration. This works in tandem with
17014/// ActOnTag.
17015///
17016/// Notes on friend class templates:
17017///
17018/// We generally treat friend class declarations as if they were
17019/// declaring a class. So, for example, the elaborated type specifier
17020/// in a friend declaration is required to obey the restrictions of a
17021/// class-head (i.e. no typedefs in the scope chain), template
17022/// parameters are required to match up with simple template-ids, &c.
17023/// However, unlike when declaring a template specialization, it's
17024/// okay to refer to a template specialization without an empty
17025/// template parameter declaration, e.g.
17026/// friend class A<T>::B<unsigned>;
17027/// We permit this as a special case; if there are any template
17028/// parameters present at all, require proper matching, i.e.
17029/// template <> template \<class T> friend class A<int>::B;
17030Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
17031 MultiTemplateParamsArg TempParams) {
17032 SourceLocation Loc = DS.getBeginLoc();
17033
17034 assert(DS.isFriendSpecified())(static_cast <bool> (DS.isFriendSpecified()) ? void (0)
: __assert_fail ("DS.isFriendSpecified()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 17034, __extension__ __PRETTY_FUNCTION__))
;
17035 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", 17035, __extension__ __PRETTY_FUNCTION__
))
;
17036
17037 // C++ [class.friend]p3:
17038 // A friend declaration that does not declare a function shall have one of
17039 // the following forms:
17040 // friend elaborated-type-specifier ;
17041 // friend simple-type-specifier ;
17042 // friend typename-specifier ;
17043 //
17044 // Any declaration with a type qualifier does not have that form. (It's
17045 // legal to specify a qualified type as a friend, you just can't write the
17046 // keywords.)
17047 if (DS.getTypeQualifiers()) {
17048 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
17049 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
17050 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
17051 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
17052 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
17053 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
17054 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
17055 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
17056 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
17057 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
17058 }
17059
17060 // Try to convert the decl specifier to a type. This works for
17061 // friend templates because ActOnTag never produces a ClassTemplateDecl
17062 // for a TUK_Friend.
17063 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
17064 DeclaratorContext::Member);
17065 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
17066 QualType T = TSI->getType();
17067 if (TheDeclarator.isInvalidType())
17068 return nullptr;
17069
17070 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
17071 return nullptr;
17072
17073 // This is definitely an error in C++98. It's probably meant to
17074 // be forbidden in C++0x, too, but the specification is just
17075 // poorly written.
17076 //
17077 // The problem is with declarations like the following:
17078 // template <T> friend A<T>::foo;
17079 // where deciding whether a class C is a friend or not now hinges
17080 // on whether there exists an instantiation of A that causes
17081 // 'foo' to equal C. There are restrictions on class-heads
17082 // (which we declare (by fiat) elaborated friend declarations to
17083 // be) that makes this tractable.
17084 //
17085 // FIXME: handle "template <> friend class A<T>;", which
17086 // is possibly well-formed? Who even knows?
17087 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
17088 Diag(Loc, diag::err_tagless_friend_type_template)
17089 << DS.getSourceRange();
17090 return nullptr;
17091 }
17092
17093 // C++98 [class.friend]p1: A friend of a class is a function
17094 // or class that is not a member of the class . . .
17095 // This is fixed in DR77, which just barely didn't make the C++03
17096 // deadline. It's also a very silly restriction that seriously
17097 // affects inner classes and which nobody else seems to implement;
17098 // thus we never diagnose it, not even in -pedantic.
17099 //
17100 // But note that we could warn about it: it's always useless to
17101 // friend one of your own members (it's not, however, worthless to
17102 // friend a member of an arbitrary specialization of your template).
17103
17104 Decl *D;
17105 if (!TempParams.empty())
17106 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
17107 TempParams,
17108 TSI,
17109 DS.getFriendSpecLoc());
17110 else
17111 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
17112
17113 if (!D)
17114 return nullptr;
17115
17116 D->setAccess(AS_public);
17117 CurContext->addDecl(D);
17118
17119 return D;
17120}
17121
17122NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
17123 MultiTemplateParamsArg TemplateParams) {
17124 const DeclSpec &DS = D.getDeclSpec();
17125
17126 assert(DS.isFriendSpecified())(static_cast <bool> (DS.isFriendSpecified()) ? void (0)
: __assert_fail ("DS.isFriendSpecified()", "clang/lib/Sema/SemaDeclCXX.cpp"
, 17126, __extension__ __PRETTY_FUNCTION__))
;
17127 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", 17127, __extension__ __PRETTY_FUNCTION__
))
;
17128
17129 SourceLocation Loc = D.getIdentifierLoc();
17130 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17131
17132 // C++ [class.friend]p1
17133 // A friend of a class is a function or class....
17134 // Note that this sees through typedefs, which is intended.
17135 // It *doesn't* see through dependent types, which is correct
17136 // according to [temp.arg.type]p3:
17137 // If a declaration acquires a function type through a
17138 // type dependent on a template-parameter and this causes
17139 // a declaration that does not use the syntactic form of a
17140 // function declarator to have a function type, the program
17141 // is ill-formed.
17142 if (!TInfo->getType()->isFunctionType()) {
17143 Diag(Loc, diag::err_unexpected_friend);
17144
17145 // It might be worthwhile to try to recover by creating an
17146 // appropriate declaration.
17147 return nullptr;
17148 }
17149
17150 // C++ [namespace.memdef]p3
17151 // - If a friend declaration in a non-local class first declares a
17152 // class or function, the friend class or function is a member
17153 // of the innermost enclosing namespace.
17154 // - The name of the friend is not found by simple name lookup
17155 // until a matching declaration is provided in that namespace
17156 // scope (either before or after the class declaration granting
17157 // friendship).
17158 // - If a friend function is called, its name may be found by the
17159 // name lookup that considers functions from namespaces and
17160 // classes associated with the types of the function arguments.
17161 // - When looking for a prior declaration of a class or a function
17162 // declared as a friend, scopes outside the innermost enclosing
17163 // namespace scope are not considered.
17164
17165 CXXScopeSpec &SS = D.getCXXScopeSpec();
17166 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
17167 assert(NameInfo.getName())(static_cast <bool> (NameInfo.getName()) ? void (0) : __assert_fail
("NameInfo.getName()", "clang/lib/Sema/SemaDeclCXX.cpp", 17167
, __extension__ __PRETTY_FUNCTION__))
;
17168
17169 // Check for unexpanded parameter packs.
17170 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
17171 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
17172 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
17173 return nullptr;
17174
17175 // The context we found the declaration in, or in which we should
17176 // create the declaration.
17177 DeclContext *DC;
17178 Scope *DCScope = S;
17179 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
17180 ForExternalRedeclaration);
17181
17182 // There are five cases here.
17183 // - There's no scope specifier and we're in a local class. Only look
17184 // for functions declared in the immediately-enclosing block scope.
17185 // We recover from invalid scope qualifiers as if they just weren't there.
17186 FunctionDecl *FunctionContainingLocalClass = nullptr;
17187 if ((SS.isInvalid() || !SS.isSet()) &&
17188 (FunctionContainingLocalClass =
17189 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17190 // C++11 [class.friend]p11:
17191 // If a friend declaration appears in a local class and the name
17192 // specified is an unqualified name, a prior declaration is
17193 // looked up without considering scopes that are outside the
17194 // innermost enclosing non-class scope. For a friend function
17195 // declaration, if there is no prior declaration, the program is
17196 // ill-formed.
17197
17198 // Find the innermost enclosing non-class scope. This is the block
17199 // scope containing the local class definition (or for a nested class,
17200 // the outer local class).
17201 DCScope = S->getFnParent();
17202
17203 // Look up the function name in the scope.
17204 Previous.clear(LookupLocalFriendName);
17205 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17206
17207 if (!Previous.empty()) {
17208 // All possible previous declarations must have the same context:
17209 // either they were declared at block scope or they are members of
17210 // one of the enclosing local classes.
17211 DC = Previous.getRepresentativeDecl()->getDeclContext();
17212 } else {
17213 // This is ill-formed, but provide the context that we would have
17214 // declared the function in, if we were permitted to, for error recovery.
17215 DC = FunctionContainingLocalClass;
17216 }
17217 adjustContextForLocalExternDecl(DC);
17218
17219 // C++ [class.friend]p6:
17220 // A function can be defined in a friend declaration of a class if and
17221 // only if the class is a non-local class (9.8), the function name is
17222 // unqualified, and the function has namespace scope.
17223 if (D.isFunctionDefinition()) {
17224 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17225 }
17226
17227 // - There's no scope specifier, in which case we just go to the
17228 // appropriate scope and look for a function or function template
17229 // there as appropriate.
17230 } else if (SS.isInvalid() || !SS.isSet()) {
17231 // C++11 [namespace.memdef]p3:
17232 // If the name in a friend declaration is neither qualified nor
17233 // a template-id and the declaration is a function or an
17234 // elaborated-type-specifier, the lookup to determine whether
17235 // the entity has been previously declared shall not consider
17236 // any scopes outside the innermost enclosing namespace.
17237 bool isTemplateId =
17238 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17239
17240 // Find the appropriate context according to the above.
17241 DC = CurContext;
17242
17243 // Skip class contexts. If someone can cite chapter and verse
17244 // for this behavior, that would be nice --- it's what GCC and
17245 // EDG do, and it seems like a reasonable intent, but the spec
17246 // really only says that checks for unqualified existing
17247 // declarations should stop at the nearest enclosing namespace,
17248 // not that they should only consider the nearest enclosing
17249 // namespace.
17250 while (DC->isRecord())
17251 DC = DC->getParent();
17252
17253 DeclContext *LookupDC = DC->getNonTransparentContext();
17254 while (true) {
17255 LookupQualifiedName(Previous, LookupDC);
17256
17257 if (!Previous.empty()) {
17258 DC = LookupDC;
17259 break;
17260 }
17261
17262 if (isTemplateId) {
17263 if (isa<TranslationUnitDecl>(LookupDC)) break;
17264 } else {
17265 if (LookupDC->isFileContext()) break;
17266 }
17267 LookupDC = LookupDC->getParent();
17268 }
17269
17270 DCScope = getScopeForDeclContext(S, DC);
17271
17272 // - There's a non-dependent scope specifier, in which case we
17273 // compute it and do a previous lookup there for a function
17274 // or function template.
17275 } else if (!SS.getScopeRep()->isDependent()) {
17276 DC = computeDeclContext(SS);
17277 if (!DC) return nullptr;
17278
17279 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17280
17281 LookupQualifiedName(Previous, DC);
17282
17283 // C++ [class.friend]p1: A friend of a class is a function or
17284 // class that is not a member of the class . . .
17285 if (DC->Equals(CurContext))
17286 Diag(DS.getFriendSpecLoc(),
17287 getLangOpts().CPlusPlus11 ?
17288 diag::warn_cxx98_compat_friend_is_member :
17289 diag::err_friend_is_member);
17290
17291 if (D.isFunctionDefinition()) {
17292 // C++ [class.friend]p6:
17293 // A function can be defined in a friend declaration of a class if and
17294 // only if the class is a non-local class (9.8), the function name is
17295 // unqualified, and the function has namespace scope.
17296 //
17297 // FIXME: We should only do this if the scope specifier names the
17298 // innermost enclosing namespace; otherwise the fixit changes the
17299 // meaning of the code.
17300 SemaDiagnosticBuilder DB
17301 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17302
17303 DB << SS.getScopeRep();
17304 if (DC->isFileContext())
17305 DB << FixItHint::CreateRemoval(SS.getRange());
17306 SS.clear();
17307 }
17308
17309 // - There's a scope specifier that does not match any template
17310 // parameter lists, in which case we use some arbitrary context,
17311 // create a method or method template, and wait for instantiation.
17312 // - There's a scope specifier that does match some template
17313 // parameter lists, which we don't handle right now.
17314 } else {
17315 if (D.isFunctionDefinition()) {
17316 // C++ [class.friend]p6:
17317 // A function can be defined in a friend declaration of a class if and
17318 // only if the class is a non-local class (9.8), the function name is
17319 // unqualified, and the function has namespace scope.
17320 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
17321 << SS.getScopeRep();
17322 }
17323
17324 DC = CurContext;
17325 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", 17325, __extension__ __PRETTY_FUNCTION__
))
;
17326 }
17327
17328 if (!DC->isRecord()) {
17329 int DiagArg = -1;
17330 switch (D.getName().getKind()) {
17331 case UnqualifiedIdKind::IK_ConstructorTemplateId:
17332 case UnqualifiedIdKind::IK_ConstructorName:
17333 DiagArg = 0;
17334 break;
17335 case UnqualifiedIdKind::IK_DestructorName:
17336 DiagArg = 1;
17337 break;
17338 case UnqualifiedIdKind::IK_ConversionFunctionId:
17339 DiagArg = 2;
17340 break;
17341 case UnqualifiedIdKind::IK_DeductionGuideName:
17342 DiagArg = 3;
17343 break;
17344 case UnqualifiedIdKind::IK_Identifier:
17345 case UnqualifiedIdKind::IK_ImplicitSelfParam:
17346 case UnqualifiedIdKind::IK_LiteralOperatorId:
17347 case UnqualifiedIdKind::IK_OperatorFunctionId:
17348 case UnqualifiedIdKind::IK_TemplateId:
17349 break;
17350 }
17351 // This implies that it has to be an operator or function.
17352 if (DiagArg >= 0) {
17353 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17354 return nullptr;
17355 }
17356 }
17357
17358 // FIXME: This is an egregious hack to cope with cases where the scope stack
17359 // does not contain the declaration context, i.e., in an out-of-line
17360 // definition of a class.
17361 Scope FakeDCScope(S, Scope::DeclScope, Diags);
17362 if (!DCScope) {
17363 FakeDCScope.setEntity(DC);
17364 DCScope = &FakeDCScope;
17365 }
17366
17367 bool AddToScope = true;
17368 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17369 TemplateParams, AddToScope);
17370 if (!ND) return nullptr;
17371
17372 assert(ND->getLexicalDeclContext() == CurContext)(static_cast <bool> (ND->getLexicalDeclContext() == CurContext
) ? void (0) : __assert_fail ("ND->getLexicalDeclContext() == CurContext"
, "clang/lib/Sema/SemaDeclCXX.cpp", 17372, __extension__ __PRETTY_FUNCTION__
))
;
17373
17374 // If we performed typo correction, we might have added a scope specifier
17375 // and changed the decl context.
17376 DC = ND->getDeclContext();
17377
17378 // Add the function declaration to the appropriate lookup tables,
17379 // adjusting the redeclarations list as necessary. We don't
17380 // want to do this yet if the friending class is dependent.
17381 //
17382 // Also update the scope-based lookup if the target context's
17383 // lookup context is in lexical scope.
17384 if (!CurContext->isDependentContext()) {
17385 DC = DC->getRedeclContext();
17386 DC->makeDeclVisibleInContext(ND);
17387 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17388 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17389 }
17390
17391 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
17392 D.getIdentifierLoc(), ND,
17393 DS.getFriendSpecLoc());
17394 FrD->setAccess(AS_public);
17395 CurContext->addDecl(FrD);
17396
17397 if (ND->isInvalidDecl()) {
17398 FrD->setInvalidDecl();
17399 } else {
17400 if (DC->isRecord()) CheckFriendAccess(ND);
17401
17402 FunctionDecl *FD;
17403 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17404 FD = FTD->getTemplatedDecl();
17405 else
17406 FD = cast<FunctionDecl>(ND);
17407
17408 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17409 // default argument expression, that declaration shall be a definition
17410 // and shall be the only declaration of the function or function
17411 // template in the translation unit.
17412 if (functionDeclHasDefaultArgument(FD)) {
17413 // We can't look at FD->getPreviousDecl() because it may not have been set
17414 // if we're in a dependent context. If the function is known to be a
17415 // redeclaration, we will have narrowed Previous down to the right decl.
17416 if (D.isRedeclaration()) {
17417 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17418 Diag(Previous.getRepresentativeDecl()->getLocation(),
17419 diag::note_previous_declaration);
17420 } else if (!D.isFunctionDefinition())
17421 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17422 }
17423
17424 // Mark templated-scope function declarations as unsupported.
17425 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17426 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17427 << SS.getScopeRep() << SS.getRange()
17428 << cast<CXXRecordDecl>(CurContext);
17429 FrD->setUnsupportedFriend(true);
17430 }
17431 }
17432
17433 warnOnReservedIdentifier(ND);
17434
17435 return ND;
17436}
17437
17438void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
17439 AdjustDeclIfTemplate(Dcl);
17440
17441 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17442 if (!Fn) {
17443 Diag(DelLoc, diag::err_deleted_non_function);
17444 return;
17445 }
17446
17447 // Deleted function does not have a body.
17448 Fn->setWillHaveBody(false);
17449
17450 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17451 // Don't consider the implicit declaration we generate for explicit
17452 // specializations. FIXME: Do not generate these implicit declarations.
17453 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17454 Prev->getPreviousDecl()) &&
17455 !Prev->isDefined()) {
17456 Diag(DelLoc, diag::err_deleted_decl_not_first);
17457 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17458 Prev->isImplicit() ? diag::note_previous_implicit_declaration
17459 : diag::note_previous_declaration);
17460 // We can't recover from this; the declaration might have already
17461 // been used.
17462 Fn->setInvalidDecl();
17463 return;
17464 }
17465
17466 // To maintain the invariant that functions are only deleted on their first
17467 // declaration, mark the implicitly-instantiated declaration of the
17468 // explicitly-specialized function as deleted instead of marking the
17469 // instantiated redeclaration.
17470 Fn = Fn->getCanonicalDecl();
17471 }
17472
17473 // dllimport/dllexport cannot be deleted.
17474 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17475 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17476 Fn->setInvalidDecl();
17477 }
17478
17479 // C++11 [basic.start.main]p3:
17480 // A program that defines main as deleted [...] is ill-formed.
17481 if (Fn->isMain())
17482 Diag(DelLoc, diag::err_deleted_main);
17483
17484 // C++11 [dcl.fct.def.delete]p4:
17485 // A deleted function is implicitly inline.
17486 Fn->setImplicitlyInline();
17487 Fn->setDeletedAsWritten();
17488}
17489
17490void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17491 if (!Dcl || Dcl->isInvalidDecl())
17492 return;
17493
17494 auto *FD = dyn_cast<FunctionDecl>(Dcl);
17495 if (!FD) {
17496 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17497 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17498 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17499 return;
17500 }
17501 }
17502
17503 Diag(DefaultLoc, diag::err_default_special_members)
17504 << getLangOpts().CPlusPlus20;
17505 return;
17506 }
17507
17508 // Reject if this can't possibly be a defaultable function.
17509 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17510 if (!DefKind &&
17511 // A dependent function that doesn't locally look defaultable can
17512 // still instantiate to a defaultable function if it's a constructor
17513 // or assignment operator.
17514 (!FD->isDependentContext() ||
17515 (!isa<CXXConstructorDecl>(FD) &&
17516 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17517 Diag(DefaultLoc, diag::err_default_special_members)
17518 << getLangOpts().CPlusPlus20;
17519 return;
17520 }
17521
17522 // Issue compatibility warning. We already warned if the operator is
17523 // 'operator<=>' when parsing the '<=>' token.
17524 if (DefKind.isComparison() &&
17525 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17526 Diag(DefaultLoc, getLangOpts().CPlusPlus20
17527 ? diag::warn_cxx17_compat_defaulted_comparison
17528 : diag::ext_defaulted_comparison);
17529 }
17530
17531 FD->setDefaulted();
17532 FD->setExplicitlyDefaulted();
17533
17534 // Defer checking functions that are defaulted in a dependent context.
17535 if (FD->isDependentContext())
17536 return;
17537
17538 // Unset that we will have a body for this function. We might not,
17539 // if it turns out to be trivial, and we don't need this marking now
17540 // that we've marked it as defaulted.
17541 FD->setWillHaveBody(false);
17542
17543 if (DefKind.isComparison()) {
17544 // If this comparison's defaulting occurs within the definition of its
17545 // lexical class context, we have to do the checking when complete.
17546 if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
17547 if (!RD->isCompleteDefinition())
17548 return;
17549 }
17550
17551 // If this member fn was defaulted on its first declaration, we will have
17552 // already performed the checking in CheckCompletedCXXClass. Such a
17553 // declaration doesn't trigger an implicit definition.
17554 if (isa<CXXMethodDecl>(FD)) {
17555 const FunctionDecl *Primary = FD;
17556 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17557 // Ask the template instantiation pattern that actually had the
17558 // '= default' on it.
17559 Primary = Pattern;
17560 if (Primary->getCanonicalDecl()->isDefaulted())
17561 return;
17562 }
17563
17564 if (DefKind.isComparison()) {
17565 if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
17566 FD->setInvalidDecl();
17567 else
17568 DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
17569 } else {
17570 auto *MD = cast<CXXMethodDecl>(FD);
17571
17572 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
17573 MD->setInvalidDecl();
17574 else
17575 DefineDefaultedFunction(*this, MD, DefaultLoc);
17576 }
17577}
17578
17579static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17580 for (Stmt *SubStmt : S->children()) {
17581 if (!SubStmt)
17582 continue;
17583 if (isa<ReturnStmt>(SubStmt))
17584 Self.Diag(SubStmt->getBeginLoc(),
17585 diag::err_return_in_constructor_handler);
17586 if (!isa<Expr>(SubStmt))
17587 SearchForReturnInStmt(Self, SubStmt);
17588 }
17589}
17590
17591void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
17592 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17593 CXXCatchStmt *Handler = TryBlock->getHandler(I);
17594 SearchForReturnInStmt(*this, Handler);
17595 }
17596}
17597
17598void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
17599 FnBodyKind BodyKind) {
17600 switch (BodyKind) {
17601 case FnBodyKind::Delete:
17602 SetDeclDeleted(D, Loc);
17603 break;
17604 case FnBodyKind::Default:
17605 SetDeclDefaulted(D, Loc);
17606 break;
17607 case FnBodyKind::Other:
17608 llvm_unreachable(::llvm::llvm_unreachable_internal("Parsed function body should be '= delete;' or '= default;'"
, "clang/lib/Sema/SemaDeclCXX.cpp", 17609)
17609 "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", 17609)
;
17610 }
17611}
17612
17613bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
17614 const CXXMethodDecl *Old) {
17615 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17616 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17617
17618 if (OldFT->hasExtParameterInfos()) {
17619 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17620 // A parameter of the overriding method should be annotated with noescape
17621 // if the corresponding parameter of the overridden method is annotated.
17622 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17623 !NewFT->getExtParameterInfo(I).isNoEscape()) {
17624 Diag(New->getParamDecl(I)->getLocation(),
17625 diag::warn_overriding_method_missing_noescape);
17626 Diag(Old->getParamDecl(I)->getLocation(),
17627 diag::note_overridden_marked_noescape);
17628 }
17629 }
17630
17631 // Virtual overrides must have the same code_seg.
17632 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17633 const auto *NewCSA = New->getAttr<CodeSegAttr>();
17634 if ((NewCSA || OldCSA) &&
17635 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17636 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17637 Diag(Old->getLocation(), diag::note_previous_declaration);
17638 return true;
17639 }
17640
17641 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17642
17643 // If the calling conventions match, everything is fine
17644 if (NewCC == OldCC)
17645 return false;
17646
17647 // If the calling conventions mismatch because the new function is static,
17648 // suppress the calling convention mismatch error; the error about static
17649 // function override (err_static_overrides_virtual from
17650 // Sema::CheckFunctionDeclaration) is more clear.
17651 if (New->getStorageClass() == SC_Static)
17652 return false;
17653
17654 Diag(New->getLocation(),
17655 diag::err_conflicting_overriding_cc_attributes)
17656 << New->getDeclName() << New->getType() << Old->getType();
17657 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
17658 return true;
17659}
17660
17661bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
17662 const CXXMethodDecl *Old) {
17663 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17664 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17665
17666 if (Context.hasSameType(NewTy, OldTy) ||
17667 NewTy->isDependentType() || OldTy->isDependentType())
17668 return false;
17669
17670 // Check if the return types are covariant
17671 QualType NewClassTy, OldClassTy;
17672
17673 /// Both types must be pointers or references to classes.
17674 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17675 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17676 NewClassTy = NewPT->getPointeeType();
17677 OldClassTy = OldPT->getPointeeType();
17678 }
17679 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17680 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17681 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17682 NewClassTy = NewRT->getPointeeType();
17683 OldClassTy = OldRT->getPointeeType();
17684 }
17685 }
17686 }
17687
17688 // The return types aren't either both pointers or references to a class type.
17689 if (NewClassTy.isNull()) {
17690 Diag(New->getLocation(),
17691 diag::err_different_return_type_for_overriding_virtual_function)
17692 << New->getDeclName() << NewTy << OldTy
17693 << New->getReturnTypeSourceRange();
17694 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17695 << Old->getReturnTypeSourceRange();
17696
17697 return true;
17698 }
17699
17700 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17701 // C++14 [class.virtual]p8:
17702 // If the class type in the covariant return type of D::f differs from
17703 // that of B::f, the class type in the return type of D::f shall be
17704 // complete at the point of declaration of D::f or shall be the class
17705 // type D.
17706 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17707 if (!RT->isBeingDefined() &&
17708 RequireCompleteType(New->getLocation(), NewClassTy,
17709 diag::err_covariant_return_incomplete,
17710 New->getDeclName()))
17711 return true;
17712 }
17713
17714 // Check if the new class derives from the old class.
17715 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17716 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17717 << New->getDeclName() << NewTy << OldTy
17718 << New->getReturnTypeSourceRange();
17719 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17720 << Old->getReturnTypeSourceRange();
17721 return true;
17722 }
17723
17724 // Check if we the conversion from derived to base is valid.
17725 if (CheckDerivedToBaseConversion(
17726 NewClassTy, OldClassTy,
17727 diag::err_covariant_return_inaccessible_base,
17728 diag::err_covariant_return_ambiguous_derived_to_base_conv,
17729 New->getLocation(), New->getReturnTypeSourceRange(),
17730 New->getDeclName(), nullptr)) {
17731 // FIXME: this note won't trigger for delayed access control
17732 // diagnostics, and it's impossible to get an undelayed error
17733 // here from access control during the original parse because
17734 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17735 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17736 << Old->getReturnTypeSourceRange();
17737 return true;
17738 }
17739 }
17740
17741 // The qualifiers of the return types must be the same.
17742 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17743 Diag(New->getLocation(),
17744 diag::err_covariant_return_type_different_qualifications)
17745 << New->getDeclName() << NewTy << OldTy
17746 << New->getReturnTypeSourceRange();
17747 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17748 << Old->getReturnTypeSourceRange();
17749 return true;
17750 }
17751
17752
17753 // The new class type must have the same or less qualifiers as the old type.
17754 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17755 Diag(New->getLocation(),
17756 diag::err_covariant_return_type_class_type_more_qualified)
17757 << New->getDeclName() << NewTy << OldTy
17758 << New->getReturnTypeSourceRange();
17759 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17760 << Old->getReturnTypeSourceRange();
17761 return true;
17762 }
17763
17764 return false;
17765}
17766
17767/// Mark the given method pure.
17768///
17769/// \param Method the method to be marked pure.
17770///
17771/// \param InitRange the source range that covers the "0" initializer.
17772bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17773 SourceLocation EndLoc = InitRange.getEnd();
17774 if (EndLoc.isValid())
17775 Method->setRangeEnd(EndLoc);
17776
17777 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17778 Method->setPure();
17779 return false;
17780 }
17781
17782 if (!Method->isInvalidDecl())
17783 Diag(Method->getLocation(), diag::err_non_virtual_pure)
17784 << Method->getDeclName() << InitRange;
17785 return true;
17786}
17787
17788void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17789 if (D->getFriendObjectKind())
17790 Diag(D->getLocation(), diag::err_pure_friend);
17791 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17792 CheckPureMethod(M, ZeroLoc);
17793 else
17794 Diag(D->getLocation(), diag::err_illegal_initializer);
17795}
17796
17797/// Determine whether the given declaration is a global variable or
17798/// static data member.
17799static bool isNonlocalVariable(const Decl *D) {
17800 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17801 return Var->hasGlobalStorage();
17802
17803 return false;
17804}
17805
17806/// Invoked when we are about to parse an initializer for the declaration
17807/// 'Dcl'.
17808///
17809/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17810/// static data member of class X, names should be looked up in the scope of
17811/// class X. If the declaration had a scope specifier, a scope will have
17812/// been created and passed in for this purpose. Otherwise, S will be null.
17813void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17814 // If there is no declaration, there was an error parsing it.
17815 if (!D || D->isInvalidDecl())
17816 return;
17817
17818 // We will always have a nested name specifier here, but this declaration
17819 // might not be out of line if the specifier names the current namespace:
17820 // extern int n;
17821 // int ::n = 0;
17822 if (S && D->isOutOfLine())
17823 EnterDeclaratorContext(S, D->getDeclContext());
17824
17825 // If we are parsing the initializer for a static data member, push a
17826 // new expression evaluation context that is associated with this static
17827 // data member.
17828 if (isNonlocalVariable(D))
17829 PushExpressionEvaluationContext(
17830 ExpressionEvaluationContext::PotentiallyEvaluated, D);
17831}
17832
17833/// Invoked after we are finished parsing an initializer for the declaration D.
17834void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17835 // If there is no declaration, there was an error parsing it.
17836 if (!D || D->isInvalidDecl())
17837 return;
17838
17839 if (isNonlocalVariable(D))
17840 PopExpressionEvaluationContext();
17841
17842 if (S && D->isOutOfLine())
17843 ExitDeclaratorContext(S);
17844}
17845
17846/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17847/// C++ if/switch/while/for statement.
17848/// e.g: "if (int x = f()) {...}"
17849DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17850 // C++ 6.4p2:
17851 // The declarator shall not specify a function or an array.
17852 // The type-specifier-seq shall not contain typedef and shall not declare a
17853 // new class or enumeration.
17854 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", 17855, __extension__ __PRETTY_FUNCTION__
))
17855 "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", 17855, __extension__ __PRETTY_FUNCTION__
))
;
17856
17857 Decl *Dcl = ActOnDeclarator(S, D);
17858 if (!Dcl)
17859 return true;
17860
17861 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17862 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17863 << D.getSourceRange();
17864 return true;
17865 }
17866
17867 return Dcl;
17868}
17869
17870void Sema::LoadExternalVTableUses() {
17871 if (!ExternalSource)
17872 return;
17873
17874 SmallVector<ExternalVTableUse, 4> VTables;
17875 ExternalSource->ReadUsedVTables(VTables);
17876 SmallVector<VTableUse, 4> NewUses;
17877 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17878 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17879 = VTablesUsed.find(VTables[I].Record);
17880 // Even if a definition wasn't required before, it may be required now.
17881 if (Pos != VTablesUsed.end()) {
17882 if (!Pos->second && VTables[I].DefinitionRequired)
17883 Pos->second = true;
17884 continue;
17885 }
17886
17887 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17888 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17889 }
17890
17891 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17892}
17893
17894void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17895 bool DefinitionRequired) {
17896 // Ignore any vtable uses in unevaluated operands or for classes that do
17897 // not have a vtable.
17898 if (!Class->isDynamicClass() || Class->isDependentContext() ||
17899 CurContext->isDependentContext() || isUnevaluatedContext())
17900 return;
17901 // Do not mark as used if compiling for the device outside of the target
17902 // region.
17903 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17904 !isInOpenMPDeclareTargetContext() &&
17905 !isInOpenMPTargetExecutionDirective()) {
17906 if (!DefinitionRequired)
17907 MarkVirtualMembersReferenced(Loc, Class);
17908 return;
17909 }
17910
17911 // Try to insert this class into the map.
17912 LoadExternalVTableUses();
17913 Class = Class->getCanonicalDecl();
17914 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17915 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17916 if (!Pos.second) {
17917 // If we already had an entry, check to see if we are promoting this vtable
17918 // to require a definition. If so, we need to reappend to the VTableUses
17919 // list, since we may have already processed the first entry.
17920 if (DefinitionRequired && !Pos.first->second) {
17921 Pos.first->second = true;
17922 } else {
17923 // Otherwise, we can early exit.
17924 return;
17925 }
17926 } else {
17927 // The Microsoft ABI requires that we perform the destructor body
17928 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17929 // the deleting destructor is emitted with the vtable, not with the
17930 // destructor definition as in the Itanium ABI.
17931 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17932 CXXDestructorDecl *DD = Class->getDestructor();
17933 if (DD && DD->isVirtual() && !DD->isDeleted()) {
17934 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17935 // If this is an out-of-line declaration, marking it referenced will
17936 // not do anything. Manually call CheckDestructor to look up operator
17937 // delete().
17938 ContextRAII SavedContext(*this, DD);
17939 CheckDestructor(DD);
17940 } else {
17941 MarkFunctionReferenced(Loc, Class->getDestructor());
17942 }
17943 }
17944 }
17945 }
17946
17947 // Local classes need to have their virtual members marked
17948 // immediately. For all other classes, we mark their virtual members
17949 // at the end of the translation unit.
17950 if (Class->isLocalClass())
17951 MarkVirtualMembersReferenced(Loc, Class);
17952 else
17953 VTableUses.push_back(std::make_pair(Class, Loc));
17954}
17955
17956bool Sema::DefineUsedVTables() {
17957 LoadExternalVTableUses();
17958 if (VTableUses.empty())
17959 return false;
17960
17961 // Note: The VTableUses vector could grow as a result of marking
17962 // the members of a class as "used", so we check the size each
17963 // time through the loop and prefer indices (which are stable) to
17964 // iterators (which are not).
17965 bool DefinedAnything = false;
17966 for (unsigned I = 0; I != VTableUses.size(); ++I) {
17967 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17968 if (!Class)
17969 continue;
17970 TemplateSpecializationKind ClassTSK =
17971 Class->getTemplateSpecializationKind();
17972
17973 SourceLocation Loc = VTableUses[I].second;
17974
17975 bool DefineVTable = true;
17976
17977 // If this class has a key function, but that key function is
17978 // defined in another translation unit, we don't need to emit the
17979 // vtable even though we're using it.
17980 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17981 if (KeyFunction && !KeyFunction->hasBody()) {
17982 // The key function is in another translation unit.
17983 DefineVTable = false;
17984 TemplateSpecializationKind TSK =
17985 KeyFunction->getTemplateSpecializationKind();
17986 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", 17988, __extension__ __PRETTY_FUNCTION__
))
17987 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", 17988, __extension__ __PRETTY_FUNCTION__
))
17988 "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", 17988, __extension__ __PRETTY_FUNCTION__
))
;
17989 (void)TSK;
17990 } else if (!KeyFunction) {
17991 // If we have a class with no key function that is the subject
17992 // of an explicit instantiation declaration, suppress the
17993 // vtable; it will live with the explicit instantiation
17994 // definition.
17995 bool IsExplicitInstantiationDeclaration =
17996 ClassTSK == TSK_ExplicitInstantiationDeclaration;
17997 for (auto *R : Class->redecls()) {
17998 TemplateSpecializationKind TSK
17999 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
18000 if (TSK == TSK_ExplicitInstantiationDeclaration)
18001 IsExplicitInstantiationDeclaration = true;
18002 else if (TSK == TSK_ExplicitInstantiationDefinition) {
18003 IsExplicitInstantiationDeclaration = false;
18004 break;
18005 }
18006 }
18007
18008 if (IsExplicitInstantiationDeclaration)
18009 DefineVTable = false;
18010 }
18011
18012 // The exception specifications for all virtual members may be needed even
18013 // if we are not providing an authoritative form of the vtable in this TU.
18014 // We may choose to emit it available_externally anyway.
18015 if (!DefineVTable) {
18016 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
18017 continue;
18018 }
18019
18020 // Mark all of the virtual members of this class as referenced, so
18021 // that we can build a vtable. Then, tell the AST consumer that a
18022 // vtable for this class is required.
18023 DefinedAnything = true;
18024 MarkVirtualMembersReferenced(Loc, Class);
18025 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
18026 if (VTablesUsed[Canonical])
18027 Consumer.HandleVTable(Class);
18028
18029 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
18030 // no key function or the key function is inlined. Don't warn in C++ ABIs
18031 // that lack key functions, since the user won't be able to make one.
18032 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
18033 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
18034 ClassTSK != TSK_ExplicitInstantiationDefinition) {
18035 const FunctionDecl *KeyFunctionDef = nullptr;
18036 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
18037 KeyFunctionDef->isInlined()))
18038 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
18039 }
18040 }
18041 VTableUses.clear();
18042
18043 return DefinedAnything;
18044}
18045
18046void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
18047 const CXXRecordDecl *RD) {
18048 for (const auto *I : RD->methods())
18049 if (I->isVirtual() && !I->isPure())
18050 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
18051}
18052
18053void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
18054 const CXXRecordDecl *RD,
18055 bool ConstexprOnly) {
18056 // Mark all functions which will appear in RD's vtable as used.
18057 CXXFinalOverriderMap FinalOverriders;
18058 RD->getFinalOverriders(FinalOverriders);
18059 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
18060 E = FinalOverriders.end();
18061 I != E; ++I) {
18062 for (OverridingMethods::const_iterator OI = I->second.begin(),
18063 OE = I->second.end();
18064 OI != OE; ++OI) {
18065 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", 18065, __extension__ __PRETTY_FUNCTION__
))
;
18066 CXXMethodDecl *Overrider = OI->second.front().Method;
18067
18068 // C++ [basic.def.odr]p2:
18069 // [...] A virtual member function is used if it is not pure. [...]
18070 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
18071 MarkFunctionReferenced(Loc, Overrider);
18072 }
18073 }
18074
18075 // Only classes that have virtual bases need a VTT.
18076 if (RD->getNumVBases() == 0)
18077 return;
18078
18079 for (const auto &I : RD->bases()) {
18080 const auto *Base =
18081 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
18082 if (Base->getNumVBases() == 0)
18083 continue;
18084 MarkVirtualMembersReferenced(Loc, Base);
18085 }
18086}
18087
18088/// SetIvarInitializers - This routine builds initialization ASTs for the
18089/// Objective-C implementation whose ivars need be initialized.
18090void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
18091 if (!getLangOpts().CPlusPlus)
18092 return;
18093 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
18094 SmallVector<ObjCIvarDecl*, 8> ivars;
18095 CollectIvarsToConstructOrDestruct(OID, ivars);
18096 if (ivars.empty())
18097 return;
18098 SmallVector<CXXCtorInitializer*, 32> AllToInit;
18099 for (unsigned i = 0; i < ivars.size(); i++) {
18100 FieldDecl *Field = ivars[i];
18101 if (Field->isInvalidDecl())
18102 continue;
18103
18104 CXXCtorInitializer *Member;
18105 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
18106 InitializationKind InitKind =
18107 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
18108
18109 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
18110 ExprResult MemberInit =
18111 InitSeq.Perform(*this, InitEntity, InitKind, None);
18112 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
18113 // Note, MemberInit could actually come back empty if no initialization
18114 // is required (e.g., because it would call a trivial default constructor)
18115 if (!MemberInit.get() || MemberInit.isInvalid())
18116 continue;
18117
18118 Member =
18119 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
18120 SourceLocation(),
18121 MemberInit.getAs<Expr>(),
18122 SourceLocation());
18123 AllToInit.push_back(Member);
18124
18125 // Be sure that the destructor is accessible and is marked as referenced.
18126 if (const RecordType *RecordTy =
18127 Context.getBaseElementType(Field->getType())
18128 ->getAs<RecordType>()) {
18129 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
18130 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
18131 MarkFunctionReferenced(Field->getLocation(), Destructor);
18132 CheckDestructorAccess(Field->getLocation(), Destructor,
18133 PDiag(diag::err_access_dtor_ivar)
18134 << Context.getBaseElementType(Field->getType()));
18135 }
18136 }
18137 }
18138 ObjCImplementation->setIvarInitializers(Context,
18139 AllToInit.data(), AllToInit.size());
18140 }
18141}
18142
18143static
18144void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
18145 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
18146 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
18147 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
18148 Sema &S) {
18149 if (Ctor->isInvalidDecl())
18150 return;
18151
18152 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
18153
18154 // Target may not be determinable yet, for instance if this is a dependent
18155 // call in an uninstantiated template.
18156 if (Target) {
18157 const FunctionDecl *FNTarget = nullptr;
18158 (void)Target->hasBody(FNTarget);
18159 Target = const_cast<CXXConstructorDecl*>(
18160 cast_or_null<CXXConstructorDecl>(FNTarget));
18161 }
18162
18163 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
18164 // Avoid dereferencing a null pointer here.
18165 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
18166
18167 if (!Current.insert(Canonical).second)
18168 return;
18169
18170 // We know that beyond here, we aren't chaining into a cycle.
18171 if (!Target || !Target->isDelegatingConstructor() ||
18172 Target->isInvalidDecl() || Valid.count(TCanonical)) {
18173 Valid.insert(Current.begin(), Current.end());
18174 Current.clear();
18175 // We've hit a cycle.
18176 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
18177 Current.count(TCanonical)) {
18178 // If we haven't diagnosed this cycle yet, do so now.
18179 if (!Invalid.count(TCanonical)) {
18180 S.Diag((*Ctor->init_begin())->getSourceLocation(),
18181 diag::warn_delegating_ctor_cycle)
18182 << Ctor;
18183
18184 // Don't add a note for a function delegating directly to itself.
18185 if (TCanonical != Canonical)
18186 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18187
18188 CXXConstructorDecl *C = Target;
18189 while (C->getCanonicalDecl() != Canonical) {
18190 const FunctionDecl *FNTarget = nullptr;
18191 (void)C->getTargetConstructor()->hasBody(FNTarget);
18192 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", 18192, __extension__ __PRETTY_FUNCTION__
))
;
18193
18194 C = const_cast<CXXConstructorDecl*>(
18195 cast<CXXConstructorDecl>(FNTarget));
18196 S.Diag(C->getLocation(), diag::note_which_delegates_to);
18197 }
18198 }
18199
18200 Invalid.insert(Current.begin(), Current.end());
18201 Current.clear();
18202 } else {
18203 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18204 }
18205}
18206
18207
18208void Sema::CheckDelegatingCtorCycles() {
18209 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
18210
18211 for (DelegatingCtorDeclsType::iterator
18212 I = DelegatingCtorDecls.begin(ExternalSource.get()),
18213 E = DelegatingCtorDecls.end();
18214 I != E; ++I)
18215 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18216
18217 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18218 (*CI)->setInvalidDecl();
18219}
18220
18221namespace {
18222 /// AST visitor that finds references to the 'this' expression.
18223 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18224 Sema &S;
18225
18226 public:
18227 explicit FindCXXThisExpr(Sema &S) : S(S) { }
18228
18229 bool VisitCXXThisExpr(CXXThisExpr *E) {
18230 S.Diag(E->getLocation(), diag::err_this_static_member_func)
18231 << E->isImplicit();
18232 return false;
18233 }
18234 };
18235}
18236
18237bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
18238 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18239 if (!TSInfo)
18240 return false;
18241
18242 TypeLoc TL = TSInfo->getTypeLoc();
18243 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18244 if (!ProtoTL)
18245 return false;
18246
18247 // C++11 [expr.prim.general]p3:
18248 // [The expression this] shall not appear before the optional
18249 // cv-qualifier-seq and it shall not appear within the declaration of a
18250 // static member function (although its type and value category are defined
18251 // within a static member function as they are within a non-static member
18252 // function). [ Note: this is because declaration matching does not occur
18253 // until the complete declarator is known. - end note ]
18254 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18255 FindCXXThisExpr Finder(*this);
18256
18257 // If the return type came after the cv-qualifier-seq, check it now.
18258 if (Proto->hasTrailingReturn() &&
18259 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18260 return true;
18261
18262 // Check the exception specification.
18263 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18264 return true;
18265
18266 // Check the trailing requires clause
18267 if (Expr *E = Method->getTrailingRequiresClause())
18268 if (!Finder.TraverseStmt(E))
18269 return true;
18270
18271 return checkThisInStaticMemberFunctionAttributes(Method);
18272}
18273
18274bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
18275 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18276 if (!TSInfo)
18277 return false;
18278
18279 TypeLoc TL = TSInfo->getTypeLoc();
18280 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18281 if (!ProtoTL)
18282 return false;
18283
18284 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18285 FindCXXThisExpr Finder(*this);
18286
18287 switch (Proto->getExceptionSpecType()) {
18288 case EST_Unparsed:
18289 case EST_Uninstantiated:
18290 case EST_Unevaluated:
18291 case EST_BasicNoexcept:
18292 case EST_NoThrow:
18293 case EST_DynamicNone:
18294 case EST_MSAny:
18295 case EST_None:
18296 break;
18297
18298 case EST_DependentNoexcept:
18299 case EST_NoexceptFalse:
18300 case EST_NoexceptTrue:
18301 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18302 return true;
18303 [[fallthrough]];
18304
18305 case EST_Dynamic:
18306 for (const auto &E : Proto->exceptions()) {
18307 if (!Finder.TraverseType(E))
18308 return true;
18309 }
18310 break;
18311 }
18312
18313 return false;
18314}
18315
18316bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
18317 FindCXXThisExpr Finder(*this);
18318
18319 // Check attributes.
18320 for (const auto *A : Method->attrs()) {
18321 // FIXME: This should be emitted by tblgen.
18322 Expr *Arg = nullptr;
18323 ArrayRef<Expr *> Args;
18324 if (const auto *G = dyn_cast<GuardedByAttr>(A))
18325 Arg = G->getArg();
18326 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18327 Arg = G->getArg();
18328 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18329 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
18330 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18331 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
18332 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18333 Arg = ETLF->getSuccessValue();
18334 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
18335 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18336 Arg = STLF->getSuccessValue();
18337 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
18338 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18339 Arg = LR->getArg();
18340 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18341 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
18342 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18343 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18344 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18345 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18346 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18347 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18348 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18349 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18350
18351 if (Arg && !Finder.TraverseStmt(Arg))
18352 return true;
18353
18354 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18355 if (!Finder.TraverseStmt(Args[I]))
18356 return true;
18357 }
18358 }
18359
18360 return false;
18361}
18362
18363void Sema::checkExceptionSpecification(
18364 bool IsTopLevel, ExceptionSpecificationType EST,
18365 ArrayRef<ParsedType> DynamicExceptions,
18366 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18367 SmallVectorImpl<QualType> &Exceptions,
18368 FunctionProtoType::ExceptionSpecInfo &ESI) {
18369 Exceptions.clear();
18370 ESI.Type = EST;
18371 if (EST == EST_Dynamic) {
18372 Exceptions.reserve(DynamicExceptions.size());
18373 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18374 // FIXME: Preserve type source info.
18375 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18376
18377 if (IsTopLevel) {
18378 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
18379 collectUnexpandedParameterPacks(ET, Unexpanded);
18380 if (!Unexpanded.empty()) {
18381 DiagnoseUnexpandedParameterPacks(
18382 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18383 Unexpanded);
18384 continue;
18385 }
18386 }
18387
18388 // Check that the type is valid for an exception spec, and
18389 // drop it if not.
18390 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18391 Exceptions.push_back(ET);
18392 }
18393 ESI.Exceptions = Exceptions;
18394 return;
18395 }
18396
18397 if (isComputedNoexcept(EST)) {
18398 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", 18401, __extension__ __PRETTY_FUNCTION__
))
18399 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", 18401, __extension__ __PRETTY_FUNCTION__
))
18400 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", 18401, __extension__ __PRETTY_FUNCTION__
))
18401 "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", 18401, __extension__ __PRETTY_FUNCTION__
))
;
18402 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18403 ESI.Type = EST_BasicNoexcept;
18404 return;
18405 }
18406
18407 ESI.NoexceptExpr = NoexceptExpr;
18408 return;
18409 }
18410}
18411
18412void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
18413 ExceptionSpecificationType EST,
18414 SourceRange SpecificationRange,
18415 ArrayRef<ParsedType> DynamicExceptions,
18416 ArrayRef<SourceRange> DynamicExceptionRanges,
18417 Expr *NoexceptExpr) {
18418 if (!MethodD)
18419 return;
18420
18421 // Dig out the method we're referring to.
18422 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18423 MethodD = FunTmpl->getTemplatedDecl();
18424
18425 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18426 if (!Method)
18427 return;
18428
18429 // Check the exception specification.
18430 llvm::SmallVector<QualType, 4> Exceptions;
18431 FunctionProtoType::ExceptionSpecInfo ESI;
18432 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18433 DynamicExceptionRanges, NoexceptExpr, Exceptions,
18434 ESI);
18435
18436 // Update the exception specification on the function type.
18437 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18438
18439 if (Method->isStatic())
18440 checkThisInStaticMemberFunctionExceptionSpec(Method);
18441
18442 if (Method->isVirtual()) {
18443 // Check overrides, which we previously had to delay.
18444 for (const CXXMethodDecl *O : Method->overridden_methods())
18445 CheckOverridingFunctionExceptionSpec(Method, O);
18446 }
18447}
18448
18449/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18450///
18451MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
18452 SourceLocation DeclStart, Declarator &D,
18453 Expr *BitWidth,
18454 InClassInitStyle InitStyle,
18455 AccessSpecifier AS,
18456 const ParsedAttr &MSPropertyAttr) {
18457 IdentifierInfo *II = D.getIdentifier();
18458 if (!II) {
18459 Diag(DeclStart, diag::err_anonymous_property);
18460 return nullptr;
18461 }
18462 SourceLocation Loc = D.getIdentifierLoc();
18463
18464 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18465 QualType T = TInfo->getType();
18466 if (getLangOpts().CPlusPlus) {
18467 CheckExtraCXXDefaultArguments(D);
18468
18469 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18470 UPPC_DataMemberType)) {
18471 D.setInvalidType();
18472 T = Context.IntTy;
18473 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18474 }
18475 }
18476
18477 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18478
18479 if (D.getDeclSpec().isInlineSpecified())
18480 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18481 << getLangOpts().CPlusPlus17;
18482 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18483 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18484 diag::err_invalid_thread)
18485 << DeclSpec::getSpecifierName(TSCS);
18486
18487 // Check to see if this name was declared as a member previously
18488 NamedDecl *PrevDecl = nullptr;
18489 LookupResult Previous(*this, II, Loc, LookupMemberName,
18490 ForVisibleRedeclaration);
18491 LookupName(Previous, S);
18492 switch (Previous.getResultKind()) {
18493 case LookupResult::Found:
18494 case LookupResult::FoundUnresolvedValue:
18495 PrevDecl = Previous.getAsSingle<NamedDecl>();
18496 break;
18497
18498 case LookupResult::FoundOverloaded:
18499 PrevDecl = Previous.getRepresentativeDecl();
18500 break;
18501
18502 case LookupResult::NotFound:
18503 case LookupResult::NotFoundInCurrentInstantiation:
18504 case LookupResult::Ambiguous:
18505 break;
18506 }
18507
18508 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18509 // Maybe we will complain about the shadowed template parameter.
18510 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18511 // Just pretend that we didn't see the previous declaration.
18512 PrevDecl = nullptr;
18513 }
18514
18515 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18516 PrevDecl = nullptr;
18517
18518 SourceLocation TSSL = D.getBeginLoc();
18519 MSPropertyDecl *NewPD =
18520 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18521 MSPropertyAttr.getPropertyDataGetter(),
18522 MSPropertyAttr.getPropertyDataSetter());
18523 ProcessDeclAttributes(TUScope, NewPD, D);
18524 NewPD->setAccess(AS);
18525
18526 if (NewPD->isInvalidDecl())
18527 Record->setInvalidDecl();
18528
18529 if (D.getDeclSpec().isModulePrivateSpecified())
18530 NewPD->setModulePrivate();
18531
18532 if (NewPD->isInvalidDecl() && PrevDecl) {
18533 // Don't introduce NewFD into scope; there's already something
18534 // with the same name in the same scope.
18535 } else if (II) {
18536 PushOnScopeChains(NewPD, S);
18537 } else
18538 Record->addDecl(NewPD);
18539
18540 return NewPD;
18541}
18542
18543void Sema::ActOnStartFunctionDeclarationDeclarator(
18544 Declarator &Declarator, unsigned TemplateParameterDepth) {
18545 auto &Info = InventedParameterInfos.emplace_back();
18546 TemplateParameterList *ExplicitParams = nullptr;
18547 ArrayRef<TemplateParameterList *> ExplicitLists =
18548 Declarator.getTemplateParameterLists();
18549 if (!ExplicitLists.empty()) {
18550 bool IsMemberSpecialization, IsInvalid;
18551 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18552 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
18553 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18554 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18555 /*SuppressDiagnostic=*/true);
18556 }
18557 if (ExplicitParams) {
18558 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18559 llvm::append_range(Info.TemplateParams, *ExplicitParams);
18560 Info.NumExplicitTemplateParams = ExplicitParams->size();
18561 } else {
18562 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18563 Info.NumExplicitTemplateParams = 0;
18564 }
18565}
18566
18567void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
18568 auto &FSI = InventedParameterInfos.back();
18569 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18570 if (FSI.NumExplicitTemplateParams != 0) {
18571 TemplateParameterList *ExplicitParams =
18572 Declarator.getTemplateParameterLists().back();
18573 Declarator.setInventedTemplateParameterList(
18574 TemplateParameterList::Create(
18575 Context, ExplicitParams->getTemplateLoc(),
18576 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18577 ExplicitParams->getRAngleLoc(),
18578 ExplicitParams->getRequiresClause()));
18579 } else {
18580 Declarator.setInventedTemplateParameterList(
18581 TemplateParameterList::Create(
18582 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18583 SourceLocation(), /*RequiresClause=*/nullptr));
18584 }
18585 }
18586 InventedParameterInfos.pop_back();
18587}