Bug Summary

File:clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 14915, column 21
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 -disable-llvm-verifier -discard-value-names -main-file-name SemaDeclCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../x86_64-linux-gnu/include -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-2021-04-05-202135-9119-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/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/EvaluatedExprVisitor.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/AST/RecursiveASTVisitor.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/AST/TypeLoc.h"
26#include "clang/AST/TypeOrdering.h"
27#include "clang/Basic/AttributeCommonInfo.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/LiteralSupport.h"
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
39#include "clang/Sema/SemaInternal.h"
40#include "clang/Sema/Template.h"
41#include "llvm/ADT/ScopeExit.h"
42#include "llvm/ADT/SmallString.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/StringExtras.h"
45#include <map>
46#include <set>
47
48using namespace clang;
49
50//===----------------------------------------------------------------------===//
51// CheckDefaultArgumentVisitor
52//===----------------------------------------------------------------------===//
53
54namespace {
55/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
56/// the default argument of a parameter to determine whether it
57/// contains any ill-formed subexpressions. For example, this will
58/// diagnose the use of local variables or parameters within the
59/// default argument expression.
60class CheckDefaultArgumentVisitor
61 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
62 Sema &S;
63 const Expr *DefaultArg;
64
65public:
66 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
67 : S(S), DefaultArg(DefaultArg) {}
68
69 bool VisitExpr(const Expr *Node);
70 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
71 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
72 bool VisitLambdaExpr(const LambdaExpr *Lambda);
73 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
74};
75
76/// VisitExpr - Visit all of the children of this expression.
77bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
78 bool IsInvalid = false;
79 for (const Stmt *SubStmt : Node->children())
80 IsInvalid |= Visit(SubStmt);
81 return IsInvalid;
82}
83
84/// VisitDeclRefExpr - Visit a reference to a declaration, to
85/// determine whether this declaration can be used in the default
86/// argument expression.
87bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
88 const NamedDecl *Decl = DRE->getDecl();
89 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
90 // C++ [dcl.fct.default]p9:
91 // [...] parameters of a function shall not be used in default
92 // argument expressions, even if they are not evaluated. [...]
93 //
94 // C++17 [dcl.fct.default]p9 (by CWG 2082):
95 // [...] A parameter shall not appear as a potentially-evaluated
96 // expression in a default argument. [...]
97 //
98 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
99 return S.Diag(DRE->getBeginLoc(),
100 diag::err_param_default_argument_references_param)
101 << Param->getDeclName() << DefaultArg->getSourceRange();
102 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
103 // C++ [dcl.fct.default]p7:
104 // Local variables shall not be used in default argument
105 // expressions.
106 //
107 // C++17 [dcl.fct.default]p7 (by CWG 2082):
108 // A local variable shall not appear as a potentially-evaluated
109 // expression in a default argument.
110 //
111 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
112 // Note: A local variable cannot be odr-used (6.3) in a default argument.
113 //
114 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
115 return S.Diag(DRE->getBeginLoc(),
116 diag::err_param_default_argument_references_local)
117 << VDecl->getDeclName() << DefaultArg->getSourceRange();
118 }
119
120 return false;
121}
122
123/// VisitCXXThisExpr - Visit a C++ "this" expression.
124bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
125 // C++ [dcl.fct.default]p8:
126 // The keyword this shall not be used in a default argument of a
127 // member function.
128 return S.Diag(ThisE->getBeginLoc(),
129 diag::err_param_default_argument_references_this)
130 << ThisE->getSourceRange();
131}
132
133bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
134 const PseudoObjectExpr *POE) {
135 bool Invalid = false;
136 for (const Expr *E : POE->semantics()) {
137 // Look through bindings.
138 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
139 E = OVE->getSourceExpr();
140 assert(E && "pseudo-object binding without source expression?")((E && "pseudo-object binding without source expression?"
) ? static_cast<void> (0) : __assert_fail ("E && \"pseudo-object binding without source expression?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 140, __PRETTY_FUNCTION__))
;
141 }
142
143 Invalid |= Visit(E);
144 }
145 return Invalid;
146}
147
148bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
149 // C++11 [expr.lambda.prim]p13:
150 // A lambda-expression appearing in a default argument shall not
151 // implicitly or explicitly capture any entity.
152 if (Lambda->capture_begin() == Lambda->capture_end())
153 return false;
154
155 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
156}
157} // namespace
158
159void
160Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
161 const CXXMethodDecl *Method) {
162 // If we have an MSAny spec already, don't bother.
163 if (!Method || ComputedEST == EST_MSAny)
164 return;
165
166 const FunctionProtoType *Proto
167 = Method->getType()->getAs<FunctionProtoType>();
168 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
169 if (!Proto)
170 return;
171
172 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
173
174 // If we have a throw-all spec at this point, ignore the function.
175 if (ComputedEST == EST_None)
176 return;
177
178 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
179 EST = EST_BasicNoexcept;
180
181 switch (EST) {
182 case EST_Unparsed:
183 case EST_Uninstantiated:
184 case EST_Unevaluated:
185 llvm_unreachable("should not see unresolved exception specs here")::llvm::llvm_unreachable_internal("should not see unresolved exception specs here"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 185)
;
186
187 // If this function can throw any exceptions, make a note of that.
188 case EST_MSAny:
189 case EST_None:
190 // FIXME: Whichever we see last of MSAny and None determines our result.
191 // We should make a consistent, order-independent choice here.
192 ClearExceptions();
193 ComputedEST = EST;
194 return;
195 case EST_NoexceptFalse:
196 ClearExceptions();
197 ComputedEST = EST_None;
198 return;
199 // FIXME: If the call to this decl is using any of its default arguments, we
200 // need to search them for potentially-throwing calls.
201 // If this function has a basic noexcept, it doesn't affect the outcome.
202 case EST_BasicNoexcept:
203 case EST_NoexceptTrue:
204 case EST_NoThrow:
205 return;
206 // If we're still at noexcept(true) and there's a throw() callee,
207 // change to that specification.
208 case EST_DynamicNone:
209 if (ComputedEST == EST_BasicNoexcept)
210 ComputedEST = EST_DynamicNone;
211 return;
212 case EST_DependentNoexcept:
213 llvm_unreachable(::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 214)
214 "should not generate implicit declarations for dependent cases")::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 214)
;
215 case EST_Dynamic:
216 break;
217 }
218 assert(EST == EST_Dynamic && "EST case not considered earlier.")((EST == EST_Dynamic && "EST case not considered earlier."
) ? static_cast<void> (0) : __assert_fail ("EST == EST_Dynamic && \"EST case not considered earlier.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 218, __PRETTY_FUNCTION__))
;
219 assert(ComputedEST != EST_None &&((ComputedEST != EST_None && "Shouldn't collect exceptions when throw-all is guaranteed."
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 220, __PRETTY_FUNCTION__))
220 "Shouldn't collect exceptions when throw-all is guaranteed.")((ComputedEST != EST_None && "Shouldn't collect exceptions when throw-all is guaranteed."
) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 220, __PRETTY_FUNCTION__))
;
221 ComputedEST = EST_Dynamic;
222 // Record the exceptions in this function's exception specification.
223 for (const auto &E : Proto->exceptions())
224 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
225 Exceptions.push_back(E);
226}
227
228void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
229 if (!S || ComputedEST == EST_MSAny)
230 return;
231
232 // FIXME:
233 //
234 // C++0x [except.spec]p14:
235 // [An] implicit exception-specification specifies the type-id T if and
236 // only if T is allowed by the exception-specification of a function directly
237 // invoked by f's implicit definition; f shall allow all exceptions if any
238 // function it directly invokes allows all exceptions, and f shall allow no
239 // exceptions if every function it directly invokes allows no exceptions.
240 //
241 // Note in particular that if an implicit exception-specification is generated
242 // for a function containing a throw-expression, that specification can still
243 // be noexcept(true).
244 //
245 // Note also that 'directly invoked' is not defined in the standard, and there
246 // is no indication that we should only consider potentially-evaluated calls.
247 //
248 // Ultimately we should implement the intent of the standard: the exception
249 // specification should be the set of exceptions which can be thrown by the
250 // implicit definition. For now, we assume that any non-nothrow expression can
251 // throw any exception.
252
253 if (Self->canThrow(S))
254 ComputedEST = EST_None;
255}
256
257ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
258 SourceLocation EqualLoc) {
259 if (RequireCompleteType(Param->getLocation(), Param->getType(),
260 diag::err_typecheck_decl_incomplete_type))
261 return true;
262
263 // C++ [dcl.fct.default]p5
264 // A default argument expression is implicitly converted (clause
265 // 4) to the parameter type. The default argument expression has
266 // the same semantic constraints as the initializer expression in
267 // a declaration of a variable of the parameter type, using the
268 // copy-initialization semantics (8.5).
269 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
270 Param);
271 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
272 EqualLoc);
273 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
274 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
275 if (Result.isInvalid())
276 return true;
277 Arg = Result.getAs<Expr>();
278
279 CheckCompletedExpr(Arg, EqualLoc);
280 Arg = MaybeCreateExprWithCleanups(Arg);
281
282 return Arg;
283}
284
285void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
286 SourceLocation EqualLoc) {
287 // Add the default argument to the parameter
288 Param->setDefaultArg(Arg);
289
290 // We have already instantiated this parameter; provide each of the
291 // instantiations with the uninstantiated default argument.
292 UnparsedDefaultArgInstantiationsMap::iterator InstPos
293 = UnparsedDefaultArgInstantiations.find(Param);
294 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
295 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
296 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
297
298 // We're done tracking this parameter's instantiations.
299 UnparsedDefaultArgInstantiations.erase(InstPos);
300 }
301}
302
303/// ActOnParamDefaultArgument - Check whether the default argument
304/// provided for a function parameter is well-formed. If so, attach it
305/// to the parameter declaration.
306void
307Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
308 Expr *DefaultArg) {
309 if (!param || !DefaultArg)
310 return;
311
312 ParmVarDecl *Param = cast<ParmVarDecl>(param);
313 UnparsedDefaultArgLocs.erase(Param);
314
315 auto Fail = [&] {
316 Param->setInvalidDecl();
317 Param->setDefaultArg(new (Context) OpaqueValueExpr(
318 EqualLoc, Param->getType().getNonReferenceType(), VK_RValue));
319 };
320
321 // Default arguments are only permitted in C++
322 if (!getLangOpts().CPlusPlus) {
323 Diag(EqualLoc, diag::err_param_default_argument)
324 << DefaultArg->getSourceRange();
325 return Fail();
326 }
327
328 // Check for unexpanded parameter packs.
329 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
330 return Fail();
331 }
332
333 // C++11 [dcl.fct.default]p3
334 // A default argument expression [...] shall not be specified for a
335 // parameter pack.
336 if (Param->isParameterPack()) {
337 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
338 << DefaultArg->getSourceRange();
339 // Recover by discarding the default argument.
340 Param->setDefaultArg(nullptr);
341 return;
342 }
343
344 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
345 if (Result.isInvalid())
346 return Fail();
347
348 DefaultArg = Result.getAs<Expr>();
349
350 // Check that the default argument is well-formed
351 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
352 if (DefaultArgChecker.Visit(DefaultArg))
353 return Fail();
354
355 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
356}
357
358/// ActOnParamUnparsedDefaultArgument - We've seen a default
359/// argument for a function parameter, but we can't parse it yet
360/// because we're inside a class definition. Note that this default
361/// argument will be parsed later.
362void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
363 SourceLocation EqualLoc,
364 SourceLocation ArgLoc) {
365 if (!param)
366 return;
367
368 ParmVarDecl *Param = cast<ParmVarDecl>(param);
369 Param->setUnparsedDefaultArg();
370 UnparsedDefaultArgLocs[Param] = ArgLoc;
371}
372
373/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
374/// the default argument for the parameter param failed.
375void Sema::ActOnParamDefaultArgumentError(Decl *param,
376 SourceLocation EqualLoc) {
377 if (!param)
378 return;
379
380 ParmVarDecl *Param = cast<ParmVarDecl>(param);
381 Param->setInvalidDecl();
382 UnparsedDefaultArgLocs.erase(Param);
383 Param->setDefaultArg(new(Context)
384 OpaqueValueExpr(EqualLoc,
385 Param->getType().getNonReferenceType(),
386 VK_RValue));
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 std::any_of(FD->param_begin(), FD->param_end(), [](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())((NewParam->hasDefaultArg()) ? static_cast<void> (0)
: __assert_fail ("NewParam->hasDefaultArg()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 644, __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())((D.isDecompositionDeclarator()) ? static_cast<void> (0
) : __assert_fail ("D.isDecompositionDeclarator()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 714, __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)) << NumElems.toString(10)
914 << (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 SmallString<128> SS;
981 llvm::raw_svector_ostream OS(SS);
982 bool First = true;
983 for (auto &Arg : Args.arguments()) {
984 if (!First)
985 OS << ", ";
986 Arg.getArgument().print(PrintingPolicy, OS);
987 First = false;
988 }
989 return std::string(OS.str());
990}
991
992static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
993 SourceLocation Loc, StringRef Trait,
994 TemplateArgumentListInfo &Args,
995 unsigned DiagID) {
996 auto DiagnoseMissing = [&] {
997 if (DiagID)
998 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
999 Args);
1000 return true;
1001 };
1002
1003 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1004 NamespaceDecl *Std = S.getStdNamespace();
1005 if (!Std)
1006 return DiagnoseMissing();
1007
1008 // Look up the trait itself, within namespace std. We can diagnose various
1009 // problems with this lookup even if we've been asked to not diagnose a
1010 // missing specialization, because this can only fail if the user has been
1011 // declaring their own names in namespace std or we don't support the
1012 // standard library implementation in use.
1013 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1014 Loc, Sema::LookupOrdinaryName);
1015 if (!S.LookupQualifiedName(Result, Std))
1016 return DiagnoseMissing();
1017 if (Result.isAmbiguous())
1018 return true;
1019
1020 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1021 if (!TraitTD) {
1022 Result.suppressDiagnostics();
1023 NamedDecl *Found = *Result.begin();
1024 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1025 S.Diag(Found->getLocation(), diag::note_declared_at);
1026 return true;
1027 }
1028
1029 // Build the template-id.
1030 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1031 if (TraitTy.isNull())
1032 return true;
1033 if (!S.isCompleteType(Loc, TraitTy)) {
1034 if (DiagID)
1035 S.RequireCompleteType(
1036 Loc, TraitTy, DiagID,
1037 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
1038 return true;
1039 }
1040
1041 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1042 assert(RD && "specialization of class template is not a class?")((RD && "specialization of class template is not a class?"
) ? static_cast<void> (0) : __assert_fail ("RD && \"specialization of class template is not a class?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 1042, __PRETTY_FUNCTION__))
;
1043
1044 // Look up the member of the trait type.
1045 S.LookupQualifiedName(TraitMemberLookup, RD);
1046 return TraitMemberLookup.isAmbiguous();
1047}
1048
1049static TemplateArgumentLoc
1050getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1051 uint64_t I) {
1052 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1053 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1054}
1055
1056static TemplateArgumentLoc
1057getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1058 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1059}
1060
1061namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1062
1063static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1064 llvm::APSInt &Size) {
1065 EnterExpressionEvaluationContext ContextRAII(
1066 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1067
1068 DeclarationName Value = S.PP.getIdentifierInfo("value");
1069 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1070
1071 // Form template argument list for tuple_size<T>.
1072 TemplateArgumentListInfo Args(Loc, Loc);
1073 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1074
1075 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1076 // it's not tuple-like.
1077 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1078 R.empty())
1079 return IsTupleLike::NotTupleLike;
1080
1081 // If we get this far, we've committed to the tuple interpretation, but
1082 // we can still fail if there actually isn't a usable ::value.
1083
1084 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1085 LookupResult &R;
1086 TemplateArgumentListInfo &Args;
1087 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1088 : R(R), Args(Args) {}
1089 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1090 SourceLocation Loc) override {
1091 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1092 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1093 }
1094 } Diagnoser(R, Args);
1095
1096 ExprResult E =
1097 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1098 if (E.isInvalid())
1099 return IsTupleLike::Error;
1100
1101 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1102 if (E.isInvalid())
1103 return IsTupleLike::Error;
1104
1105 return IsTupleLike::TupleLike;
1106}
1107
1108/// \return std::tuple_element<I, T>::type.
1109static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1110 unsigned I, QualType T) {
1111 // Form template argument list for tuple_element<I, T>.
1112 TemplateArgumentListInfo Args(Loc, Loc);
1113 Args.addArgument(
1114 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1115 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1116
1117 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1118 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1119 if (lookupStdTypeTraitMember(
1120 S, R, Loc, "tuple_element", Args,
1121 diag::err_decomp_decl_std_tuple_element_not_specialized))
1122 return QualType();
1123
1124 auto *TD = R.getAsSingle<TypeDecl>();
1125 if (!TD) {
1126 R.suppressDiagnostics();
1127 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1128 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1129 if (!R.empty())
1130 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1131 return QualType();
1132 }
1133
1134 return S.Context.getTypeDeclType(TD);
1135}
1136
1137namespace {
1138struct InitializingBinding {
1139 Sema &S;
1140 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1141 Sema::CodeSynthesisContext Ctx;
1142 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1143 Ctx.PointOfInstantiation = BD->getLocation();
1144 Ctx.Entity = BD;
1145 S.pushCodeSynthesisContext(Ctx);
1146 }
1147 ~InitializingBinding() {
1148 S.popCodeSynthesisContext();
1149 }
1150};
1151}
1152
1153static bool checkTupleLikeDecomposition(Sema &S,
1154 ArrayRef<BindingDecl *> Bindings,
1155 VarDecl *Src, QualType DecompType,
1156 const llvm::APSInt &TupleSize) {
1157 if ((int64_t)Bindings.size() != TupleSize) {
1158 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1159 << DecompType << (unsigned)Bindings.size()
1160 << (unsigned)TupleSize.getLimitedValue(UINT_MAX(2147483647 *2U +1U))
1161 << TupleSize.toString(10) << (TupleSize < Bindings.size());
1162 return true;
1163 }
1164
1165 if (Bindings.empty())
1166 return false;
1167
1168 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1169
1170 // [dcl.decomp]p3:
1171 // The unqualified-id get is looked up in the scope of E by class member
1172 // access lookup ...
1173 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1174 bool UseMemberGet = false;
1175 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1176 if (auto *RD = DecompType->getAsCXXRecordDecl())
1177 S.LookupQualifiedName(MemberGet, RD);
1178 if (MemberGet.isAmbiguous())
1179 return true;
1180 // ... and if that finds at least one declaration that is a function
1181 // template whose first template parameter is a non-type parameter ...
1182 for (NamedDecl *D : MemberGet) {
1183 if (FunctionTemplateDecl *FTD =
1184 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1185 TemplateParameterList *TPL = FTD->getTemplateParameters();
1186 if (TPL->size() != 0 &&
1187 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1188 // ... the initializer is e.get<i>().
1189 UseMemberGet = true;
1190 break;
1191 }
1192 }
1193 }
1194 }
1195
1196 unsigned I = 0;
1197 for (auto *B : Bindings) {
1198 InitializingBinding InitContext(S, B);
1199 SourceLocation Loc = B->getLocation();
1200
1201 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1202 if (E.isInvalid())
1203 return true;
1204
1205 // e is an lvalue if the type of the entity is an lvalue reference and
1206 // an xvalue otherwise
1207 if (!Src->getType()->isLValueReferenceType())
1208 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1209 E.get(), nullptr, VK_XValue,
1210 FPOptionsOverride());
1211
1212 TemplateArgumentListInfo Args(Loc, Loc);
1213 Args.addArgument(
1214 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1215
1216 if (UseMemberGet) {
1217 // if [lookup of member get] finds at least one declaration, the
1218 // initializer is e.get<i-1>().
1219 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1220 CXXScopeSpec(), SourceLocation(), nullptr,
1221 MemberGet, &Args, nullptr);
1222 if (E.isInvalid())
1223 return true;
1224
1225 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1226 } else {
1227 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1228 // in the associated namespaces.
1229 Expr *Get = UnresolvedLookupExpr::Create(
1230 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1231 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1232 UnresolvedSetIterator(), UnresolvedSetIterator());
1233
1234 Expr *Arg = E.get();
1235 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1236 }
1237 if (E.isInvalid())
1238 return true;
1239 Expr *Init = E.get();
1240
1241 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1242 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1243 if (T.isNull())
1244 return true;
1245
1246 // each vi is a variable of type "reference to T" initialized with the
1247 // initializer, where the reference is an lvalue reference if the
1248 // initializer is an lvalue and an rvalue reference otherwise
1249 QualType RefType =
1250 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1251 if (RefType.isNull())
1252 return true;
1253 auto *RefVD = VarDecl::Create(
1254 S.Context, Src->getDeclContext(), Loc, Loc,
1255 B->getDeclName().getAsIdentifierInfo(), RefType,
1256 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1257 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1258 RefVD->setTSCSpec(Src->getTSCSpec());
1259 RefVD->setImplicit();
1260 if (Src->isInlineSpecified())
1261 RefVD->setInlineSpecified();
1262 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1263
1264 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1265 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1266 InitializationSequence Seq(S, Entity, Kind, Init);
1267 E = Seq.Perform(S, Entity, Kind, Init);
1268 if (E.isInvalid())
1269 return true;
1270 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1271 if (E.isInvalid())
1272 return true;
1273 RefVD->setInit(E.get());
1274 S.CheckCompleteVariableDeclaration(RefVD);
1275
1276 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1277 DeclarationNameInfo(B->getDeclName(), Loc),
1278 RefVD);
1279 if (E.isInvalid())
1280 return true;
1281
1282 B->setBinding(T, E.get());
1283 I++;
1284 }
1285
1286 return false;
1287}
1288
1289/// Find the base class to decompose in a built-in decomposition of a class type.
1290/// This base class search is, unfortunately, not quite like any other that we
1291/// perform anywhere else in C++.
1292static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1293 const CXXRecordDecl *RD,
1294 CXXCastPath &BasePath) {
1295 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1296 CXXBasePath &Path) {
1297 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1298 };
1299
1300 const CXXRecordDecl *ClassWithFields = nullptr;
1301 AccessSpecifier AS = AS_public;
1302 if (RD->hasDirectFields())
1303 // [dcl.decomp]p4:
1304 // Otherwise, all of E's non-static data members shall be public direct
1305 // members of E ...
1306 ClassWithFields = RD;
1307 else {
1308 // ... or of ...
1309 CXXBasePaths Paths;
1310 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1311 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1312 // If no classes have fields, just decompose RD itself. (This will work
1313 // if and only if zero bindings were provided.)
1314 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1315 }
1316
1317 CXXBasePath *BestPath = nullptr;
1318 for (auto &P : Paths) {
1319 if (!BestPath)
1320 BestPath = &P;
1321 else if (!S.Context.hasSameType(P.back().Base->getType(),
1322 BestPath->back().Base->getType())) {
1323 // ... the same ...
1324 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1325 << false << RD << BestPath->back().Base->getType()
1326 << P.back().Base->getType();
1327 return DeclAccessPair();
1328 } else if (P.Access < BestPath->Access) {
1329 BestPath = &P;
1330 }
1331 }
1332
1333 // ... unambiguous ...
1334 QualType BaseType = BestPath->back().Base->getType();
1335 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1336 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1337 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1338 return DeclAccessPair();
1339 }
1340
1341 // ... [accessible, implied by other rules] base class of E.
1342 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1343 *BestPath, diag::err_decomp_decl_inaccessible_base);
1344 AS = BestPath->Access;
1345
1346 ClassWithFields = BaseType->getAsCXXRecordDecl();
1347 S.BuildBasePathArray(Paths, BasePath);
1348 }
1349
1350 // The above search did not check whether the selected class itself has base
1351 // classes with fields, so check that now.
1352 CXXBasePaths Paths;
1353 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1354 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1355 << (ClassWithFields == RD) << RD << ClassWithFields
1356 << Paths.front().back().Base->getType();
1357 return DeclAccessPair();
1358 }
1359
1360 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1361}
1362
1363static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1364 ValueDecl *Src, QualType DecompType,
1365 const CXXRecordDecl *OrigRD) {
1366 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1367 diag::err_incomplete_type))
1368 return true;
1369
1370 CXXCastPath BasePath;
1371 DeclAccessPair BasePair =
1372 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1373 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1374 if (!RD)
1375 return true;
1376 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1377 DecompType.getQualifiers());
1378
1379 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1380 unsigned NumFields =
1381 std::count_if(RD->field_begin(), RD->field_end(),
1382 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1383 assert(Bindings.size() != NumFields)((Bindings.size() != NumFields) ? static_cast<void> (0)
: __assert_fail ("Bindings.size() != NumFields", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 1383, __PRETTY_FUNCTION__))
;
1384 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1385 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1386 << (NumFields < Bindings.size());
1387 return true;
1388 };
1389
1390 // all of E's non-static data members shall be [...] well-formed
1391 // when named as e.name in the context of the structured binding,
1392 // E shall not have an anonymous union member, ...
1393 unsigned I = 0;
1394 for (auto *FD : RD->fields()) {
1395 if (FD->isUnnamedBitfield())
1396 continue;
1397
1398 // All the non-static data members are required to be nameable, so they
1399 // must all have names.
1400 if (!FD->getDeclName()) {
1401 if (RD->isLambda()) {
1402 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1403 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1404 return true;
1405 }
1406
1407 if (FD->isAnonymousStructOrUnion()) {
1408 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1409 << DecompType << FD->getType()->isUnionType();
1410 S.Diag(FD->getLocation(), diag::note_declared_at);
1411 return true;
1412 }
1413
1414 // FIXME: Are there any other ways we could have an anonymous member?
1415 }
1416
1417 // We have a real field to bind.
1418 if (I >= Bindings.size())
1419 return DiagnoseBadNumberOfBindings();
1420 auto *B = Bindings[I++];
1421 SourceLocation Loc = B->getLocation();
1422
1423 // The field must be accessible in the context of the structured binding.
1424 // We already checked that the base class is accessible.
1425 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1426 // const_cast here.
1427 S.CheckStructuredBindingMemberAccess(
1428 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1429 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1430 BasePair.getAccess(), FD->getAccess())));
1431
1432 // Initialize the binding to Src.FD.
1433 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1434 if (E.isInvalid())
1435 return true;
1436 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1437 VK_LValue, &BasePath);
1438 if (E.isInvalid())
1439 return true;
1440 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1441 CXXScopeSpec(), FD,
1442 DeclAccessPair::make(FD, FD->getAccess()),
1443 DeclarationNameInfo(FD->getDeclName(), Loc));
1444 if (E.isInvalid())
1445 return true;
1446
1447 // If the type of the member is T, the referenced type is cv T, where cv is
1448 // the cv-qualification of the decomposition expression.
1449 //
1450 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1451 // 'const' to the type of the field.
1452 Qualifiers Q = DecompType.getQualifiers();
1453 if (FD->isMutable())
1454 Q.removeConst();
1455 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1456 }
1457
1458 if (I != Bindings.size())
1459 return DiagnoseBadNumberOfBindings();
1460
1461 return false;
1462}
1463
1464void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1465 QualType DecompType = DD->getType();
1466
1467 // If the type of the decomposition is dependent, then so is the type of
1468 // each binding.
1469 if (DecompType->isDependentType()) {
1470 for (auto *B : DD->bindings())
1471 B->setType(Context.DependentTy);
1472 return;
1473 }
1474
1475 DecompType = DecompType.getNonReferenceType();
1476 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1477
1478 // C++1z [dcl.decomp]/2:
1479 // If E is an array type [...]
1480 // As an extension, we also support decomposition of built-in complex and
1481 // vector types.
1482 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1483 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1484 DD->setInvalidDecl();
1485 return;
1486 }
1487 if (auto *VT = DecompType->getAs<VectorType>()) {
1488 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1489 DD->setInvalidDecl();
1490 return;
1491 }
1492 if (auto *CT = DecompType->getAs<ComplexType>()) {
1493 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1494 DD->setInvalidDecl();
1495 return;
1496 }
1497
1498 // C++1z [dcl.decomp]/3:
1499 // if the expression std::tuple_size<E>::value is a well-formed integral
1500 // constant expression, [...]
1501 llvm::APSInt TupleSize(32);
1502 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1503 case IsTupleLike::Error:
1504 DD->setInvalidDecl();
1505 return;
1506
1507 case IsTupleLike::TupleLike:
1508 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1509 DD->setInvalidDecl();
1510 return;
1511
1512 case IsTupleLike::NotTupleLike:
1513 break;
1514 }
1515
1516 // C++1z [dcl.dcl]/8:
1517 // [E shall be of array or non-union class type]
1518 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1519 if (!RD || RD->isUnion()) {
1520 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1521 << DD << !RD << DecompType;
1522 DD->setInvalidDecl();
1523 return;
1524 }
1525
1526 // C++1z [dcl.decomp]/4:
1527 // all of E's non-static data members shall be [...] direct members of
1528 // E or of the same unambiguous public base class of E, ...
1529 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1530 DD->setInvalidDecl();
1531}
1532
1533/// Merge the exception specifications of two variable declarations.
1534///
1535/// This is called when there's a redeclaration of a VarDecl. The function
1536/// checks if the redeclaration might have an exception specification and
1537/// validates compatibility and merges the specs if necessary.
1538void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1539 // Shortcut if exceptions are disabled.
1540 if (!getLangOpts().CXXExceptions)
1541 return;
1542
1543 assert(Context.hasSameType(New->getType(), Old->getType()) &&((Context.hasSameType(New->getType(), Old->getType()) &&
"Should only be called if types are otherwise the same.") ? static_cast
<void> (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 1544, __PRETTY_FUNCTION__))
1544 "Should only be called if types are otherwise the same.")((Context.hasSameType(New->getType(), Old->getType()) &&
"Should only be called if types are otherwise the same.") ? static_cast
<void> (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 1544, __PRETTY_FUNCTION__))
;
1545
1546 QualType NewType = New->getType();
1547 QualType OldType = Old->getType();
1548
1549 // We're only interested in pointers and references to functions, as well
1550 // as pointers to member functions.
1551 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1552 NewType = R->getPointeeType();
1553 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1554 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1555 NewType = P->getPointeeType();
1556 OldType = OldType->castAs<PointerType>()->getPointeeType();
1557 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1558 NewType = M->getPointeeType();
1559 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1560 }
1561
1562 if (!NewType->isFunctionProtoType())
1563 return;
1564
1565 // There's lots of special cases for functions. For function pointers, system
1566 // libraries are hopefully not as broken so that we don't need these
1567 // workarounds.
1568 if (CheckEquivalentExceptionSpec(
1569 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1570 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1571 New->setInvalidDecl();
1572 }
1573}
1574
1575/// CheckCXXDefaultArguments - Verify that the default arguments for a
1576/// function declaration are well-formed according to C++
1577/// [dcl.fct.default].
1578void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1579 unsigned NumParams = FD->getNumParams();
1580 unsigned ParamIdx = 0;
1581
1582 // This checking doesn't make sense for explicit specializations; their
1583 // default arguments are determined by the declaration we're specializing,
1584 // not by FD.
1585 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1586 return;
1587 if (auto *FTD = FD->getDescribedFunctionTemplate())
1588 if (FTD->isMemberSpecialization())
1589 return;
1590
1591 // Find first parameter with a default argument
1592 for (; ParamIdx < NumParams; ++ParamIdx) {
1593 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1594 if (Param->hasDefaultArg())
1595 break;
1596 }
1597
1598 // C++20 [dcl.fct.default]p4:
1599 // In a given function declaration, each parameter subsequent to a parameter
1600 // with a default argument shall have a default argument supplied in this or
1601 // a previous declaration, unless the parameter was expanded from a
1602 // parameter pack, or shall be a function parameter pack.
1603 for (; ParamIdx < NumParams; ++ParamIdx) {
1604 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1605 if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1606 !(CurrentInstantiationScope &&
1607 CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1608 if (Param->isInvalidDecl())
1609 /* We already complained about this parameter. */;
1610 else if (Param->getIdentifier())
1611 Diag(Param->getLocation(),
1612 diag::err_param_default_argument_missing_name)
1613 << Param->getIdentifier();
1614 else
1615 Diag(Param->getLocation(),
1616 diag::err_param_default_argument_missing);
1617 }
1618 }
1619}
1620
1621/// Check that the given type is a literal type. Issue a diagnostic if not,
1622/// if Kind is Diagnose.
1623/// \return \c true if a problem has been found (and optionally diagnosed).
1624template <typename... Ts>
1625static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1626 SourceLocation Loc, QualType T, unsigned DiagID,
1627 Ts &&...DiagArgs) {
1628 if (T->isDependentType())
1629 return false;
1630
1631 switch (Kind) {
1632 case Sema::CheckConstexprKind::Diagnose:
1633 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1634 std::forward<Ts>(DiagArgs)...);
1635
1636 case Sema::CheckConstexprKind::CheckValid:
1637 return !T->isLiteralType(SemaRef.Context);
1638 }
1639
1640 llvm_unreachable("unknown CheckConstexprKind")::llvm::llvm_unreachable_internal("unknown CheckConstexprKind"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 1640)
;
1641}
1642
1643/// Determine whether a destructor cannot be constexpr due to
1644static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1645 const CXXDestructorDecl *DD,
1646 Sema::CheckConstexprKind Kind) {
1647 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1648 const CXXRecordDecl *RD =
1649 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1650 if (!RD || RD->hasConstexprDestructor())
1651 return true;
1652
1653 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1654 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1655 << static_cast<int>(DD->getConstexprKind()) << !FD
1656 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1657 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1658 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1659 }
1660 return false;
1661 };
1662
1663 const CXXRecordDecl *RD = DD->getParent();
1664 for (const CXXBaseSpecifier &B : RD->bases())
1665 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1666 return false;
1667 for (const FieldDecl *FD : RD->fields())
1668 if (!Check(FD->getLocation(), FD->getType(), FD))
1669 return false;
1670 return true;
1671}
1672
1673/// Check whether a function's parameter types are all literal types. If so,
1674/// return true. If not, produce a suitable diagnostic and return false.
1675static bool CheckConstexprParameterTypes(Sema &SemaRef,
1676 const FunctionDecl *FD,
1677 Sema::CheckConstexprKind Kind) {
1678 unsigned ArgIndex = 0;
1679 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1680 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1681 e = FT->param_type_end();
1682 i != e; ++i, ++ArgIndex) {
1683 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1684 SourceLocation ParamLoc = PD->getLocation();
1685 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1686 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1687 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1688 FD->isConsteval()))
1689 return false;
1690 }
1691 return true;
1692}
1693
1694/// Check whether a function's return type is a literal type. If so, return
1695/// true. If not, produce a suitable diagnostic and return false.
1696static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1697 Sema::CheckConstexprKind Kind) {
1698 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1699 diag::err_constexpr_non_literal_return,
1700 FD->isConsteval()))
1701 return false;
1702 return true;
1703}
1704
1705/// Get diagnostic %select index for tag kind for
1706/// record diagnostic message.
1707/// WARNING: Indexes apply to particular diagnostics only!
1708///
1709/// \returns diagnostic %select index.
1710static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1711 switch (Tag) {
1712 case TTK_Struct: return 0;
1713 case TTK_Interface: return 1;
1714 case TTK_Class: return 2;
1715 default: llvm_unreachable("Invalid tag kind for record diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for record diagnostic!"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 1715)
;
1716 }
1717}
1718
1719static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1720 Stmt *Body,
1721 Sema::CheckConstexprKind Kind);
1722
1723// Check whether a function declaration satisfies the requirements of a
1724// constexpr function definition or a constexpr constructor definition. If so,
1725// return true. If not, produce appropriate diagnostics (unless asked not to by
1726// Kind) and return false.
1727//
1728// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1729bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1730 CheckConstexprKind Kind) {
1731 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1732 if (MD && MD->isInstance()) {
1733 // C++11 [dcl.constexpr]p4:
1734 // The definition of a constexpr constructor shall satisfy the following
1735 // constraints:
1736 // - the class shall not have any virtual base classes;
1737 //
1738 // FIXME: This only applies to constructors and destructors, not arbitrary
1739 // member functions.
1740 const CXXRecordDecl *RD = MD->getParent();
1741 if (RD->getNumVBases()) {
1742 if (Kind == CheckConstexprKind::CheckValid)
1743 return false;
1744
1745 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1746 << isa<CXXConstructorDecl>(NewFD)
1747 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1748 for (const auto &I : RD->vbases())
1749 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1750 << I.getSourceRange();
1751 return false;
1752 }
1753 }
1754
1755 if (!isa<CXXConstructorDecl>(NewFD)) {
1756 // C++11 [dcl.constexpr]p3:
1757 // The definition of a constexpr function shall satisfy the following
1758 // constraints:
1759 // - it shall not be virtual; (removed in C++20)
1760 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1761 if (Method && Method->isVirtual()) {
1762 if (getLangOpts().CPlusPlus20) {
1763 if (Kind == CheckConstexprKind::Diagnose)
1764 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1765 } else {
1766 if (Kind == CheckConstexprKind::CheckValid)
1767 return false;
1768
1769 Method = Method->getCanonicalDecl();
1770 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1771
1772 // If it's not obvious why this function is virtual, find an overridden
1773 // function which uses the 'virtual' keyword.
1774 const CXXMethodDecl *WrittenVirtual = Method;
1775 while (!WrittenVirtual->isVirtualAsWritten())
1776 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1777 if (WrittenVirtual != Method)
1778 Diag(WrittenVirtual->getLocation(),
1779 diag::note_overridden_virtual_function);
1780 return false;
1781 }
1782 }
1783
1784 // - its return type shall be a literal type;
1785 if (!CheckConstexprReturnType(*this, NewFD, Kind))
1786 return false;
1787 }
1788
1789 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1790 // A destructor can be constexpr only if the defaulted destructor could be;
1791 // we don't need to check the members and bases if we already know they all
1792 // have constexpr destructors.
1793 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1794 if (Kind == CheckConstexprKind::CheckValid)
1795 return false;
1796 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1797 return false;
1798 }
1799 }
1800
1801 // - each of its parameter types shall be a literal type;
1802 if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1803 return false;
1804
1805 Stmt *Body = NewFD->getBody();
1806 assert(Body &&((Body && "CheckConstexprFunctionDefinition called on function with no body"
) ? static_cast<void> (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 1807, __PRETTY_FUNCTION__))
1807 "CheckConstexprFunctionDefinition called on function with no body")((Body && "CheckConstexprFunctionDefinition called on function with no body"
) ? static_cast<void> (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 1807, __PRETTY_FUNCTION__))
;
1808 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1809}
1810
1811/// Check the given declaration statement is legal within a constexpr function
1812/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1813///
1814/// \return true if the body is OK (maybe only as an extension), false if we
1815/// have diagnosed a problem.
1816static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1817 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1818 Sema::CheckConstexprKind Kind) {
1819 // C++11 [dcl.constexpr]p3 and p4:
1820 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1821 // contain only
1822 for (const auto *DclIt : DS->decls()) {
1823 switch (DclIt->getKind()) {
1824 case Decl::StaticAssert:
1825 case Decl::Using:
1826 case Decl::UsingShadow:
1827 case Decl::UsingDirective:
1828 case Decl::UnresolvedUsingTypename:
1829 case Decl::UnresolvedUsingValue:
1830 // - static_assert-declarations
1831 // - using-declarations,
1832 // - using-directives,
1833 continue;
1834
1835 case Decl::Typedef:
1836 case Decl::TypeAlias: {
1837 // - typedef declarations and alias-declarations that do not define
1838 // classes or enumerations,
1839 const auto *TN = cast<TypedefNameDecl>(DclIt);
1840 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1841 // Don't allow variably-modified types in constexpr functions.
1842 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1843 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1844 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1845 << TL.getSourceRange() << TL.getType()
1846 << isa<CXXConstructorDecl>(Dcl);
1847 }
1848 return false;
1849 }
1850 continue;
1851 }
1852
1853 case Decl::Enum:
1854 case Decl::CXXRecord:
1855 // C++1y allows types to be defined, not just declared.
1856 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1857 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1858 SemaRef.Diag(DS->getBeginLoc(),
1859 SemaRef.getLangOpts().CPlusPlus14
1860 ? diag::warn_cxx11_compat_constexpr_type_definition
1861 : diag::ext_constexpr_type_definition)
1862 << isa<CXXConstructorDecl>(Dcl);
1863 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1864 return false;
1865 }
1866 }
1867 continue;
1868
1869 case Decl::EnumConstant:
1870 case Decl::IndirectField:
1871 case Decl::ParmVar:
1872 // These can only appear with other declarations which are banned in
1873 // C++11 and permitted in C++1y, so ignore them.
1874 continue;
1875
1876 case Decl::Var:
1877 case Decl::Decomposition: {
1878 // C++1y [dcl.constexpr]p3 allows anything except:
1879 // a definition of a variable of non-literal type or of static or
1880 // thread storage duration or [before C++2a] for which no
1881 // initialization is performed.
1882 const auto *VD = cast<VarDecl>(DclIt);
1883 if (VD->isThisDeclarationADefinition()) {
1884 if (VD->isStaticLocal()) {
1885 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1886 SemaRef.Diag(VD->getLocation(),
1887 diag::err_constexpr_local_var_static)
1888 << isa<CXXConstructorDecl>(Dcl)
1889 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1890 }
1891 return false;
1892 }
1893 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1894 diag::err_constexpr_local_var_non_literal_type,
1895 isa<CXXConstructorDecl>(Dcl)))
1896 return false;
1897 if (!VD->getType()->isDependentType() &&
1898 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1899 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1900 SemaRef.Diag(
1901 VD->getLocation(),
1902 SemaRef.getLangOpts().CPlusPlus20
1903 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1904 : diag::ext_constexpr_local_var_no_init)
1905 << isa<CXXConstructorDecl>(Dcl);
1906 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1907 return false;
1908 }
1909 continue;
1910 }
1911 }
1912 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1913 SemaRef.Diag(VD->getLocation(),
1914 SemaRef.getLangOpts().CPlusPlus14
1915 ? diag::warn_cxx11_compat_constexpr_local_var
1916 : diag::ext_constexpr_local_var)
1917 << isa<CXXConstructorDecl>(Dcl);
1918 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1919 return false;
1920 }
1921 continue;
1922 }
1923
1924 case Decl::NamespaceAlias:
1925 case Decl::Function:
1926 // These are disallowed in C++11 and permitted in C++1y. Allow them
1927 // everywhere as an extension.
1928 if (!Cxx1yLoc.isValid())
1929 Cxx1yLoc = DS->getBeginLoc();
1930 continue;
1931
1932 default:
1933 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1934 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1935 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1936 }
1937 return false;
1938 }
1939 }
1940
1941 return true;
1942}
1943
1944/// Check that the given field is initialized within a constexpr constructor.
1945///
1946/// \param Dcl The constexpr constructor being checked.
1947/// \param Field The field being checked. This may be a member of an anonymous
1948/// struct or union nested within the class being checked.
1949/// \param Inits All declarations, including anonymous struct/union members and
1950/// indirect members, for which any initialization was provided.
1951/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1952/// multiple notes for different members to the same error.
1953/// \param Kind Whether we're diagnosing a constructor as written or determining
1954/// whether the formal requirements are satisfied.
1955/// \return \c false if we're checking for validity and the constructor does
1956/// not satisfy the requirements on a constexpr constructor.
1957static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1958 const FunctionDecl *Dcl,
1959 FieldDecl *Field,
1960 llvm::SmallSet<Decl*, 16> &Inits,
1961 bool &Diagnosed,
1962 Sema::CheckConstexprKind Kind) {
1963 // In C++20 onwards, there's nothing to check for validity.
1964 if (Kind == Sema::CheckConstexprKind::CheckValid &&
1965 SemaRef.getLangOpts().CPlusPlus20)
1966 return true;
1967
1968 if (Field->isInvalidDecl())
1969 return true;
1970
1971 if (Field->isUnnamedBitfield())
1972 return true;
1973
1974 // Anonymous unions with no variant members and empty anonymous structs do not
1975 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1976 // indirect fields don't need initializing.
1977 if (Field->isAnonymousStructOrUnion() &&
1978 (Field->getType()->isUnionType()
1979 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1980 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1981 return true;
1982
1983 if (!Inits.count(Field)) {
1984 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1985 if (!Diagnosed) {
1986 SemaRef.Diag(Dcl->getLocation(),
1987 SemaRef.getLangOpts().CPlusPlus20
1988 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1989 : diag::ext_constexpr_ctor_missing_init);
1990 Diagnosed = true;
1991 }
1992 SemaRef.Diag(Field->getLocation(),
1993 diag::note_constexpr_ctor_missing_init);
1994 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1995 return false;
1996 }
1997 } else if (Field->isAnonymousStructOrUnion()) {
1998 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1999 for (auto *I : RD->fields())
2000 // If an anonymous union contains an anonymous struct of which any member
2001 // is initialized, all members must be initialized.
2002 if (!RD->isUnion() || Inits.count(I))
2003 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2004 Kind))
2005 return false;
2006 }
2007 return true;
2008}
2009
2010/// Check the provided statement is allowed in a constexpr function
2011/// definition.
2012static bool
2013CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2014 SmallVectorImpl<SourceLocation> &ReturnStmts,
2015 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2016 Sema::CheckConstexprKind Kind) {
2017 // - its function-body shall be [...] a compound-statement that contains only
2018 switch (S->getStmtClass()) {
2019 case Stmt::NullStmtClass:
2020 // - null statements,
2021 return true;
2022
2023 case Stmt::DeclStmtClass:
2024 // - static_assert-declarations
2025 // - using-declarations,
2026 // - using-directives,
2027 // - typedef declarations and alias-declarations that do not define
2028 // classes or enumerations,
2029 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2030 return false;
2031 return true;
2032
2033 case Stmt::ReturnStmtClass:
2034 // - and exactly one return statement;
2035 if (isa<CXXConstructorDecl>(Dcl)) {
2036 // C++1y allows return statements in constexpr constructors.
2037 if (!Cxx1yLoc.isValid())
2038 Cxx1yLoc = S->getBeginLoc();
2039 return true;
2040 }
2041
2042 ReturnStmts.push_back(S->getBeginLoc());
2043 return true;
2044
2045 case Stmt::CompoundStmtClass: {
2046 // C++1y allows compound-statements.
2047 if (!Cxx1yLoc.isValid())
2048 Cxx1yLoc = S->getBeginLoc();
2049
2050 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2051 for (auto *BodyIt : CompStmt->body()) {
2052 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2053 Cxx1yLoc, Cxx2aLoc, Kind))
2054 return false;
2055 }
2056 return true;
2057 }
2058
2059 case Stmt::AttributedStmtClass:
2060 if (!Cxx1yLoc.isValid())
2061 Cxx1yLoc = S->getBeginLoc();
2062 return true;
2063
2064 case Stmt::IfStmtClass: {
2065 // C++1y allows if-statements.
2066 if (!Cxx1yLoc.isValid())
2067 Cxx1yLoc = S->getBeginLoc();
2068
2069 IfStmt *If = cast<IfStmt>(S);
2070 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2071 Cxx1yLoc, Cxx2aLoc, Kind))
2072 return false;
2073 if (If->getElse() &&
2074 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2075 Cxx1yLoc, Cxx2aLoc, Kind))
2076 return false;
2077 return true;
2078 }
2079
2080 case Stmt::WhileStmtClass:
2081 case Stmt::DoStmtClass:
2082 case Stmt::ForStmtClass:
2083 case Stmt::CXXForRangeStmtClass:
2084 case Stmt::ContinueStmtClass:
2085 // C++1y allows all of these. We don't allow them as extensions in C++11,
2086 // because they don't make sense without variable mutation.
2087 if (!SemaRef.getLangOpts().CPlusPlus14)
2088 break;
2089 if (!Cxx1yLoc.isValid())
2090 Cxx1yLoc = S->getBeginLoc();
2091 for (Stmt *SubStmt : S->children())
2092 if (SubStmt &&
2093 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2094 Cxx1yLoc, Cxx2aLoc, Kind))
2095 return false;
2096 return true;
2097
2098 case Stmt::SwitchStmtClass:
2099 case Stmt::CaseStmtClass:
2100 case Stmt::DefaultStmtClass:
2101 case Stmt::BreakStmtClass:
2102 // C++1y allows switch-statements, and since they don't need variable
2103 // mutation, we can reasonably allow them in C++11 as an extension.
2104 if (!Cxx1yLoc.isValid())
2105 Cxx1yLoc = S->getBeginLoc();
2106 for (Stmt *SubStmt : S->children())
2107 if (SubStmt &&
2108 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2109 Cxx1yLoc, Cxx2aLoc, Kind))
2110 return false;
2111 return true;
2112
2113 case Stmt::GCCAsmStmtClass:
2114 case Stmt::MSAsmStmtClass:
2115 // C++2a allows inline assembly statements.
2116 case Stmt::CXXTryStmtClass:
2117 if (Cxx2aLoc.isInvalid())
2118 Cxx2aLoc = S->getBeginLoc();
2119 for (Stmt *SubStmt : S->children()) {
2120 if (SubStmt &&
2121 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2122 Cxx1yLoc, Cxx2aLoc, Kind))
2123 return false;
2124 }
2125 return true;
2126
2127 case Stmt::CXXCatchStmtClass:
2128 // Do not bother checking the language mode (already covered by the
2129 // try block check).
2130 if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2131 cast<CXXCatchStmt>(S)->getHandlerBlock(),
2132 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2133 return false;
2134 return true;
2135
2136 default:
2137 if (!isa<Expr>(S))
2138 break;
2139
2140 // C++1y allows expression-statements.
2141 if (!Cxx1yLoc.isValid())
2142 Cxx1yLoc = S->getBeginLoc();
2143 return true;
2144 }
2145
2146 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2147 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2148 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2149 }
2150 return false;
2151}
2152
2153/// Check the body for the given constexpr function declaration only contains
2154/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2155///
2156/// \return true if the body is OK, false if we have found or diagnosed a
2157/// problem.
2158static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2159 Stmt *Body,
2160 Sema::CheckConstexprKind Kind) {
2161 SmallVector<SourceLocation, 4> ReturnStmts;
2162
2163 if (isa<CXXTryStmt>(Body)) {
2164 // C++11 [dcl.constexpr]p3:
2165 // The definition of a constexpr function shall satisfy the following
2166 // constraints: [...]
2167 // - its function-body shall be = delete, = default, or a
2168 // compound-statement
2169 //
2170 // C++11 [dcl.constexpr]p4:
2171 // In the definition of a constexpr constructor, [...]
2172 // - its function-body shall not be a function-try-block;
2173 //
2174 // This restriction is lifted in C++2a, as long as inner statements also
2175 // apply the general constexpr rules.
2176 switch (Kind) {
2177 case Sema::CheckConstexprKind::CheckValid:
2178 if (!SemaRef.getLangOpts().CPlusPlus20)
2179 return false;
2180 break;
2181
2182 case Sema::CheckConstexprKind::Diagnose:
2183 SemaRef.Diag(Body->getBeginLoc(),
2184 !SemaRef.getLangOpts().CPlusPlus20
2185 ? diag::ext_constexpr_function_try_block_cxx20
2186 : diag::warn_cxx17_compat_constexpr_function_try_block)
2187 << isa<CXXConstructorDecl>(Dcl);
2188 break;
2189 }
2190 }
2191
2192 // - its function-body shall be [...] a compound-statement that contains only
2193 // [... list of cases ...]
2194 //
2195 // Note that walking the children here is enough to properly check for
2196 // CompoundStmt and CXXTryStmt body.
2197 SourceLocation Cxx1yLoc, Cxx2aLoc;
2198 for (Stmt *SubStmt : Body->children()) {
2199 if (SubStmt &&
2200 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2201 Cxx1yLoc, Cxx2aLoc, Kind))
2202 return false;
2203 }
2204
2205 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2206 // If this is only valid as an extension, report that we don't satisfy the
2207 // constraints of the current language.
2208 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2209 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2210 return false;
2211 } else if (Cxx2aLoc.isValid()) {
2212 SemaRef.Diag(Cxx2aLoc,
2213 SemaRef.getLangOpts().CPlusPlus20
2214 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2215 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2216 << isa<CXXConstructorDecl>(Dcl);
2217 } else if (Cxx1yLoc.isValid()) {
2218 SemaRef.Diag(Cxx1yLoc,
2219 SemaRef.getLangOpts().CPlusPlus14
2220 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2221 : diag::ext_constexpr_body_invalid_stmt)
2222 << isa<CXXConstructorDecl>(Dcl);
2223 }
2224
2225 if (const CXXConstructorDecl *Constructor
2226 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2227 const CXXRecordDecl *RD = Constructor->getParent();
2228 // DR1359:
2229 // - every non-variant non-static data member and base class sub-object
2230 // shall be initialized;
2231 // DR1460:
2232 // - if the class is a union having variant members, exactly one of them
2233 // shall be initialized;
2234 if (RD->isUnion()) {
2235 if (Constructor->getNumCtorInitializers() == 0 &&
2236 RD->hasVariantMembers()) {
2237 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2238 SemaRef.Diag(
2239 Dcl->getLocation(),
2240 SemaRef.getLangOpts().CPlusPlus20
2241 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2242 : diag::ext_constexpr_union_ctor_no_init);
2243 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2244 return false;
2245 }
2246 }
2247 } else if (!Constructor->isDependentContext() &&
2248 !Constructor->isDelegatingConstructor()) {
2249 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases")((RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"
) ? static_cast<void> (0) : __assert_fail ("RD->getNumVBases() == 0 && \"constexpr ctor with virtual bases\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 2249, __PRETTY_FUNCTION__))
;
2250
2251 // Skip detailed checking if we have enough initializers, and we would
2252 // allow at most one initializer per member.
2253 bool AnyAnonStructUnionMembers = false;
2254 unsigned Fields = 0;
2255 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2256 E = RD->field_end(); I != E; ++I, ++Fields) {
2257 if (I->isAnonymousStructOrUnion()) {
2258 AnyAnonStructUnionMembers = true;
2259 break;
2260 }
2261 }
2262 // DR1460:
2263 // - if the class is a union-like class, but is not a union, for each of
2264 // its anonymous union members having variant members, exactly one of
2265 // them shall be initialized;
2266 if (AnyAnonStructUnionMembers ||
2267 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2268 // Check initialization of non-static data members. Base classes are
2269 // always initialized so do not need to be checked. Dependent bases
2270 // might not have initializers in the member initializer list.
2271 llvm::SmallSet<Decl*, 16> Inits;
2272 for (const auto *I: Constructor->inits()) {
2273 if (FieldDecl *FD = I->getMember())
2274 Inits.insert(FD);
2275 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2276 Inits.insert(ID->chain_begin(), ID->chain_end());
2277 }
2278
2279 bool Diagnosed = false;
2280 for (auto *I : RD->fields())
2281 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2282 Kind))
2283 return false;
2284 }
2285 }
2286 } else {
2287 if (ReturnStmts.empty()) {
2288 // C++1y doesn't require constexpr functions to contain a 'return'
2289 // statement. We still do, unless the return type might be void, because
2290 // otherwise if there's no return statement, the function cannot
2291 // be used in a core constant expression.
2292 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2293 (Dcl->getReturnType()->isVoidType() ||
2294 Dcl->getReturnType()->isDependentType());
2295 switch (Kind) {
2296 case Sema::CheckConstexprKind::Diagnose:
2297 SemaRef.Diag(Dcl->getLocation(),
2298 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2299 : diag::err_constexpr_body_no_return)
2300 << Dcl->isConsteval();
2301 if (!OK)
2302 return false;
2303 break;
2304
2305 case Sema::CheckConstexprKind::CheckValid:
2306 // The formal requirements don't include this rule in C++14, even
2307 // though the "must be able to produce a constant expression" rules
2308 // still imply it in some cases.
2309 if (!SemaRef.getLangOpts().CPlusPlus14)
2310 return false;
2311 break;
2312 }
2313 } else if (ReturnStmts.size() > 1) {
2314 switch (Kind) {
2315 case Sema::CheckConstexprKind::Diagnose:
2316 SemaRef.Diag(
2317 ReturnStmts.back(),
2318 SemaRef.getLangOpts().CPlusPlus14
2319 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2320 : diag::ext_constexpr_body_multiple_return);
2321 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2322 SemaRef.Diag(ReturnStmts[I],
2323 diag::note_constexpr_body_previous_return);
2324 break;
2325
2326 case Sema::CheckConstexprKind::CheckValid:
2327 if (!SemaRef.getLangOpts().CPlusPlus14)
2328 return false;
2329 break;
2330 }
2331 }
2332 }
2333
2334 // C++11 [dcl.constexpr]p5:
2335 // if no function argument values exist such that the function invocation
2336 // substitution would produce a constant expression, the program is
2337 // ill-formed; no diagnostic required.
2338 // C++11 [dcl.constexpr]p3:
2339 // - every constructor call and implicit conversion used in initializing the
2340 // return value shall be one of those allowed in a constant expression.
2341 // C++11 [dcl.constexpr]p4:
2342 // - every constructor involved in initializing non-static data members and
2343 // base class sub-objects shall be a constexpr constructor.
2344 //
2345 // Note that this rule is distinct from the "requirements for a constexpr
2346 // function", so is not checked in CheckValid mode.
2347 SmallVector<PartialDiagnosticAt, 8> Diags;
2348 if (Kind == Sema::CheckConstexprKind::Diagnose &&
2349 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2350 SemaRef.Diag(Dcl->getLocation(),
2351 diag::ext_constexpr_function_never_constant_expr)
2352 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2353 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2354 SemaRef.Diag(Diags[I].first, Diags[I].second);
2355 // Don't return false here: we allow this for compatibility in
2356 // system headers.
2357 }
2358
2359 return true;
2360}
2361
2362/// Get the class that is directly named by the current context. This is the
2363/// class for which an unqualified-id in this scope could name a constructor
2364/// or destructor.
2365///
2366/// If the scope specifier denotes a class, this will be that class.
2367/// If the scope specifier is empty, this will be the class whose
2368/// member-specification we are currently within. Otherwise, there
2369/// is no such class.
2370CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2371 assert(getLangOpts().CPlusPlus && "No class names in C!")((getLangOpts().CPlusPlus && "No class names in C!") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 2371, __PRETTY_FUNCTION__))
;
2372
2373 if (SS && SS->isInvalid())
2374 return nullptr;
2375
2376 if (SS && SS->isNotEmpty()) {
2377 DeclContext *DC = computeDeclContext(*SS, true);
2378 return dyn_cast_or_null<CXXRecordDecl>(DC);
2379 }
2380
2381 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2382}
2383
2384/// isCurrentClassName - Determine whether the identifier II is the
2385/// name of the class type currently being defined. In the case of
2386/// nested classes, this will only return true if II is the name of
2387/// the innermost class.
2388bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2389 const CXXScopeSpec *SS) {
2390 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2391 return CurDecl && &II == CurDecl->getIdentifier();
2392}
2393
2394/// Determine whether the identifier II is a typo for the name of
2395/// the class type currently being defined. If so, update it to the identifier
2396/// that should have been used.
2397bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2398 assert(getLangOpts().CPlusPlus && "No class names in C!")((getLangOpts().CPlusPlus && "No class names in C!") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 2398, __PRETTY_FUNCTION__))
;
2399
2400 if (!getLangOpts().SpellChecking)
2401 return false;
2402
2403 CXXRecordDecl *CurDecl;
2404 if (SS && SS->isSet() && !SS->isInvalid()) {
2405 DeclContext *DC = computeDeclContext(*SS, true);
2406 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2407 } else
2408 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2409
2410 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2411 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2412 < II->getLength()) {
2413 II = CurDecl->getIdentifier();
2414 return true;
2415 }
2416
2417 return false;
2418}
2419
2420/// Determine whether the given class is a base class of the given
2421/// class, including looking at dependent bases.
2422static bool findCircularInheritance(const CXXRecordDecl *Class,
2423 const CXXRecordDecl *Current) {
2424 SmallVector<const CXXRecordDecl*, 8> Queue;
2425
2426 Class = Class->getCanonicalDecl();
2427 while (true) {
2428 for (const auto &I : Current->bases()) {
2429 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2430 if (!Base)
2431 continue;
2432
2433 Base = Base->getDefinition();
2434 if (!Base)
2435 continue;
2436
2437 if (Base->getCanonicalDecl() == Class)
2438 return true;
2439
2440 Queue.push_back(Base);
2441 }
2442
2443 if (Queue.empty())
2444 return false;
2445
2446 Current = Queue.pop_back_val();
2447 }
2448
2449 return false;
2450}
2451
2452/// Check the validity of a C++ base class specifier.
2453///
2454/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2455/// and returns NULL otherwise.
2456CXXBaseSpecifier *
2457Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2458 SourceRange SpecifierRange,
2459 bool Virtual, AccessSpecifier Access,
2460 TypeSourceInfo *TInfo,
2461 SourceLocation EllipsisLoc) {
2462 QualType BaseType = TInfo->getType();
2463 if (BaseType->containsErrors()) {
2464 // Already emitted a diagnostic when parsing the error type.
2465 return nullptr;
2466 }
2467 // C++ [class.union]p1:
2468 // A union shall not have base classes.
2469 if (Class->isUnion()) {
2470 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2471 << SpecifierRange;
2472 return nullptr;
2473 }
2474
2475 if (EllipsisLoc.isValid() &&
2476 !TInfo->getType()->containsUnexpandedParameterPack()) {
2477 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2478 << TInfo->getTypeLoc().getSourceRange();
2479 EllipsisLoc = SourceLocation();
2480 }
2481
2482 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2483
2484 if (BaseType->isDependentType()) {
2485 // Make sure that we don't have circular inheritance among our dependent
2486 // bases. For non-dependent bases, the check for completeness below handles
2487 // this.
2488 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2489 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2490 ((BaseDecl = BaseDecl->getDefinition()) &&
2491 findCircularInheritance(Class, BaseDecl))) {
2492 Diag(BaseLoc, diag::err_circular_inheritance)
2493 << BaseType << Context.getTypeDeclType(Class);
2494
2495 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2496 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2497 << BaseType;
2498
2499 return nullptr;
2500 }
2501 }
2502
2503 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2504 Class->getTagKind() == TTK_Class,
2505 Access, TInfo, EllipsisLoc);
2506 }
2507
2508 // Base specifiers must be record types.
2509 if (!BaseType->isRecordType()) {
2510 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2511 return nullptr;
2512 }
2513
2514 // C++ [class.union]p1:
2515 // A union shall not be used as a base class.
2516 if (BaseType->isUnionType()) {
2517 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2518 return nullptr;
2519 }
2520
2521 // For the MS ABI, propagate DLL attributes to base class templates.
2522 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2523 if (Attr *ClassAttr = getDLLAttr(Class)) {
2524 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2525 BaseType->getAsCXXRecordDecl())) {
2526 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2527 BaseLoc);
2528 }
2529 }
2530 }
2531
2532 // C++ [class.derived]p2:
2533 // The class-name in a base-specifier shall not be an incompletely
2534 // defined class.
2535 if (RequireCompleteType(BaseLoc, BaseType,
2536 diag::err_incomplete_base_class, SpecifierRange)) {
2537 Class->setInvalidDecl();
2538 return nullptr;
2539 }
2540
2541 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2542 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2543 assert(BaseDecl && "Record type has no declaration")((BaseDecl && "Record type has no declaration") ? static_cast
<void> (0) : __assert_fail ("BaseDecl && \"Record type has no declaration\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 2543, __PRETTY_FUNCTION__))
;
2544 BaseDecl = BaseDecl->getDefinition();
2545 assert(BaseDecl && "Base type is not incomplete, but has no definition")((BaseDecl && "Base type is not incomplete, but has no definition"
) ? static_cast<void> (0) : __assert_fail ("BaseDecl && \"Base type is not incomplete, but has no definition\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 2545, __PRETTY_FUNCTION__))
;
2546 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2547 assert(CXXBaseDecl && "Base type is not a C++ type")((CXXBaseDecl && "Base type is not a C++ type") ? static_cast
<void> (0) : __assert_fail ("CXXBaseDecl && \"Base type is not a C++ type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 2547, __PRETTY_FUNCTION__))
;
2548
2549 // Microsoft docs say:
2550 // "If a base-class has a code_seg attribute, derived classes must have the
2551 // same attribute."
2552 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2553 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2554 if ((DerivedCSA || BaseCSA) &&
2555 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2556 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2557 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2558 << CXXBaseDecl;
2559 return nullptr;
2560 }
2561
2562 // A class which contains a flexible array member is not suitable for use as a
2563 // base class:
2564 // - If the layout determines that a base comes before another base,
2565 // the flexible array member would index into the subsequent base.
2566 // - If the layout determines that base comes before the derived class,
2567 // the flexible array member would index into the derived class.
2568 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2569 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2570 << CXXBaseDecl->getDeclName();
2571 return nullptr;
2572 }
2573
2574 // C++ [class]p3:
2575 // If a class is marked final and it appears as a base-type-specifier in
2576 // base-clause, the program is ill-formed.
2577 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2578 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2579 << CXXBaseDecl->getDeclName()
2580 << FA->isSpelledAsSealed();
2581 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2582 << CXXBaseDecl->getDeclName() << FA->getRange();
2583 return nullptr;
2584 }
2585
2586 if (BaseDecl->isInvalidDecl())
2587 Class->setInvalidDecl();
2588
2589 // Create the base specifier.
2590 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2591 Class->getTagKind() == TTK_Class,
2592 Access, TInfo, EllipsisLoc);
2593}
2594
2595/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2596/// one entry in the base class list of a class specifier, for
2597/// example:
2598/// class foo : public bar, virtual private baz {
2599/// 'public bar' and 'virtual private baz' are each base-specifiers.
2600BaseResult
2601Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2602 ParsedAttributes &Attributes,
2603 bool Virtual, AccessSpecifier Access,
2604 ParsedType basetype, SourceLocation BaseLoc,
2605 SourceLocation EllipsisLoc) {
2606 if (!classdecl)
2607 return true;
2608
2609 AdjustDeclIfTemplate(classdecl);
2610 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2611 if (!Class)
2612 return true;
2613
2614 // We haven't yet attached the base specifiers.
2615 Class->setIsParsingBaseSpecifiers();
2616
2617 // We do not support any C++11 attributes on base-specifiers yet.
2618 // Diagnose any attributes we see.
2619 for (const ParsedAttr &AL : Attributes) {
2620 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2621 continue;
2622 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2623 ? (unsigned)diag::warn_unknown_attribute_ignored
2624 : (unsigned)diag::err_base_specifier_attribute)
2625 << AL << AL.getRange();
2626 }
2627
2628 TypeSourceInfo *TInfo = nullptr;
2629 GetTypeFromParser(basetype, &TInfo);
2630
2631 if (EllipsisLoc.isInvalid() &&
2632 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2633 UPPC_BaseType))
2634 return true;
2635
2636 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2637 Virtual, Access, TInfo,
2638 EllipsisLoc))
2639 return BaseSpec;
2640 else
2641 Class->setInvalidDecl();
2642
2643 return true;
2644}
2645
2646/// Use small set to collect indirect bases. As this is only used
2647/// locally, there's no need to abstract the small size parameter.
2648typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2649
2650/// Recursively add the bases of Type. Don't add Type itself.
2651static void
2652NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2653 const QualType &Type)
2654{
2655 // Even though the incoming type is a base, it might not be
2656 // a class -- it could be a template parm, for instance.
2657 if (auto Rec = Type->getAs<RecordType>()) {
2658 auto Decl = Rec->getAsCXXRecordDecl();
2659
2660 // Iterate over its bases.
2661 for (const auto &BaseSpec : Decl->bases()) {
2662 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2663 .getUnqualifiedType();
2664 if (Set.insert(Base).second)
2665 // If we've not already seen it, recurse.
2666 NoteIndirectBases(Context, Set, Base);
2667 }
2668 }
2669}
2670
2671/// Performs the actual work of attaching the given base class
2672/// specifiers to a C++ class.
2673bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2674 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2675 if (Bases.empty())
2676 return false;
2677
2678 // Used to keep track of which base types we have already seen, so
2679 // that we can properly diagnose redundant direct base types. Note
2680 // that the key is always the unqualified canonical type of the base
2681 // class.
2682 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2683
2684 // Used to track indirect bases so we can see if a direct base is
2685 // ambiguous.
2686 IndirectBaseSet IndirectBaseTypes;
2687
2688 // Copy non-redundant base specifiers into permanent storage.
2689 unsigned NumGoodBases = 0;
2690 bool Invalid = false;
2691 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2692 QualType NewBaseType
2693 = Context.getCanonicalType(Bases[idx]->getType());
2694 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2695
2696 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2697 if (KnownBase) {
2698 // C++ [class.mi]p3:
2699 // A class shall not be specified as a direct base class of a
2700 // derived class more than once.
2701 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2702 << KnownBase->getType() << Bases[idx]->getSourceRange();
2703
2704 // Delete the duplicate base class specifier; we're going to
2705 // overwrite its pointer later.
2706 Context.Deallocate(Bases[idx]);
2707
2708 Invalid = true;
2709 } else {
2710 // Okay, add this new base class.
2711 KnownBase = Bases[idx];
2712 Bases[NumGoodBases++] = Bases[idx];
2713
2714 // Note this base's direct & indirect bases, if there could be ambiguity.
2715 if (Bases.size() > 1)
2716 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2717
2718 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2719 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2720 if (Class->isInterface() &&
2721 (!RD->isInterfaceLike() ||
2722 KnownBase->getAccessSpecifier() != AS_public)) {
2723 // The Microsoft extension __interface does not permit bases that
2724 // are not themselves public interfaces.
2725 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2726 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2727 << RD->getSourceRange();
2728 Invalid = true;
2729 }
2730 if (RD->hasAttr<WeakAttr>())
2731 Class->addAttr(WeakAttr::CreateImplicit(Context));
2732 }
2733 }
2734 }
2735
2736 // Attach the remaining base class specifiers to the derived class.
2737 Class->setBases(Bases.data(), NumGoodBases);
2738
2739 // Check that the only base classes that are duplicate are virtual.
2740 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2741 // Check whether this direct base is inaccessible due to ambiguity.
2742 QualType BaseType = Bases[idx]->getType();
2743
2744 // Skip all dependent types in templates being used as base specifiers.
2745 // Checks below assume that the base specifier is a CXXRecord.
2746 if (BaseType->isDependentType())
2747 continue;
2748
2749 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2750 .getUnqualifiedType();
2751
2752 if (IndirectBaseTypes.count(CanonicalBase)) {
2753 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2754 /*DetectVirtual=*/true);
2755 bool found
2756 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2757 assert(found)((found) ? static_cast<void> (0) : __assert_fail ("found"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 2757, __PRETTY_FUNCTION__))
;
2758 (void)found;
2759
2760 if (Paths.isAmbiguous(CanonicalBase))
2761 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2762 << BaseType << getAmbiguousPathsDisplayString(Paths)
2763 << Bases[idx]->getSourceRange();
2764 else
2765 assert(Bases[idx]->isVirtual())((Bases[idx]->isVirtual()) ? static_cast<void> (0) :
__assert_fail ("Bases[idx]->isVirtual()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 2765, __PRETTY_FUNCTION__))
;
2766 }
2767
2768 // Delete the base class specifier, since its data has been copied
2769 // into the CXXRecordDecl.
2770 Context.Deallocate(Bases[idx]);
2771 }
2772
2773 return Invalid;
2774}
2775
2776/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2777/// class, after checking whether there are any duplicate base
2778/// classes.
2779void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2780 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2781 if (!ClassDecl || Bases.empty())
2782 return;
2783
2784 AdjustDeclIfTemplate(ClassDecl);
2785 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2786}
2787
2788/// Determine whether the type \p Derived is a C++ class that is
2789/// derived from the type \p Base.
2790bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2791 if (!getLangOpts().CPlusPlus)
2792 return false;
2793
2794 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2795 if (!DerivedRD)
2796 return false;
2797
2798 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2799 if (!BaseRD)
2800 return false;
2801
2802 // If either the base or the derived type is invalid, don't try to
2803 // check whether one is derived from the other.
2804 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2805 return false;
2806
2807 // FIXME: In a modules build, do we need the entire path to be visible for us
2808 // to be able to use the inheritance relationship?
2809 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2810 return false;
2811
2812 return DerivedRD->isDerivedFrom(BaseRD);
2813}
2814
2815/// Determine whether the type \p Derived is a C++ class that is
2816/// derived from the type \p Base.
2817bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2818 CXXBasePaths &Paths) {
2819 if (!getLangOpts().CPlusPlus)
2820 return false;
2821
2822 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2823 if (!DerivedRD)
2824 return false;
2825
2826 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2827 if (!BaseRD)
2828 return false;
2829
2830 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2831 return false;
2832
2833 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2834}
2835
2836static void BuildBasePathArray(const CXXBasePath &Path,
2837 CXXCastPath &BasePathArray) {
2838 // We first go backward and check if we have a virtual base.
2839 // FIXME: It would be better if CXXBasePath had the base specifier for
2840 // the nearest virtual base.
2841 unsigned Start = 0;
2842 for (unsigned I = Path.size(); I != 0; --I) {
2843 if (Path[I - 1].Base->isVirtual()) {
2844 Start = I - 1;
2845 break;
2846 }
2847 }
2848
2849 // Now add all bases.
2850 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2851 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2852}
2853
2854
2855void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2856 CXXCastPath &BasePathArray) {
2857 assert(BasePathArray.empty() && "Base path array must be empty!")((BasePathArray.empty() && "Base path array must be empty!"
) ? static_cast<void> (0) : __assert_fail ("BasePathArray.empty() && \"Base path array must be empty!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 2857, __PRETTY_FUNCTION__))
;
2858 assert(Paths.isRecordingPaths() && "Must record paths!")((Paths.isRecordingPaths() && "Must record paths!") ?
static_cast<void> (0) : __assert_fail ("Paths.isRecordingPaths() && \"Must record paths!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 2858, __PRETTY_FUNCTION__))
;
2859 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2860}
2861/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2862/// conversion (where Derived and Base are class types) is
2863/// well-formed, meaning that the conversion is unambiguous (and
2864/// that all of the base classes are accessible). Returns true
2865/// and emits a diagnostic if the code is ill-formed, returns false
2866/// otherwise. Loc is the location where this routine should point to
2867/// if there is an error, and Range is the source range to highlight
2868/// if there is an error.
2869///
2870/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2871/// diagnostic for the respective type of error will be suppressed, but the
2872/// check for ill-formed code will still be performed.
2873bool
2874Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2875 unsigned InaccessibleBaseID,
2876 unsigned AmbiguousBaseConvID,
2877 SourceLocation Loc, SourceRange Range,
2878 DeclarationName Name,
2879 CXXCastPath *BasePath,
2880 bool IgnoreAccess) {
2881 // First, determine whether the path from Derived to Base is
2882 // ambiguous. This is slightly more expensive than checking whether
2883 // the Derived to Base conversion exists, because here we need to
2884 // explore multiple paths to determine if there is an ambiguity.
2885 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2886 /*DetectVirtual=*/false);
2887 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2888 if (!DerivationOkay)
2889 return true;
2890
2891 const CXXBasePath *Path = nullptr;
2892 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2893 Path = &Paths.front();
2894
2895 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2896 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2897 // user to access such bases.
2898 if (!Path && getLangOpts().MSVCCompat) {
2899 for (const CXXBasePath &PossiblePath : Paths) {
2900 if (PossiblePath.size() == 1) {
2901 Path = &PossiblePath;
2902 if (AmbiguousBaseConvID)
2903 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2904 << Base << Derived << Range;
2905 break;
2906 }
2907 }
2908 }
2909
2910 if (Path) {
2911 if (!IgnoreAccess) {
2912 // Check that the base class can be accessed.
2913 switch (
2914 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2915 case AR_inaccessible:
2916 return true;
2917 case AR_accessible:
2918 case AR_dependent:
2919 case AR_delayed:
2920 break;
2921 }
2922 }
2923
2924 // Build a base path if necessary.
2925 if (BasePath)
2926 ::BuildBasePathArray(*Path, *BasePath);
2927 return false;
2928 }
2929
2930 if (AmbiguousBaseConvID) {
2931 // We know that the derived-to-base conversion is ambiguous, and
2932 // we're going to produce a diagnostic. Perform the derived-to-base
2933 // search just one more time to compute all of the possible paths so
2934 // that we can print them out. This is more expensive than any of
2935 // the previous derived-to-base checks we've done, but at this point
2936 // performance isn't as much of an issue.
2937 Paths.clear();
2938 Paths.setRecordingPaths(true);
2939 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2940 assert(StillOkay && "Can only be used with a derived-to-base conversion")((StillOkay && "Can only be used with a derived-to-base conversion"
) ? static_cast<void> (0) : __assert_fail ("StillOkay && \"Can only be used with a derived-to-base conversion\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 2940, __PRETTY_FUNCTION__))
;
2941 (void)StillOkay;
2942
2943 // Build up a textual representation of the ambiguous paths, e.g.,
2944 // D -> B -> A, that will be used to illustrate the ambiguous
2945 // conversions in the diagnostic. We only print one of the paths
2946 // to each base class subobject.
2947 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2948
2949 Diag(Loc, AmbiguousBaseConvID)
2950 << Derived << Base << PathDisplayStr << Range << Name;
2951 }
2952 return true;
2953}
2954
2955bool
2956Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2957 SourceLocation Loc, SourceRange Range,
2958 CXXCastPath *BasePath,
2959 bool IgnoreAccess) {
2960 return CheckDerivedToBaseConversion(
2961 Derived, Base, diag::err_upcast_to_inaccessible_base,
2962 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2963 BasePath, IgnoreAccess);
2964}
2965
2966
2967/// Builds a string representing ambiguous paths from a
2968/// specific derived class to different subobjects of the same base
2969/// class.
2970///
2971/// This function builds a string that can be used in error messages
2972/// to show the different paths that one can take through the
2973/// inheritance hierarchy to go from the derived class to different
2974/// subobjects of a base class. The result looks something like this:
2975/// @code
2976/// struct D -> struct B -> struct A
2977/// struct D -> struct C -> struct A
2978/// @endcode
2979std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2980 std::string PathDisplayStr;
2981 std::set<unsigned> DisplayedPaths;
2982 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2983 Path != Paths.end(); ++Path) {
2984 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2985 // We haven't displayed a path to this particular base
2986 // class subobject yet.
2987 PathDisplayStr += "\n ";
2988 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2989 for (CXXBasePath::const_iterator Element = Path->begin();
2990 Element != Path->end(); ++Element)
2991 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2992 }
2993 }
2994
2995 return PathDisplayStr;
2996}
2997
2998//===----------------------------------------------------------------------===//
2999// C++ class member Handling
3000//===----------------------------------------------------------------------===//
3001
3002/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3003bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3004 SourceLocation ColonLoc,
3005 const ParsedAttributesView &Attrs) {
3006 assert(Access != AS_none && "Invalid kind for syntactic access specifier!")((Access != AS_none && "Invalid kind for syntactic access specifier!"
) ? static_cast<void> (0) : __assert_fail ("Access != AS_none && \"Invalid kind for syntactic access specifier!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 3006, __PRETTY_FUNCTION__))
;
3007 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3008 ASLoc, ColonLoc);
3009 CurContext->addHiddenDecl(ASDecl);
3010 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3011}
3012
3013/// CheckOverrideControl - Check C++11 override control semantics.
3014void Sema::CheckOverrideControl(NamedDecl *D) {
3015 if (D->isInvalidDecl())
3016 return;
3017
3018 // We only care about "override" and "final" declarations.
3019 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3020 return;
3021
3022 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3023
3024 // We can't check dependent instance methods.
3025 if (MD && MD->isInstance() &&
3026 (MD->getParent()->hasAnyDependentBases() ||
3027 MD->getType()->isDependentType()))
3028 return;
3029
3030 if (MD && !MD->isVirtual()) {
3031 // If we have a non-virtual method, check if if hides a virtual method.
3032 // (In that case, it's most likely the method has the wrong type.)
3033 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3034 FindHiddenVirtualMethods(MD, OverloadedMethods);
3035
3036 if (!OverloadedMethods.empty()) {
3037 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3038 Diag(OA->getLocation(),
3039 diag::override_keyword_hides_virtual_member_function)
3040 << "override" << (OverloadedMethods.size() > 1);
3041 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3042 Diag(FA->getLocation(),
3043 diag::override_keyword_hides_virtual_member_function)
3044 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3045 << (OverloadedMethods.size() > 1);
3046 }
3047 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3048 MD->setInvalidDecl();
3049 return;
3050 }
3051 // Fall through into the general case diagnostic.
3052 // FIXME: We might want to attempt typo correction here.
3053 }
3054
3055 if (!MD || !MD->isVirtual()) {
3056 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3057 Diag(OA->getLocation(),
3058 diag::override_keyword_only_allowed_on_virtual_member_functions)
3059 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3060 D->dropAttr<OverrideAttr>();
3061 }
3062 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3063 Diag(FA->getLocation(),
3064 diag::override_keyword_only_allowed_on_virtual_member_functions)
3065 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3066 << FixItHint::CreateRemoval(FA->getLocation());
3067 D->dropAttr<FinalAttr>();
3068 }
3069 return;
3070 }
3071
3072 // C++11 [class.virtual]p5:
3073 // If a function is marked with the virt-specifier override and
3074 // does not override a member function of a base class, the program is
3075 // ill-formed.
3076 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3077 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3078 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3079 << MD->getDeclName();
3080}
3081
3082void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3083 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3084 return;
3085 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3086 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3087 return;
3088
3089 SourceLocation Loc = MD->getLocation();
3090 SourceLocation SpellingLoc = Loc;
3091 if (getSourceManager().isMacroArgExpansion(Loc))
3092 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3093 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3094 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3095 return;
3096
3097 if (MD->size_overridden_methods() > 0) {
3098 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3099 unsigned DiagID =
3100 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3101 ? DiagInconsistent
3102 : DiagSuggest;
3103 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3104 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3105 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3106 };
3107 if (isa<CXXDestructorDecl>(MD))
3108 EmitDiag(
3109 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3110 diag::warn_suggest_destructor_marked_not_override_overriding);
3111 else
3112 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3113 diag::warn_suggest_function_marked_not_override_overriding);
3114 }
3115}
3116
3117/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3118/// function overrides a virtual member function marked 'final', according to
3119/// C++11 [class.virtual]p4.
3120bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3121 const CXXMethodDecl *Old) {
3122 FinalAttr *FA = Old->getAttr<FinalAttr>();
3123 if (!FA)
3124 return false;
3125
3126 Diag(New->getLocation(), diag::err_final_function_overridden)
3127 << New->getDeclName()
3128 << FA->isSpelledAsSealed();
3129 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3130 return true;
3131}
3132
3133static bool InitializationHasSideEffects(const FieldDecl &FD) {
3134 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3135 // FIXME: Destruction of ObjC lifetime types has side-effects.
3136 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3137 return !RD->isCompleteDefinition() ||
3138 !RD->hasTrivialDefaultConstructor() ||
3139 !RD->hasTrivialDestructor();
3140 return false;
3141}
3142
3143static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3144 ParsedAttributesView::const_iterator Itr =
3145 llvm::find_if(list, [](const ParsedAttr &AL) {
3146 return AL.isDeclspecPropertyAttribute();
3147 });
3148 if (Itr != list.end())
3149 return &*Itr;
3150 return nullptr;
3151}
3152
3153// Check if there is a field shadowing.
3154void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3155 DeclarationName FieldName,
3156 const CXXRecordDecl *RD,
3157 bool DeclIsField) {
3158 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3159 return;
3160
3161 // To record a shadowed field in a base
3162 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3163 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3164 CXXBasePath &Path) {
3165 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3166 // Record an ambiguous path directly
3167 if (Bases.find(Base) != Bases.end())
3168 return true;
3169 for (const auto Field : Base->lookup(FieldName)) {
3170 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3171 Field->getAccess() != AS_private) {
3172 assert(Field->getAccess() != AS_none)((Field->getAccess() != AS_none) ? static_cast<void>
(0) : __assert_fail ("Field->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 3172, __PRETTY_FUNCTION__))
;
3173 assert(Bases.find(Base) == Bases.end())((Bases.find(Base) == Bases.end()) ? static_cast<void> (
0) : __assert_fail ("Bases.find(Base) == Bases.end()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 3173, __PRETTY_FUNCTION__))
;
3174 Bases[Base] = Field;
3175 return true;
3176 }
3177 }
3178 return false;
3179 };
3180
3181 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3182 /*DetectVirtual=*/true);
3183 if (!RD->lookupInBases(FieldShadowed, Paths))
3184 return;
3185
3186 for (const auto &P : Paths) {
3187 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3188 auto It = Bases.find(Base);
3189 // Skip duplicated bases
3190 if (It == Bases.end())
3191 continue;
3192 auto BaseField = It->second;
3193 assert(BaseField->getAccess() != AS_private)((BaseField->getAccess() != AS_private) ? static_cast<void
> (0) : __assert_fail ("BaseField->getAccess() != AS_private"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 3193, __PRETTY_FUNCTION__))
;
3194 if (AS_none !=
3195 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3196 Diag(Loc, diag::warn_shadow_field)
3197 << FieldName << RD << Base << DeclIsField;
3198 Diag(BaseField->getLocation(), diag::note_shadow_field);
3199 Bases.erase(It);
3200 }
3201 }
3202}
3203
3204/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3205/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3206/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3207/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3208/// present (but parsing it has been deferred).
3209NamedDecl *
3210Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3211 MultiTemplateParamsArg TemplateParameterLists,
3212 Expr *BW, const VirtSpecifiers &VS,
3213 InClassInitStyle InitStyle) {
3214 const DeclSpec &DS = D.getDeclSpec();
3215 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3216 DeclarationName Name = NameInfo.getName();
3217 SourceLocation Loc = NameInfo.getLoc();
3218
3219 // For anonymous bitfields, the location should point to the type.
3220 if (Loc.isInvalid())
3221 Loc = D.getBeginLoc();
3222
3223 Expr *BitWidth = static_cast<Expr*>(BW);
3224
3225 assert(isa<CXXRecordDecl>(CurContext))((isa<CXXRecordDecl>(CurContext)) ? static_cast<void
> (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 3225, __PRETTY_FUNCTION__))
;
3226 assert(!DS.isFriendSpecified())((!DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail
("!DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 3226, __PRETTY_FUNCTION__))
;
3227
3228 bool isFunc = D.isDeclarationOfFunction();
3229 const ParsedAttr *MSPropertyAttr =
3230 getMSPropertyAttr(D.getDeclSpec().getAttributes());
3231
3232 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3233 // The Microsoft extension __interface only permits public member functions
3234 // and prohibits constructors, destructors, operators, non-public member
3235 // functions, static methods and data members.
3236 unsigned InvalidDecl;
3237 bool ShowDeclName = true;
3238 if (!isFunc &&
3239 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3240 InvalidDecl = 0;
3241 else if (!isFunc)
3242 InvalidDecl = 1;
3243 else if (AS != AS_public)
3244 InvalidDecl = 2;
3245 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3246 InvalidDecl = 3;
3247 else switch (Name.getNameKind()) {
3248 case DeclarationName::CXXConstructorName:
3249 InvalidDecl = 4;
3250 ShowDeclName = false;
3251 break;
3252
3253 case DeclarationName::CXXDestructorName:
3254 InvalidDecl = 5;
3255 ShowDeclName = false;
3256 break;
3257
3258 case DeclarationName::CXXOperatorName:
3259 case DeclarationName::CXXConversionFunctionName:
3260 InvalidDecl = 6;
3261 break;
3262
3263 default:
3264 InvalidDecl = 0;
3265 break;
3266 }
3267
3268 if (InvalidDecl) {
3269 if (ShowDeclName)
3270 Diag(Loc, diag::err_invalid_member_in_interface)
3271 << (InvalidDecl-1) << Name;
3272 else
3273 Diag(Loc, diag::err_invalid_member_in_interface)
3274 << (InvalidDecl-1) << "";
3275 return nullptr;
3276 }
3277 }
3278
3279 // C++ 9.2p6: A member shall not be declared to have automatic storage
3280 // duration (auto, register) or with the extern storage-class-specifier.
3281 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3282 // data members and cannot be applied to names declared const or static,
3283 // and cannot be applied to reference members.
3284 switch (DS.getStorageClassSpec()) {
3285 case DeclSpec::SCS_unspecified:
3286 case DeclSpec::SCS_typedef:
3287 case DeclSpec::SCS_static:
3288 break;
3289 case DeclSpec::SCS_mutable:
3290 if (isFunc) {
3291 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3292
3293 // FIXME: It would be nicer if the keyword was ignored only for this
3294 // declarator. Otherwise we could get follow-up errors.
3295 D.getMutableDeclSpec().ClearStorageClassSpecs();
3296 }
3297 break;
3298 default:
3299 Diag(DS.getStorageClassSpecLoc(),
3300 diag::err_storageclass_invalid_for_member);
3301 D.getMutableDeclSpec().ClearStorageClassSpecs();
3302 break;
3303 }
3304
3305 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3306 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3307 !isFunc);
3308
3309 if (DS.hasConstexprSpecifier() && isInstField) {
3310 SemaDiagnosticBuilder B =
3311 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3312 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3313 if (InitStyle == ICIS_NoInit) {
3314 B << 0 << 0;
3315 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3316 B << FixItHint::CreateRemoval(ConstexprLoc);
3317 else {
3318 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3319 D.getMutableDeclSpec().ClearConstexprSpec();
3320 const char *PrevSpec;
3321 unsigned DiagID;
3322 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3323 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3324 (void)Failed;
3325 assert(!Failed && "Making a constexpr member const shouldn't fail")((!Failed && "Making a constexpr member const shouldn't fail"
) ? static_cast<void> (0) : __assert_fail ("!Failed && \"Making a constexpr member const shouldn't fail\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 3325, __PRETTY_FUNCTION__))
;
3326 }
3327 } else {
3328 B << 1;
3329 const char *PrevSpec;
3330 unsigned DiagID;
3331 if (D.getMutableDeclSpec().SetStorageClassSpec(
3332 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3333 Context.getPrintingPolicy())) {
3334 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&((DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
"This is the only DeclSpec that should fail to be applied") ?
static_cast<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 3335, __PRETTY_FUNCTION__))
3335 "This is the only DeclSpec that should fail to be applied")((DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
"This is the only DeclSpec that should fail to be applied") ?
static_cast<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 3335, __PRETTY_FUNCTION__))
;
3336 B << 1;
3337 } else {
3338 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3339 isInstField = false;
3340 }
3341 }
3342 }
3343
3344 NamedDecl *Member;
3345 if (isInstField) {
3346 CXXScopeSpec &SS = D.getCXXScopeSpec();
3347
3348 // Data members must have identifiers for names.
3349 if (!Name.isIdentifier()) {
3350 Diag(Loc, diag::err_bad_variable_name)
3351 << Name;
3352 return nullptr;
3353 }
3354
3355 IdentifierInfo *II = Name.getAsIdentifierInfo();
3356
3357 // Member field could not be with "template" keyword.
3358 // So TemplateParameterLists should be empty in this case.
3359 if (TemplateParameterLists.size()) {
3360 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3361 if (TemplateParams->size()) {
3362 // There is no such thing as a member field template.
3363 Diag(D.getIdentifierLoc(), diag::err_template_member)
3364 << II
3365 << SourceRange(TemplateParams->getTemplateLoc(),
3366 TemplateParams->getRAngleLoc());
3367 } else {
3368 // There is an extraneous 'template<>' for this member.
3369 Diag(TemplateParams->getTemplateLoc(),
3370 diag::err_template_member_noparams)
3371 << II
3372 << SourceRange(TemplateParams->getTemplateLoc(),
3373 TemplateParams->getRAngleLoc());
3374 }
3375 return nullptr;
3376 }
3377
3378 if (SS.isSet() && !SS.isInvalid()) {
3379 // The user provided a superfluous scope specifier inside a class
3380 // definition:
3381 //
3382 // class X {
3383 // int X::member;
3384 // };
3385 if (DeclContext *DC = computeDeclContext(SS, false))
3386 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3387 D.getName().getKind() ==
3388 UnqualifiedIdKind::IK_TemplateId);
3389 else
3390 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3391 << Name << SS.getRange();
3392
3393 SS.clear();
3394 }
3395
3396 if (MSPropertyAttr) {
3397 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3398 BitWidth, InitStyle, AS, *MSPropertyAttr);
3399 if (!Member)
3400 return nullptr;
3401 isInstField = false;
3402 } else {
3403 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3404 BitWidth, InitStyle, AS);
3405 if (!Member)
3406 return nullptr;
3407 }
3408
3409 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3410 } else {
3411 Member = HandleDeclarator(S, D, TemplateParameterLists);
3412 if (!Member)
3413 return nullptr;
3414
3415 // Non-instance-fields can't have a bitfield.
3416 if (BitWidth) {
3417 if (Member->isInvalidDecl()) {
3418 // don't emit another diagnostic.
3419 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3420 // C++ 9.6p3: A bit-field shall not be a static member.
3421 // "static member 'A' cannot be a bit-field"
3422 Diag(Loc, diag::err_static_not_bitfield)
3423 << Name << BitWidth->getSourceRange();
3424 } else if (isa<TypedefDecl>(Member)) {
3425 // "typedef member 'x' cannot be a bit-field"
3426 Diag(Loc, diag::err_typedef_not_bitfield)
3427 << Name << BitWidth->getSourceRange();
3428 } else {
3429 // A function typedef ("typedef int f(); f a;").
3430 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3431 Diag(Loc, diag::err_not_integral_type_bitfield)
3432 << Name << cast<ValueDecl>(Member)->getType()
3433 << BitWidth->getSourceRange();
3434 }
3435
3436 BitWidth = nullptr;
3437 Member->setInvalidDecl();
3438 }
3439
3440 NamedDecl *NonTemplateMember = Member;
3441 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3442 NonTemplateMember = FunTmpl->getTemplatedDecl();
3443 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3444 NonTemplateMember = VarTmpl->getTemplatedDecl();
3445
3446 Member->setAccess(AS);
3447
3448 // If we have declared a member function template or static data member
3449 // template, set the access of the templated declaration as well.
3450 if (NonTemplateMember != Member)
3451 NonTemplateMember->setAccess(AS);
3452
3453 // C++ [temp.deduct.guide]p3:
3454 // A deduction guide [...] for a member class template [shall be
3455 // declared] with the same access [as the template].
3456 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3457 auto *TD = DG->getDeducedTemplate();
3458 // Access specifiers are only meaningful if both the template and the
3459 // deduction guide are from the same scope.
3460 if (AS != TD->getAccess() &&
3461 TD->getDeclContext()->getRedeclContext()->Equals(
3462 DG->getDeclContext()->getRedeclContext())) {
3463 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3464 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3465 << TD->getAccess();
3466 const AccessSpecDecl *LastAccessSpec = nullptr;
3467 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3468 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3469 LastAccessSpec = AccessSpec;
3470 }
3471 assert(LastAccessSpec && "differing access with no access specifier")((LastAccessSpec && "differing access with no access specifier"
) ? static_cast<void> (0) : __assert_fail ("LastAccessSpec && \"differing access with no access specifier\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 3471, __PRETTY_FUNCTION__))
;
3472 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3473 << AS;
3474 }
3475 }
3476 }
3477
3478 if (VS.isOverrideSpecified())
3479 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3480 AttributeCommonInfo::AS_Keyword));
3481 if (VS.isFinalSpecified())
3482 Member->addAttr(FinalAttr::Create(
3483 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3484 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3485
3486 if (VS.getLastLocation().isValid()) {
3487 // Update the end location of a method that has a virt-specifiers.
3488 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3489 MD->setRangeEnd(VS.getLastLocation());
3490 }
3491
3492 CheckOverrideControl(Member);
3493
3494 assert((Name || isInstField) && "No identifier for non-field ?")(((Name || isInstField) && "No identifier for non-field ?"
) ? static_cast<void> (0) : __assert_fail ("(Name || isInstField) && \"No identifier for non-field ?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 3494, __PRETTY_FUNCTION__))
;
3495
3496 if (isInstField) {
3497 FieldDecl *FD = cast<FieldDecl>(Member);
3498 FieldCollector->Add(FD);
3499
3500 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3501 // Remember all explicit private FieldDecls that have a name, no side
3502 // effects and are not part of a dependent type declaration.
3503 if (!FD->isImplicit() && FD->getDeclName() &&
3504 FD->getAccess() == AS_private &&
3505 !FD->hasAttr<UnusedAttr>() &&
3506 !FD->getParent()->isDependentContext() &&
3507 !InitializationHasSideEffects(*FD))
3508 UnusedPrivateFields.insert(FD);
3509 }
3510 }
3511
3512 return Member;
3513}
3514
3515namespace {
3516 class UninitializedFieldVisitor
3517 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3518 Sema &S;
3519 // List of Decls to generate a warning on. Also remove Decls that become
3520 // initialized.
3521 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3522 // List of base classes of the record. Classes are removed after their
3523 // initializers.
3524 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3525 // Vector of decls to be removed from the Decl set prior to visiting the
3526 // nodes. These Decls may have been initialized in the prior initializer.
3527 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3528 // If non-null, add a note to the warning pointing back to the constructor.
3529 const CXXConstructorDecl *Constructor;
3530 // Variables to hold state when processing an initializer list. When
3531 // InitList is true, special case initialization of FieldDecls matching
3532 // InitListFieldDecl.
3533 bool InitList;
3534 FieldDecl *InitListFieldDecl;
3535 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3536
3537 public:
3538 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3539 UninitializedFieldVisitor(Sema &S,
3540 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3541 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3542 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3543 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3544
3545 // Returns true if the use of ME is not an uninitialized use.
3546 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3547 bool CheckReferenceOnly) {
3548 llvm::SmallVector<FieldDecl*, 4> Fields;
3549 bool ReferenceField = false;
3550 while (ME) {
3551 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3552 if (!FD)
3553 return false;
3554 Fields.push_back(FD);
3555 if (FD->getType()->isReferenceType())
3556 ReferenceField = true;
3557 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3558 }
3559
3560 // Binding a reference to an uninitialized field is not an
3561 // uninitialized use.
3562 if (CheckReferenceOnly && !ReferenceField)
3563 return true;
3564
3565 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3566 // Discard the first field since it is the field decl that is being
3567 // initialized.
3568 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3569 UsedFieldIndex.push_back((*I)->getFieldIndex());
3570 }
3571
3572 for (auto UsedIter = UsedFieldIndex.begin(),
3573 UsedEnd = UsedFieldIndex.end(),
3574 OrigIter = InitFieldIndex.begin(),
3575 OrigEnd = InitFieldIndex.end();
3576 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3577 if (*UsedIter < *OrigIter)
3578 return true;
3579 if (*UsedIter > *OrigIter)
3580 break;
3581 }
3582
3583 return false;
3584 }
3585
3586 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3587 bool AddressOf) {
3588 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3589 return;
3590
3591 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3592 // or union.
3593 MemberExpr *FieldME = ME;
3594
3595 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3596
3597 Expr *Base = ME;
3598 while (MemberExpr *SubME =
3599 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3600
3601 if (isa<VarDecl>(SubME->getMemberDecl()))
3602 return;
3603
3604 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3605 if (!FD->isAnonymousStructOrUnion())
3606 FieldME = SubME;
3607
3608 if (!FieldME->getType().isPODType(S.Context))
3609 AllPODFields = false;
3610
3611 Base = SubME->getBase();
3612 }
3613
3614 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3615 Visit(Base);
3616 return;
3617 }
3618
3619 if (AddressOf && AllPODFields)
3620 return;
3621
3622 ValueDecl* FoundVD = FieldME->getMemberDecl();
3623
3624 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3625 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3626 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3627 }
3628
3629 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3630 QualType T = BaseCast->getType();
3631 if (T->isPointerType() &&
3632 BaseClasses.count(T->getPointeeType())) {
3633 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3634 << T->getPointeeType() << FoundVD;
3635 }
3636 }
3637 }
3638
3639 if (!Decls.count(FoundVD))
3640 return;
3641
3642 const bool IsReference = FoundVD->getType()->isReferenceType();
3643
3644 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3645 // Special checking for initializer lists.
3646 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3647 return;
3648 }
3649 } else {
3650 // Prevent double warnings on use of unbounded references.
3651 if (CheckReferenceOnly && !IsReference)
3652 return;
3653 }
3654
3655 unsigned diag = IsReference
3656 ? diag::warn_reference_field_is_uninit
3657 : diag::warn_field_is_uninit;
3658 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3659 if (Constructor)
3660 S.Diag(Constructor->getLocation(),
3661 diag::note_uninit_in_this_constructor)
3662 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3663
3664 }
3665
3666 void HandleValue(Expr *E, bool AddressOf) {
3667 E = E->IgnoreParens();
3668
3669 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3670 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3671 AddressOf /*AddressOf*/);
3672 return;
3673 }
3674
3675 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3676 Visit(CO->getCond());
3677 HandleValue(CO->getTrueExpr(), AddressOf);
3678 HandleValue(CO->getFalseExpr(), AddressOf);
3679 return;
3680 }
3681
3682 if (BinaryConditionalOperator *BCO =
3683 dyn_cast<BinaryConditionalOperator>(E)) {
3684 Visit(BCO->getCond());
3685 HandleValue(BCO->getFalseExpr(), AddressOf);
3686 return;
3687 }
3688
3689 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3690 HandleValue(OVE->getSourceExpr(), AddressOf);
3691 return;
3692 }
3693
3694 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3695 switch (BO->getOpcode()) {
3696 default:
3697 break;
3698 case(BO_PtrMemD):
3699 case(BO_PtrMemI):
3700 HandleValue(BO->getLHS(), AddressOf);
3701 Visit(BO->getRHS());
3702 return;
3703 case(BO_Comma):
3704 Visit(BO->getLHS());
3705 HandleValue(BO->getRHS(), AddressOf);
3706 return;
3707 }
3708 }
3709
3710 Visit(E);
3711 }
3712
3713 void CheckInitListExpr(InitListExpr *ILE) {
3714 InitFieldIndex.push_back(0);
3715 for (auto Child : ILE->children()) {
3716 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3717 CheckInitListExpr(SubList);
3718 } else {
3719 Visit(Child);
3720 }
3721 ++InitFieldIndex.back();
3722 }
3723 InitFieldIndex.pop_back();
3724 }
3725
3726 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3727 FieldDecl *Field, const Type *BaseClass) {
3728 // Remove Decls that may have been initialized in the previous
3729 // initializer.
3730 for (ValueDecl* VD : DeclsToRemove)
3731 Decls.erase(VD);
3732 DeclsToRemove.clear();
3733
3734 Constructor = FieldConstructor;
3735 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3736
3737 if (ILE && Field) {
3738 InitList = true;
3739 InitListFieldDecl = Field;
3740 InitFieldIndex.clear();
3741 CheckInitListExpr(ILE);
3742 } else {
3743 InitList = false;
3744 Visit(E);
3745 }
3746
3747 if (Field)
3748 Decls.erase(Field);
3749 if (BaseClass)
3750 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3751 }
3752
3753 void VisitMemberExpr(MemberExpr *ME) {
3754 // All uses of unbounded reference fields will warn.
3755 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3756 }
3757
3758 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3759 if (E->getCastKind() == CK_LValueToRValue) {
3760 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3761 return;
3762 }
3763
3764 Inherited::VisitImplicitCastExpr(E);
3765 }
3766
3767 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3768 if (E->getConstructor()->isCopyConstructor()) {
3769 Expr *ArgExpr = E->getArg(0);
3770 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3771 if (ILE->getNumInits() == 1)
3772 ArgExpr = ILE->getInit(0);
3773 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3774 if (ICE->getCastKind() == CK_NoOp)
3775 ArgExpr = ICE->getSubExpr();
3776 HandleValue(ArgExpr, false /*AddressOf*/);
3777 return;
3778 }
3779 Inherited::VisitCXXConstructExpr(E);
3780 }
3781
3782 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3783 Expr *Callee = E->getCallee();
3784 if (isa<MemberExpr>(Callee)) {
3785 HandleValue(Callee, false /*AddressOf*/);
3786 for (auto Arg : E->arguments())
3787 Visit(Arg);
3788 return;
3789 }
3790
3791 Inherited::VisitCXXMemberCallExpr(E);
3792 }
3793
3794 void VisitCallExpr(CallExpr *E) {
3795 // Treat std::move as a use.
3796 if (E->isCallToStdMove()) {
3797 HandleValue(E->getArg(0), /*AddressOf=*/false);
3798 return;
3799 }
3800
3801 Inherited::VisitCallExpr(E);
3802 }
3803
3804 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3805 Expr *Callee = E->getCallee();
3806
3807 if (isa<UnresolvedLookupExpr>(Callee))
3808 return Inherited::VisitCXXOperatorCallExpr(E);
3809
3810 Visit(Callee);
3811 for (auto Arg : E->arguments())
3812 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3813 }
3814
3815 void VisitBinaryOperator(BinaryOperator *E) {
3816 // If a field assignment is detected, remove the field from the
3817 // uninitiailized field set.
3818 if (E->getOpcode() == BO_Assign)
3819 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3820 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3821 if (!FD->getType()->isReferenceType())
3822 DeclsToRemove.push_back(FD);
3823
3824 if (E->isCompoundAssignmentOp()) {
3825 HandleValue(E->getLHS(), false /*AddressOf*/);
3826 Visit(E->getRHS());
3827 return;
3828 }
3829
3830 Inherited::VisitBinaryOperator(E);
3831 }
3832
3833 void VisitUnaryOperator(UnaryOperator *E) {
3834 if (E->isIncrementDecrementOp()) {
3835 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3836 return;
3837 }
3838 if (E->getOpcode() == UO_AddrOf) {
3839 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3840 HandleValue(ME->getBase(), true /*AddressOf*/);
3841 return;
3842 }
3843 }
3844
3845 Inherited::VisitUnaryOperator(E);
3846 }
3847 };
3848
3849 // Diagnose value-uses of fields to initialize themselves, e.g.
3850 // foo(foo)
3851 // where foo is not also a parameter to the constructor.
3852 // Also diagnose across field uninitialized use such as
3853 // x(y), y(x)
3854 // TODO: implement -Wuninitialized and fold this into that framework.
3855 static void DiagnoseUninitializedFields(
3856 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3857
3858 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3859 Constructor->getLocation())) {
3860 return;
3861 }
3862
3863 if (Constructor->isInvalidDecl())
3864 return;
3865
3866 const CXXRecordDecl *RD = Constructor->getParent();
3867
3868 if (RD->isDependentContext())
3869 return;
3870
3871 // Holds fields that are uninitialized.
3872 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3873
3874 // At the beginning, all fields are uninitialized.
3875 for (auto *I : RD->decls()) {
3876 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3877 UninitializedFields.insert(FD);
3878 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3879 UninitializedFields.insert(IFD->getAnonField());
3880 }
3881 }
3882
3883 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3884 for (auto I : RD->bases())
3885 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3886
3887 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3888 return;
3889
3890 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3891 UninitializedFields,
3892 UninitializedBaseClasses);
3893
3894 for (const auto *FieldInit : Constructor->inits()) {
3895 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3896 break;
3897
3898 Expr *InitExpr = FieldInit->getInit();
3899 if (!InitExpr)
3900 continue;
3901
3902 if (CXXDefaultInitExpr *Default =
3903 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3904 InitExpr = Default->getExpr();
3905 if (!InitExpr)
3906 continue;
3907 // In class initializers will point to the constructor.
3908 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3909 FieldInit->getAnyMember(),
3910 FieldInit->getBaseClass());
3911 } else {
3912 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3913 FieldInit->getAnyMember(),
3914 FieldInit->getBaseClass());
3915 }
3916 }
3917 }
3918} // namespace
3919
3920/// Enter a new C++ default initializer scope. After calling this, the
3921/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3922/// parsing or instantiating the initializer failed.
3923void Sema::ActOnStartCXXInClassMemberInitializer() {
3924 // Create a synthetic function scope to represent the call to the constructor
3925 // that notionally surrounds a use of this initializer.
3926 PushFunctionScope();
3927}
3928
3929void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3930 if (!D.isFunctionDeclarator())
3931 return;
3932 auto &FTI = D.getFunctionTypeInfo();
3933 if (!FTI.Params)
3934 return;
3935 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3936 FTI.NumParams)) {
3937 auto *ParamDecl = cast<NamedDecl>(Param.Param);
3938 if (ParamDecl->getDeclName())
3939 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3940 }
3941}
3942
3943ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3944 return ActOnRequiresClause(ConstraintExpr);
3945}
3946
3947ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
3948 if (ConstraintExpr.isInvalid())
3949 return ExprError();
3950
3951 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
3952 if (ConstraintExpr.isInvalid())
3953 return ExprError();
3954
3955 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
3956 UPPC_RequiresClause))
3957 return ExprError();
3958
3959 return ConstraintExpr;
3960}
3961
3962/// This is invoked after parsing an in-class initializer for a
3963/// non-static C++ class member, and after instantiating an in-class initializer
3964/// in a class template. Such actions are deferred until the class is complete.
3965void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3966 SourceLocation InitLoc,
3967 Expr *InitExpr) {
3968 // Pop the notional constructor scope we created earlier.
3969 PopFunctionScopeInfo(nullptr, D);
3970
3971 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3972 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&(((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle
() != ICIS_NoInit) && "must set init style when field is created"
) ? static_cast<void> (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 3973, __PRETTY_FUNCTION__))
3973 "must set init style when field is created")(((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle
() != ICIS_NoInit) && "must set init style when field is created"
) ? static_cast<void> (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 3973, __PRETTY_FUNCTION__))
;
3974
3975 if (!InitExpr) {
3976 D->setInvalidDecl();
3977 if (FD)
3978 FD->removeInClassInitializer();
3979 return;
3980 }
3981
3982 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3983 FD->setInvalidDecl();
3984 FD->removeInClassInitializer();
3985 return;
3986 }
3987
3988 ExprResult Init = InitExpr;
3989 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3990 InitializedEntity Entity =
3991 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3992 InitializationKind Kind =
3993 FD->getInClassInitStyle() == ICIS_ListInit
3994 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3995 InitExpr->getBeginLoc(),
3996 InitExpr->getEndLoc())
3997 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3998 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3999 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4000 if (Init.isInvalid()) {
4001 FD->setInvalidDecl();
4002 return;
4003 }
4004 }
4005
4006 // C++11 [class.base.init]p7:
4007 // The initialization of each base and member constitutes a
4008 // full-expression.
4009 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4010 if (Init.isInvalid()) {
4011 FD->setInvalidDecl();
4012 return;
4013 }
4014
4015 InitExpr = Init.get();
4016
4017 FD->setInClassInitializer(InitExpr);
4018}
4019
4020/// Find the direct and/or virtual base specifiers that
4021/// correspond to the given base type, for use in base initialization
4022/// within a constructor.
4023static bool FindBaseInitializer(Sema &SemaRef,
4024 CXXRecordDecl *ClassDecl,
4025 QualType BaseType,
4026 const CXXBaseSpecifier *&DirectBaseSpec,
4027 const CXXBaseSpecifier *&VirtualBaseSpec) {
4028 // First, check for a direct base class.
4029 DirectBaseSpec = nullptr;
4030 for (const auto &Base : ClassDecl->bases()) {
4031 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4032 // We found a direct base of this type. That's what we're
4033 // initializing.
4034 DirectBaseSpec = &Base;
4035 break;
4036 }
4037 }
4038
4039 // Check for a virtual base class.
4040 // FIXME: We might be able to short-circuit this if we know in advance that
4041 // there are no virtual bases.
4042 VirtualBaseSpec = nullptr;
4043 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4044 // We haven't found a base yet; search the class hierarchy for a
4045 // virtual base class.
4046 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4047 /*DetectVirtual=*/false);
4048 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4049 SemaRef.Context.getTypeDeclType(ClassDecl),
4050 BaseType, Paths)) {
4051 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4052 Path != Paths.end(); ++Path) {
4053 if (Path->back().Base->isVirtual()) {
4054 VirtualBaseSpec = Path->back().Base;
4055 break;
4056 }
4057 }
4058 }
4059 }
4060
4061 return DirectBaseSpec || VirtualBaseSpec;
4062}
4063
4064/// Handle a C++ member initializer using braced-init-list syntax.
4065MemInitResult
4066Sema::ActOnMemInitializer(Decl *ConstructorD,
4067 Scope *S,
4068 CXXScopeSpec &SS,
4069 IdentifierInfo *MemberOrBase,
4070 ParsedType TemplateTypeTy,
4071 const DeclSpec &DS,
4072 SourceLocation IdLoc,
4073 Expr *InitList,
4074 SourceLocation EllipsisLoc) {
4075 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4076 DS, IdLoc, InitList,
4077 EllipsisLoc);
4078}
4079
4080/// Handle a C++ member initializer using parentheses syntax.
4081MemInitResult
4082Sema::ActOnMemInitializer(Decl *ConstructorD,
4083 Scope *S,
4084 CXXScopeSpec &SS,
4085 IdentifierInfo *MemberOrBase,
4086 ParsedType TemplateTypeTy,
4087 const DeclSpec &DS,
4088 SourceLocation IdLoc,
4089 SourceLocation LParenLoc,
4090 ArrayRef<Expr *> Args,
4091 SourceLocation RParenLoc,
4092 SourceLocation EllipsisLoc) {
4093 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4094 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4095 DS, IdLoc, List, EllipsisLoc);
4096}
4097
4098namespace {
4099
4100// Callback to only accept typo corrections that can be a valid C++ member
4101// intializer: either a non-static field member or a base class.
4102class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4103public:
4104 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4105 : ClassDecl(ClassDecl) {}
4106
4107 bool ValidateCandidate(const TypoCorrection &candidate) override {
4108 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4109 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4110 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4111 return isa<TypeDecl>(ND);
4112 }
4113 return false;
4114 }
4115
4116 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4117 return std::make_unique<MemInitializerValidatorCCC>(*this);
4118 }
4119
4120private:
4121 CXXRecordDecl *ClassDecl;
4122};
4123
4124}
4125
4126ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4127 CXXScopeSpec &SS,
4128 ParsedType TemplateTypeTy,
4129 IdentifierInfo *MemberOrBase) {
4130 if (SS.getScopeRep() || TemplateTypeTy)
4131 return nullptr;
4132 for (auto *D : ClassDecl->lookup(MemberOrBase))
4133 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4134 return cast<ValueDecl>(D);
4135 return nullptr;
4136}
4137
4138/// Handle a C++ member initializer.
4139MemInitResult
4140Sema::BuildMemInitializer(Decl *ConstructorD,
4141 Scope *S,
4142 CXXScopeSpec &SS,
4143 IdentifierInfo *MemberOrBase,
4144 ParsedType TemplateTypeTy,
4145 const DeclSpec &DS,
4146 SourceLocation IdLoc,
4147 Expr *Init,
4148 SourceLocation EllipsisLoc) {
4149 ExprResult Res = CorrectDelayedTyposInExpr(Init);
4150 if (!Res.isUsable())
4151 return true;
4152 Init = Res.get();
4153
4154 if (!ConstructorD)
4155 return true;
4156
4157 AdjustDeclIfTemplate(ConstructorD);
4158
4159 CXXConstructorDecl *Constructor
4160 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4161 if (!Constructor) {
4162 // The user wrote a constructor initializer on a function that is
4163 // not a C++ constructor. Ignore the error for now, because we may
4164 // have more member initializers coming; we'll diagnose it just
4165 // once in ActOnMemInitializers.
4166 return true;
4167 }
4168
4169 CXXRecordDecl *ClassDecl = Constructor->getParent();
4170
4171 // C++ [class.base.init]p2:
4172 // Names in a mem-initializer-id are looked up in the scope of the
4173 // constructor's class and, if not found in that scope, are looked
4174 // up in the scope containing the constructor's definition.
4175 // [Note: if the constructor's class contains a member with the
4176 // same name as a direct or virtual base class of the class, a
4177 // mem-initializer-id naming the member or base class and composed
4178 // of a single identifier refers to the class member. A
4179 // mem-initializer-id for the hidden base class may be specified
4180 // using a qualified name. ]
4181
4182 // Look for a member, first.
4183 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4184 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4185 if (EllipsisLoc.isValid())
4186 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4187 << MemberOrBase
4188 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4189
4190 return BuildMemberInitializer(Member, Init, IdLoc);
4191 }
4192 // It didn't name a member, so see if it names a class.
4193 QualType BaseType;
4194 TypeSourceInfo *TInfo = nullptr;
4195
4196 if (TemplateTypeTy) {
4197 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4198 if (BaseType.isNull())
4199 return true;
4200 } else if (DS.getTypeSpecType() == TST_decltype) {
4201 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4202 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4203 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4204 return true;
4205 } else {
4206 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4207 LookupParsedName(R, S, &SS);
4208
4209 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4210 if (!TyD) {
4211 if (R.isAmbiguous()) return true;
4212
4213 // We don't want access-control diagnostics here.
4214 R.suppressDiagnostics();
4215
4216 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4217 bool NotUnknownSpecialization = false;
4218 DeclContext *DC = computeDeclContext(SS, false);
4219 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4220 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4221
4222 if (!NotUnknownSpecialization) {
4223 // When the scope specifier can refer to a member of an unknown
4224 // specialization, we take it as a type name.
4225 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4226 SS.getWithLocInContext(Context),
4227 *MemberOrBase, IdLoc);
4228 if (BaseType.isNull())
4229 return true;
4230
4231 TInfo = Context.CreateTypeSourceInfo(BaseType);
4232 DependentNameTypeLoc TL =
4233 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4234 if (!TL.isNull()) {
4235 TL.setNameLoc(IdLoc);
4236 TL.setElaboratedKeywordLoc(SourceLocation());
4237 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4238 }
4239
4240 R.clear();
4241 R.setLookupName(MemberOrBase);
4242 }
4243 }
4244
4245 // If no results were found, try to correct typos.
4246 TypoCorrection Corr;
4247 MemInitializerValidatorCCC CCC(ClassDecl);
4248 if (R.empty() && BaseType.isNull() &&
4249 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4250 CCC, CTK_ErrorRecovery, ClassDecl))) {
4251 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4252 // We have found a non-static data member with a similar
4253 // name to what was typed; complain and initialize that
4254 // member.
4255 diagnoseTypo(Corr,
4256 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4257 << MemberOrBase << true);
4258 return BuildMemberInitializer(Member, Init, IdLoc);
4259 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4260 const CXXBaseSpecifier *DirectBaseSpec;
4261 const CXXBaseSpecifier *VirtualBaseSpec;
4262 if (FindBaseInitializer(*this, ClassDecl,
4263 Context.getTypeDeclType(Type),
4264 DirectBaseSpec, VirtualBaseSpec)) {
4265 // We have found a direct or virtual base class with a
4266 // similar name to what was typed; complain and initialize
4267 // that base class.
4268 diagnoseTypo(Corr,
4269 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4270 << MemberOrBase << false,
4271 PDiag() /*Suppress note, we provide our own.*/);
4272
4273 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4274 : VirtualBaseSpec;
4275 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4276 << BaseSpec->getType() << BaseSpec->getSourceRange();
4277
4278 TyD = Type;
4279 }
4280 }
4281 }
4282
4283 if (!TyD && BaseType.isNull()) {
4284 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4285 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4286 return true;
4287 }
4288 }
4289
4290 if (BaseType.isNull()) {
4291 BaseType = Context.getTypeDeclType(TyD);
4292 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4293 if (SS.isSet()) {
4294 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4295 BaseType);
4296 TInfo = Context.CreateTypeSourceInfo(BaseType);
4297 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4298 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4299 TL.setElaboratedKeywordLoc(SourceLocation());
4300 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4301 }
4302 }
4303 }
4304
4305 if (!TInfo)
4306 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4307
4308 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4309}
4310
4311MemInitResult
4312Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4313 SourceLocation IdLoc) {
4314 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4315 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4316 assert((DirectMember || IndirectMember) &&(((DirectMember || IndirectMember) && "Member must be a FieldDecl or IndirectFieldDecl"
) ? static_cast<void> (0) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 4317, __PRETTY_FUNCTION__))
4317 "Member must be a FieldDecl or IndirectFieldDecl")(((DirectMember || IndirectMember) && "Member must be a FieldDecl or IndirectFieldDecl"
) ? static_cast<void> (0) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 4317, __PRETTY_FUNCTION__))
;
4318
4319 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4320 return true;
4321
4322 if (Member->isInvalidDecl())
4323 return true;
4324
4325 MultiExprArg Args;
4326 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4327 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4328 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4329 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4330 } else {
4331 // Template instantiation doesn't reconstruct ParenListExprs for us.
4332 Args = Init;
4333 }
4334
4335 SourceRange InitRange = Init->getSourceRange();
4336
4337 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4338 // Can't check initialization for a member of dependent type or when
4339 // any of the arguments are type-dependent expressions.
4340 DiscardCleanupsInEvaluationContext();
4341 } else {
4342 bool InitList = false;
4343 if (isa<InitListExpr>(Init)) {
4344 InitList = true;
4345 Args = Init;
4346 }
4347
4348 // Initialize the member.
4349 InitializedEntity MemberEntity =
4350 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4351 : InitializedEntity::InitializeMember(IndirectMember,
4352 nullptr);
4353 InitializationKind Kind =
4354 InitList ? InitializationKind::CreateDirectList(
4355 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4356 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4357 InitRange.getEnd());
4358
4359 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4360 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4361 nullptr);
4362 if (MemberInit.isInvalid())
4363 return true;
4364
4365 // C++11 [class.base.init]p7:
4366 // The initialization of each base and member constitutes a
4367 // full-expression.
4368 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4369 /*DiscardedValue*/ false);
4370 if (MemberInit.isInvalid())
4371 return true;
4372
4373 Init = MemberInit.get();
4374 }
4375
4376 if (DirectMember) {
4377 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4378 InitRange.getBegin(), Init,
4379 InitRange.getEnd());
4380 } else {
4381 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4382 InitRange.getBegin(), Init,
4383 InitRange.getEnd());
4384 }
4385}
4386
4387MemInitResult
4388Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4389 CXXRecordDecl *ClassDecl) {
4390 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4391 if (!LangOpts.CPlusPlus11)
4392 return Diag(NameLoc, diag::err_delegating_ctor)
4393 << TInfo->getTypeLoc().getLocalSourceRange();
4394 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4395
4396 bool InitList = true;
4397 MultiExprArg Args = Init;
4398 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4399 InitList = false;
4400 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4401 }
4402
4403 SourceRange InitRange = Init->getSourceRange();
4404 // Initialize the object.
4405 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4406 QualType(ClassDecl->getTypeForDecl(), 0));
4407 InitializationKind Kind =
4408 InitList ? InitializationKind::CreateDirectList(
4409 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4410 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4411 InitRange.getEnd());
4412 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4413 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4414 Args, nullptr);
4415 if (DelegationInit.isInvalid())
4416 return true;
4417
4418 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&((cast<CXXConstructExpr>(DelegationInit.get())->getConstructor
() && "Delegating constructor with no target?") ? static_cast
<void> (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 4419, __PRETTY_FUNCTION__))
4419 "Delegating constructor with no target?")((cast<CXXConstructExpr>(DelegationInit.get())->getConstructor
() && "Delegating constructor with no target?") ? static_cast
<void> (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 4419, __PRETTY_FUNCTION__))
;
4420
4421 // C++11 [class.base.init]p7:
4422 // The initialization of each base and member constitutes a
4423 // full-expression.
4424 DelegationInit = ActOnFinishFullExpr(
4425 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4426 if (DelegationInit.isInvalid())
4427 return true;
4428
4429 // If we are in a dependent context, template instantiation will
4430 // perform this type-checking again. Just save the arguments that we
4431 // received in a ParenListExpr.
4432 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4433 // of the information that we have about the base
4434 // initializer. However, deconstructing the ASTs is a dicey process,
4435 // and this approach is far more likely to get the corner cases right.
4436 if (CurContext->isDependentContext())
4437 DelegationInit = Init;
4438
4439 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4440 DelegationInit.getAs<Expr>(),
4441 InitRange.getEnd());
4442}
4443
4444MemInitResult
4445Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4446 Expr *Init, CXXRecordDecl *ClassDecl,
4447 SourceLocation EllipsisLoc) {
4448 SourceLocation BaseLoc
4449 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4450
4451 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4452 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4453 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4454
4455 // C++ [class.base.init]p2:
4456 // [...] Unless the mem-initializer-id names a nonstatic data
4457 // member of the constructor's class or a direct or virtual base
4458 // of that class, the mem-initializer is ill-formed. A
4459 // mem-initializer-list can initialize a base class using any
4460 // name that denotes that base class type.
4461 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4462
4463 SourceRange InitRange = Init->getSourceRange();
4464 if (EllipsisLoc.isValid()) {
4465 // This is a pack expansion.
4466 if (!BaseType->containsUnexpandedParameterPack()) {
4467 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4468 << SourceRange(BaseLoc, InitRange.getEnd());
4469
4470 EllipsisLoc = SourceLocation();
4471 }
4472 } else {
4473 // Check for any unexpanded parameter packs.
4474 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4475 return true;
4476
4477 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4478 return true;
4479 }
4480
4481 // Check for direct and virtual base classes.
4482 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4483 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4484 if (!Dependent) {
4485 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4486 BaseType))
4487 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4488
4489 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4490 VirtualBaseSpec);
4491
4492 // C++ [base.class.init]p2:
4493 // Unless the mem-initializer-id names a nonstatic data member of the
4494 // constructor's class or a direct or virtual base of that class, the
4495 // mem-initializer is ill-formed.
4496 if (!DirectBaseSpec && !VirtualBaseSpec) {
4497 // If the class has any dependent bases, then it's possible that
4498 // one of those types will resolve to the same type as
4499 // BaseType. Therefore, just treat this as a dependent base
4500 // class initialization. FIXME: Should we try to check the
4501 // initialization anyway? It seems odd.
4502 if (ClassDecl->hasAnyDependentBases())
4503 Dependent = true;
4504 else
4505 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4506 << BaseType << Context.getTypeDeclType(ClassDecl)
4507 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4508 }
4509 }
4510
4511 if (Dependent) {
4512 DiscardCleanupsInEvaluationContext();
4513
4514 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4515 /*IsVirtual=*/false,
4516 InitRange.getBegin(), Init,
4517 InitRange.getEnd(), EllipsisLoc);
4518 }
4519
4520 // C++ [base.class.init]p2:
4521 // If a mem-initializer-id is ambiguous because it designates both
4522 // a direct non-virtual base class and an inherited virtual base
4523 // class, the mem-initializer is ill-formed.
4524 if (DirectBaseSpec && VirtualBaseSpec)
4525 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4526 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4527
4528 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4529 if (!BaseSpec)
4530 BaseSpec = VirtualBaseSpec;
4531
4532 // Initialize the base.
4533 bool InitList = true;
4534 MultiExprArg Args = Init;
4535 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4536 InitList = false;
4537 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4538 }
4539
4540 InitializedEntity BaseEntity =
4541 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4542 InitializationKind Kind =
4543 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4544 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4545 InitRange.getEnd());
4546 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4547 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4548 if (BaseInit.isInvalid())
4549 return true;
4550
4551 // C++11 [class.base.init]p7:
4552 // The initialization of each base and member constitutes a
4553 // full-expression.
4554 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4555 /*DiscardedValue*/ false);
4556 if (BaseInit.isInvalid())
4557 return true;
4558
4559 // If we are in a dependent context, template instantiation will
4560 // perform this type-checking again. Just save the arguments that we
4561 // received in a ParenListExpr.
4562 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4563 // of the information that we have about the base
4564 // initializer. However, deconstructing the ASTs is a dicey process,
4565 // and this approach is far more likely to get the corner cases right.
4566 if (CurContext->isDependentContext())
4567 BaseInit = Init;
4568
4569 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4570 BaseSpec->isVirtual(),
4571 InitRange.getBegin(),
4572 BaseInit.getAs<Expr>(),
4573 InitRange.getEnd(), EllipsisLoc);
4574}
4575
4576// Create a static_cast\<T&&>(expr).
4577static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4578 if (T.isNull()) T = E->getType();
4579 QualType TargetType = SemaRef.BuildReferenceType(
4580 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4581 SourceLocation ExprLoc = E->getBeginLoc();
4582 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4583 TargetType, ExprLoc);
4584
4585 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4586 SourceRange(ExprLoc, ExprLoc),
4587 E->getSourceRange()).get();
4588}
4589
4590/// ImplicitInitializerKind - How an implicit base or member initializer should
4591/// initialize its base or member.
4592enum ImplicitInitializerKind {
4593 IIK_Default,
4594 IIK_Copy,
4595 IIK_Move,
4596 IIK_Inherit
4597};
4598
4599static bool
4600BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4601 ImplicitInitializerKind ImplicitInitKind,
4602 CXXBaseSpecifier *BaseSpec,
4603 bool IsInheritedVirtualBase,
4604 CXXCtorInitializer *&CXXBaseInit) {
4605 InitializedEntity InitEntity
4606 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4607 IsInheritedVirtualBase);
4608
4609 ExprResult BaseInit;
4610
4611 switch (ImplicitInitKind) {
4612 case IIK_Inherit:
4613 case IIK_Default: {
4614 InitializationKind InitKind
4615 = InitializationKind::CreateDefault(Constructor->getLocation());
4616 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4617 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4618 break;
4619 }
4620
4621 case IIK_Move:
4622 case IIK_Copy: {
4623 bool Moving = ImplicitInitKind == IIK_Move;
4624 ParmVarDecl *Param = Constructor->getParamDecl(0);
4625 QualType ParamType = Param->getType().getNonReferenceType();
4626
4627 Expr *CopyCtorArg =
4628 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4629 SourceLocation(), Param, false,
4630 Constructor->getLocation(), ParamType,
4631 VK_LValue, nullptr);
4632
4633 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4634
4635 // Cast to the base class to avoid ambiguities.
4636 QualType ArgTy =
4637 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4638 ParamType.getQualifiers());
4639
4640 if (Moving) {
4641 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4642 }
4643
4644 CXXCastPath BasePath;
4645 BasePath.push_back(BaseSpec);
4646 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4647 CK_UncheckedDerivedToBase,
4648 Moving ? VK_XValue : VK_LValue,
4649 &BasePath).get();
4650
4651 InitializationKind InitKind
4652 = InitializationKind::CreateDirect(Constructor->getLocation(),
4653 SourceLocation(), SourceLocation());
4654 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4655 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4656 break;
4657 }
4658 }
4659
4660 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4661 if (BaseInit.isInvalid())
4662 return true;
4663
4664 CXXBaseInit =
4665 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4666 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4667 SourceLocation()),
4668 BaseSpec->isVirtual(),
4669 SourceLocation(),
4670 BaseInit.getAs<Expr>(),
4671 SourceLocation(),
4672 SourceLocation());
4673
4674 return false;
4675}
4676
4677static bool RefersToRValueRef(Expr *MemRef) {
4678 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4679 return Referenced->getType()->isRValueReferenceType();
4680}
4681
4682static bool
4683BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4684 ImplicitInitializerKind ImplicitInitKind,
4685 FieldDecl *Field, IndirectFieldDecl *Indirect,
4686 CXXCtorInitializer *&CXXMemberInit) {
4687 if (Field->isInvalidDecl())
4688 return true;
4689
4690 SourceLocation Loc = Constructor->getLocation();
4691
4692 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4693 bool Moving = ImplicitInitKind == IIK_Move;
4694 ParmVarDecl *Param = Constructor->getParamDecl(0);
4695 QualType ParamType = Param->getType().getNonReferenceType();
4696
4697 // Suppress copying zero-width bitfields.
4698 if (Field->isZeroLengthBitField(SemaRef.Context))
4699 return false;
4700
4701 Expr *MemberExprBase =
4702 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4703 SourceLocation(), Param, false,
4704 Loc, ParamType, VK_LValue, nullptr);
4705
4706 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4707
4708 if (Moving) {
4709 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4710 }
4711
4712 // Build a reference to this field within the parameter.
4713 CXXScopeSpec SS;
4714 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4715 Sema::LookupMemberName);
4716 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4717 : cast<ValueDecl>(Field), AS_public);
4718 MemberLookup.resolveKind();
4719 ExprResult CtorArg
4720 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4721 ParamType, Loc,
4722 /*IsArrow=*/false,
4723 SS,
4724 /*TemplateKWLoc=*/SourceLocation(),
4725 /*FirstQualifierInScope=*/nullptr,
4726 MemberLookup,
4727 /*TemplateArgs=*/nullptr,
4728 /*S*/nullptr);
4729 if (CtorArg.isInvalid())
4730 return true;
4731
4732 // C++11 [class.copy]p15:
4733 // - if a member m has rvalue reference type T&&, it is direct-initialized
4734 // with static_cast<T&&>(x.m);
4735 if (RefersToRValueRef(CtorArg.get())) {
4736 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4737 }
4738
4739 InitializedEntity Entity =
4740 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4741 /*Implicit*/ true)
4742 : InitializedEntity::InitializeMember(Field, nullptr,
4743 /*Implicit*/ true);
4744
4745 // Direct-initialize to use the copy constructor.
4746 InitializationKind InitKind =
4747 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4748
4749 Expr *CtorArgE = CtorArg.getAs<Expr>();
4750 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4751 ExprResult MemberInit =
4752 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4753 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4754 if (MemberInit.isInvalid())
4755 return true;
4756
4757 if (Indirect)
4758 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4759 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4760 else
4761 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4762 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4763 return false;
4764 }
4765
4766 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&(((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit
) && "Unhandled implicit init kind!") ? static_cast<
void> (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 4767, __PRETTY_FUNCTION__))
4767 "Unhandled implicit init kind!")(((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit
) && "Unhandled implicit init kind!") ? static_cast<
void> (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 4767, __PRETTY_FUNCTION__))
;
4768
4769 QualType FieldBaseElementType =
4770 SemaRef.Context.getBaseElementType(Field->getType());
4771
4772 if (FieldBaseElementType->isRecordType()) {
4773 InitializedEntity InitEntity =
4774 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4775 /*Implicit*/ true)
4776 : InitializedEntity::InitializeMember(Field, nullptr,
4777 /*Implicit*/ true);
4778 InitializationKind InitKind =
4779 InitializationKind::CreateDefault(Loc);
4780
4781 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4782 ExprResult MemberInit =
4783 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4784
4785 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4786 if (MemberInit.isInvalid())
4787 return true;
4788
4789 if (Indirect)
4790 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4791 Indirect, Loc,
4792 Loc,
4793 MemberInit.get(),
4794 Loc);
4795 else
4796 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4797 Field, Loc, Loc,
4798 MemberInit.get(),
4799 Loc);
4800 return false;
4801 }
4802
4803 if (!Field->getParent()->isUnion()) {
4804 if (FieldBaseElementType->isReferenceType()) {
4805 SemaRef.Diag(Constructor->getLocation(),
4806 diag::err_uninitialized_member_in_ctor)
4807 << (int)Constructor->isImplicit()
4808 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4809 << 0 << Field->getDeclName();
4810 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4811 return true;
4812 }
4813
4814 if (FieldBaseElementType.isConstQualified()) {
4815 SemaRef.Diag(Constructor->getLocation(),
4816 diag::err_uninitialized_member_in_ctor)
4817 << (int)Constructor->isImplicit()
4818 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4819 << 1 << Field->getDeclName();
4820 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4821 return true;
4822 }
4823 }
4824
4825 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4826 // ARC and Weak:
4827 // Default-initialize Objective-C pointers to NULL.
4828 CXXMemberInit
4829 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4830 Loc, Loc,
4831 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4832 Loc);
4833 return false;
4834 }
4835
4836 // Nothing to initialize.
4837 CXXMemberInit = nullptr;
4838 return false;
4839}
4840
4841namespace {
4842struct BaseAndFieldInfo {
4843 Sema &S;
4844 CXXConstructorDecl *Ctor;
4845 bool AnyErrorsInInits;
4846 ImplicitInitializerKind IIK;
4847 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4848 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4849 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4850
4851 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4852 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4853 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4854 if (Ctor->getInheritedConstructor())
4855 IIK = IIK_Inherit;
4856 else if (Generated && Ctor->isCopyConstructor())
4857 IIK = IIK_Copy;
4858 else if (Generated && Ctor->isMoveConstructor())
4859 IIK = IIK_Move;
4860 else
4861 IIK = IIK_Default;
4862 }
4863
4864 bool isImplicitCopyOrMove() const {
4865 switch (IIK) {
4866 case IIK_Copy:
4867 case IIK_Move:
4868 return true;
4869
4870 case IIK_Default:
4871 case IIK_Inherit:
4872 return false;
4873 }
4874
4875 llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 4875)
;
4876 }
4877
4878 bool addFieldInitializer(CXXCtorInitializer *Init) {
4879 AllToInit.push_back(Init);
4880
4881 // Check whether this initializer makes the field "used".
4882 if (Init->getInit()->HasSideEffects(S.Context))
4883 S.UnusedPrivateFields.remove(Init->getAnyMember());
4884
4885 return false;
4886 }
4887
4888 bool isInactiveUnionMember(FieldDecl *Field) {
4889 RecordDecl *Record = Field->getParent();
4890 if (!Record->isUnion())
4891 return false;
4892
4893 if (FieldDecl *Active =
4894 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4895 return Active != Field->getCanonicalDecl();
4896
4897 // In an implicit copy or move constructor, ignore any in-class initializer.
4898 if (isImplicitCopyOrMove())
4899 return true;
4900
4901 // If there's no explicit initialization, the field is active only if it
4902 // has an in-class initializer...
4903 if (Field->hasInClassInitializer())
4904 return false;
4905 // ... or it's an anonymous struct or union whose class has an in-class
4906 // initializer.
4907 if (!Field->isAnonymousStructOrUnion())
4908 return true;
4909 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4910 return !FieldRD->hasInClassInitializer();
4911 }
4912
4913 /// Determine whether the given field is, or is within, a union member
4914 /// that is inactive (because there was an initializer given for a different
4915 /// member of the union, or because the union was not initialized at all).
4916 bool isWithinInactiveUnionMember(FieldDecl *Field,
4917 IndirectFieldDecl *Indirect) {
4918 if (!Indirect)
4919 return isInactiveUnionMember(Field);
4920
4921 for (auto *C : Indirect->chain()) {
4922 FieldDecl *Field = dyn_cast<FieldDecl>(C);
4923 if (Field && isInactiveUnionMember(Field))
4924 return true;
4925 }
4926 return false;
4927 }
4928};
4929}
4930
4931/// Determine whether the given type is an incomplete or zero-lenfgth
4932/// array type.
4933static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4934 if (T->isIncompleteArrayType())
4935 return true;
4936
4937 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4938 if (!ArrayT->getSize())
4939 return true;
4940
4941 T = ArrayT->getElementType();
4942 }
4943
4944 return false;
4945}
4946
4947static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4948 FieldDecl *Field,
4949 IndirectFieldDecl *Indirect = nullptr) {
4950 if (Field->isInvalidDecl())
4951 return false;
4952
4953 // Overwhelmingly common case: we have a direct initializer for this field.
4954 if (CXXCtorInitializer *Init =
4955 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4956 return Info.addFieldInitializer(Init);
4957
4958 // C++11 [class.base.init]p8:
4959 // if the entity is a non-static data member that has a
4960 // brace-or-equal-initializer and either
4961 // -- the constructor's class is a union and no other variant member of that
4962 // union is designated by a mem-initializer-id or
4963 // -- the constructor's class is not a union, and, if the entity is a member
4964 // of an anonymous union, no other member of that union is designated by
4965 // a mem-initializer-id,
4966 // the entity is initialized as specified in [dcl.init].
4967 //
4968 // We also apply the same rules to handle anonymous structs within anonymous
4969 // unions.
4970 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4971 return false;
4972
4973 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4974 ExprResult DIE =
4975 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4976 if (DIE.isInvalid())
4977 return true;
4978
4979 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4980 SemaRef.checkInitializerLifetime(Entity, DIE.get());
4981
4982 CXXCtorInitializer *Init;
4983 if (Indirect)
4984 Init = new (SemaRef.Context)
4985 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4986 SourceLocation(), DIE.get(), SourceLocation());
4987 else
4988 Init = new (SemaRef.Context)
4989 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4990 SourceLocation(), DIE.get(), SourceLocation());
4991 return Info.addFieldInitializer(Init);
4992 }
4993
4994 // Don't initialize incomplete or zero-length arrays.
4995 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4996 return false;
4997
4998 // Don't try to build an implicit initializer if there were semantic
4999 // errors in any of the initializers (and therefore we might be
5000 // missing some that the user actually wrote).
5001 if (Info.AnyErrorsInInits)
5002 return false;
5003
5004 CXXCtorInitializer *Init = nullptr;
5005 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5006 Indirect, Init))
5007 return true;
5008
5009 if (!Init)
5010 return false;
5011
5012 return Info.addFieldInitializer(Init);
5013}
5014
5015bool
5016Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5017 CXXCtorInitializer *Initializer) {
5018 assert(Initializer->isDelegatingInitializer())((Initializer->isDelegatingInitializer()) ? static_cast<
void> (0) : __assert_fail ("Initializer->isDelegatingInitializer()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 5018, __PRETTY_FUNCTION__))
;
5019 Constructor->setNumCtorInitializers(1);
5020 CXXCtorInitializer **initializer =
5021 new (Context) CXXCtorInitializer*[1];
5022 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5023 Constructor->setCtorInitializers(initializer);
5024
5025 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5026 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5027 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5028 }
5029
5030 DelegatingCtorDecls.push_back(Constructor);
5031
5032 DiagnoseUninitializedFields(*this, Constructor);
5033
5034 return false;
5035}
5036
5037bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5038 ArrayRef<CXXCtorInitializer *> Initializers) {
5039 if (Constructor->isDependentContext()) {
5040 // Just store the initializers as written, they will be checked during
5041 // instantiation.
5042 if (!Initializers.empty()) {
5043 Constructor->setNumCtorInitializers(Initializers.size());
5044 CXXCtorInitializer **baseOrMemberInitializers =
5045 new (Context) CXXCtorInitializer*[Initializers.size()];
5046 memcpy(baseOrMemberInitializers, Initializers.data(),
5047 Initializers.size() * sizeof(CXXCtorInitializer*));
5048 Constructor->setCtorInitializers(baseOrMemberInitializers);
5049 }
5050
5051 // Let template instantiation know whether we had errors.
5052 if (AnyErrors)
5053 Constructor->setInvalidDecl();
5054
5055 return false;
5056 }
5057
5058 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5059
5060 // We need to build the initializer AST according to order of construction
5061 // and not what user specified in the Initializers list.
5062 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5063 if (!ClassDecl)
5064 return true;
5065
5066 bool HadError = false;
5067
5068 for (unsigned i = 0; i < Initializers.size(); i++) {
5069 CXXCtorInitializer *Member = Initializers[i];
5070
5071 if (Member->isBaseInitializer())
5072 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5073 else {
5074 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5075
5076 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5077 for (auto *C : F->chain()) {
5078 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5079 if (FD && FD->getParent()->isUnion())
5080 Info.ActiveUnionMember.insert(std::make_pair(
5081 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5082 }
5083 } else if (FieldDecl *FD = Member->getMember()) {
5084 if (FD->getParent()->isUnion())
5085 Info.ActiveUnionMember.insert(std::make_pair(
5086 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5087 }
5088 }
5089 }
5090
5091 // Keep track of the direct virtual bases.
5092 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5093 for (auto &I : ClassDecl->bases()) {
5094 if (I.isVirtual())
5095 DirectVBases.insert(&I);
5096 }
5097
5098 // Push virtual bases before others.
5099 for (auto &VBase : ClassDecl->vbases()) {
5100 if (CXXCtorInitializer *Value
5101 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5102 // [class.base.init]p7, per DR257:
5103 // A mem-initializer where the mem-initializer-id names a virtual base
5104 // class is ignored during execution of a constructor of any class that
5105 // is not the most derived class.
5106 if (ClassDecl->isAbstract()) {
5107 // FIXME: Provide a fixit to remove the base specifier. This requires
5108 // tracking the location of the associated comma for a base specifier.
5109 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5110 << VBase.getType() << ClassDecl;
5111 DiagnoseAbstractType(ClassDecl);
5112 }
5113
5114 Info.AllToInit.push_back(Value);
5115 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5116 // [class.base.init]p8, per DR257:
5117 // If a given [...] base class is not named by a mem-initializer-id
5118 // [...] and the entity is not a virtual base class of an abstract
5119 // class, then [...] the entity is default-initialized.
5120 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5121 CXXCtorInitializer *CXXBaseInit;
5122 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5123 &VBase, IsInheritedVirtualBase,
5124 CXXBaseInit)) {
5125 HadError = true;
5126 continue;
5127 }
5128
5129 Info.AllToInit.push_back(CXXBaseInit);
5130 }
5131 }
5132
5133 // Non-virtual bases.
5134 for (auto &Base : ClassDecl->bases()) {
5135 // Virtuals are in the virtual base list and already constructed.
5136 if (Base.isVirtual())
5137 continue;
5138
5139 if (CXXCtorInitializer *Value
5140 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5141 Info.AllToInit.push_back(Value);
5142 } else if (!AnyErrors) {
5143 CXXCtorInitializer *CXXBaseInit;
5144 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5145 &Base, /*IsInheritedVirtualBase=*/false,
5146 CXXBaseInit)) {
5147 HadError = true;
5148 continue;
5149 }
5150
5151 Info.AllToInit.push_back(CXXBaseInit);
5152 }
5153 }
5154
5155 // Fields.
5156 for (auto *Mem : ClassDecl->decls()) {
5157 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5158 // C++ [class.bit]p2:
5159 // A declaration for a bit-field that omits the identifier declares an
5160 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5161 // initialized.
5162 if (F->isUnnamedBitfield())
5163 continue;
5164
5165 // If we're not generating the implicit copy/move constructor, then we'll
5166 // handle anonymous struct/union fields based on their individual
5167 // indirect fields.
5168 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5169 continue;
5170
5171 if (CollectFieldInitializer(*this, Info, F))
5172 HadError = true;
5173 continue;
5174 }
5175
5176 // Beyond this point, we only consider default initialization.
5177 if (Info.isImplicitCopyOrMove())
5178 continue;
5179
5180 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5181 if (F->getType()->isIncompleteArrayType()) {
5182 assert(ClassDecl->hasFlexibleArrayMember() &&((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 5183, __PRETTY_FUNCTION__))
5183 "Incomplete array type is not valid")((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid"
) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 5183, __PRETTY_FUNCTION__))
;
5184 continue;
5185 }
5186
5187 // Initialize each field of an anonymous struct individually.
5188 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5189 HadError = true;
5190
5191 continue;
5192 }
5193 }
5194
5195 unsigned NumInitializers = Info.AllToInit.size();
5196 if (NumInitializers > 0) {
5197 Constructor->setNumCtorInitializers(NumInitializers);
5198 CXXCtorInitializer **baseOrMemberInitializers =
5199 new (Context) CXXCtorInitializer*[NumInitializers];
5200 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5201 NumInitializers * sizeof(CXXCtorInitializer*));
5202 Constructor->setCtorInitializers(baseOrMemberInitializers);
5203
5204 // Constructors implicitly reference the base and member
5205 // destructors.
5206 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5207 Constructor->getParent());
5208 }
5209
5210 return HadError;
5211}
5212
5213static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5214 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5215 const RecordDecl *RD = RT->getDecl();
5216 if (RD->isAnonymousStructOrUnion()) {
5217 for (auto *Field : RD->fields())
5218 PopulateKeysForFields(Field, IdealInits);
5219 return;
5220 }
5221 }
5222 IdealInits.push_back(Field->getCanonicalDecl());
5223}
5224
5225static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5226 return Context.getCanonicalType(BaseType).getTypePtr();
5227}
5228
5229static const void *GetKeyForMember(ASTContext &Context,
5230 CXXCtorInitializer *Member) {
5231 if (!Member->isAnyMemberInitializer())
5232 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5233
5234 return Member->getAnyMember()->getCanonicalDecl();
5235}
5236
5237static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5238 const CXXCtorInitializer *Previous,
5239 const CXXCtorInitializer *Current) {
5240 if (Previous->isAnyMemberInitializer())
5241 Diag << 0 << Previous->getAnyMember();
5242 else
5243 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5244
5245 if (Current->isAnyMemberInitializer())
5246 Diag << 0 << Current->getAnyMember();
5247 else
5248 Diag << 1 << Current->getTypeSourceInfo()->getType();
5249}
5250
5251static void DiagnoseBaseOrMemInitializerOrder(
5252 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5253 ArrayRef<CXXCtorInitializer *> Inits) {
5254 if (Constructor->getDeclContext()->isDependentContext())
5255 return;
5256
5257 // Don't check initializers order unless the warning is enabled at the
5258 // location of at least one initializer.
5259 bool ShouldCheckOrder = false;
5260 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5261 CXXCtorInitializer *Init = Inits[InitIndex];
5262 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5263 Init->getSourceLocation())) {
5264 ShouldCheckOrder = true;
5265 break;
5266 }
5267 }
5268 if (!ShouldCheckOrder)
5269 return;
5270
5271 // Build the list of bases and members in the order that they'll
5272 // actually be initialized. The explicit initializers should be in
5273 // this same order but may be missing things.
5274 SmallVector<const void*, 32> IdealInitKeys;
5275
5276 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5277
5278 // 1. Virtual bases.
5279 for (const auto &VBase : ClassDecl->vbases())
5280 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5281
5282 // 2. Non-virtual bases.
5283 for (const auto &Base : ClassDecl->bases()) {
5284 if (Base.isVirtual())
5285 continue;
5286 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5287 }
5288
5289 // 3. Direct fields.
5290 for (auto *Field : ClassDecl->fields()) {
5291 if (Field->isUnnamedBitfield())
5292 continue;
5293
5294 PopulateKeysForFields(Field, IdealInitKeys);
5295 }
5296
5297 unsigned NumIdealInits = IdealInitKeys.size();
5298 unsigned IdealIndex = 0;
5299
5300 // Track initializers that are in an incorrect order for either a warning or
5301 // note if multiple ones occur.
5302 SmallVector<unsigned> WarnIndexes;
5303 // Correlates the index of an initializer in the init-list to the index of
5304 // the field/base in the class.
5305 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5306
5307 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5308 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5309
5310 // Scan forward to try to find this initializer in the idealized
5311 // initializers list.
5312 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5313 if (InitKey == IdealInitKeys[IdealIndex])
5314 break;
5315
5316 // If we didn't find this initializer, it must be because we
5317 // scanned past it on a previous iteration. That can only
5318 // happen if we're out of order; emit a warning.
5319 if (IdealIndex == NumIdealInits && InitIndex) {
5320 WarnIndexes.push_back(InitIndex);
5321
5322 // Move back to the initializer's location in the ideal list.
5323 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5324 if (InitKey == IdealInitKeys[IdealIndex])
5325 break;
5326
5327 assert(IdealIndex < NumIdealInits &&((IdealIndex < NumIdealInits && "initializer not found in initializer list"
) ? static_cast<void> (0) : __assert_fail ("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 5328, __PRETTY_FUNCTION__))
5328 "initializer not found in initializer list")((IdealIndex < NumIdealInits && "initializer not found in initializer list"
) ? static_cast<void> (0) : __assert_fail ("IdealIndex < NumIdealInits && \"initializer not found in initializer list\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 5328, __PRETTY_FUNCTION__))
;
5329 }
5330 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5331 }
5332
5333 if (WarnIndexes.empty())
5334 return;
5335
5336 // Sort based on the ideal order, first in the pair.
5337 llvm::sort(CorrelatedInitOrder,
5338 [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; });
5339
5340 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5341 // emit the diagnostic before we can try adding notes.
5342 {
5343 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5344 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5345 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5346 : diag::warn_some_initializers_out_of_order);
5347
5348 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5349 if (CorrelatedInitOrder[I].second == I)
5350 continue;
5351 // Ideally we would be using InsertFromRange here, but clang doesn't
5352 // appear to handle InsertFromRange correctly when the source range is
5353 // modified by another fix-it.
5354 D << FixItHint::CreateReplacement(
5355 Inits[I]->getSourceRange(),
5356 Lexer::getSourceText(
5357 CharSourceRange::getTokenRange(
5358 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5359 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5360 }
5361
5362 // If there is only 1 item out of order, the warning expects the name and
5363 // type of each being added to it.
5364 if (WarnIndexes.size() == 1) {
5365 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5366 Inits[WarnIndexes.front()]);
5367 return;
5368 }
5369 }
5370 // More than 1 item to warn, create notes letting the user know which ones
5371 // are bad.
5372 for (unsigned WarnIndex : WarnIndexes) {
5373 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5374 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5375 diag::note_initializer_out_of_order);
5376 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5377 D << PrevInit->getSourceRange();
5378 }
5379}
5380
5381namespace {
5382bool CheckRedundantInit(Sema &S,
5383 CXXCtorInitializer *Init,
5384 CXXCtorInitializer *&PrevInit) {
5385 if (!PrevInit) {
5386 PrevInit = Init;
5387 return false;
5388 }
5389
5390 if (FieldDecl *Field = Init->getAnyMember())
5391 S.Diag(Init->getSourceLocation(),
5392 diag::err_multiple_mem_initialization)
5393 << Field->getDeclName()
5394 << Init->getSourceRange();
5395 else {
5396 const Type *BaseClass = Init->getBaseClass();
5397 assert(BaseClass && "neither field nor base")((BaseClass && "neither field nor base") ? static_cast
<void> (0) : __assert_fail ("BaseClass && \"neither field nor base\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 5397, __PRETTY_FUNCTION__))
;
5398 S.Diag(Init->getSourceLocation(),
5399 diag::err_multiple_base_initialization)
5400 << QualType(BaseClass, 0)
5401 << Init->getSourceRange();
5402 }
5403 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5404 << 0 << PrevInit->getSourceRange();
5405
5406 return true;
5407}
5408
5409typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5410typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5411
5412bool CheckRedundantUnionInit(Sema &S,
5413 CXXCtorInitializer *Init,
5414 RedundantUnionMap &Unions) {
5415 FieldDecl *Field = Init->getAnyMember();
5416 RecordDecl *Parent = Field->getParent();
5417 NamedDecl *Child = Field;
5418
5419 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5420 if (Parent->isUnion()) {
5421 UnionEntry &En = Unions[Parent];
5422 if (En.first && En.first != Child) {
5423 S.Diag(Init->getSourceLocation(),
5424 diag::err_multiple_mem_union_initialization)
5425 << Field->getDeclName()
5426 << Init->getSourceRange();
5427 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5428 << 0 << En.second->getSourceRange();
5429 return true;
5430 }
5431 if (!En.first) {
5432 En.first = Child;
5433 En.second = Init;
5434 }
5435 if (!Parent->isAnonymousStructOrUnion())
5436 return false;
5437 }
5438
5439 Child = Parent;
5440 Parent = cast<RecordDecl>(Parent->getDeclContext());
5441 }
5442
5443 return false;
5444}
5445} // namespace
5446
5447/// ActOnMemInitializers - Handle the member initializers for a constructor.
5448void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5449 SourceLocation ColonLoc,
5450 ArrayRef<CXXCtorInitializer*> MemInits,
5451 bool AnyErrors) {
5452 if (!ConstructorDecl)
5453 return;
5454
5455 AdjustDeclIfTemplate(ConstructorDecl);
5456
5457 CXXConstructorDecl *Constructor
5458 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5459
5460 if (!Constructor) {
5461 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5462 return;
5463 }
5464
5465 // Mapping for the duplicate initializers check.
5466 // For member initializers, this is keyed with a FieldDecl*.
5467 // For base initializers, this is keyed with a Type*.
5468 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5469
5470 // Mapping for the inconsistent anonymous-union initializers check.
5471 RedundantUnionMap MemberUnions;
5472
5473 bool HadError = false;
5474 for (unsigned i = 0; i < MemInits.size(); i++) {
5475 CXXCtorInitializer *Init = MemInits[i];
5476
5477 // Set the source order index.
5478 Init->setSourceOrder(i);
5479
5480 if (Init->isAnyMemberInitializer()) {
5481 const void *Key = GetKeyForMember(Context, Init);
5482 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5483 CheckRedundantUnionInit(*this, Init, MemberUnions))
5484 HadError = true;
5485 } else if (Init->isBaseInitializer()) {
5486 const void *Key = GetKeyForMember(Context, Init);
5487 if (CheckRedundantInit(*this, Init, Members[Key]))
5488 HadError = true;
5489 } else {
5490 assert(Init->isDelegatingInitializer())((Init->isDelegatingInitializer()) ? static_cast<void>
(0) : __assert_fail ("Init->isDelegatingInitializer()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 5490, __PRETTY_FUNCTION__))
;
5491 // This must be the only initializer
5492 if (MemInits.size() != 1) {
5493 Diag(Init->getSourceLocation(),
5494 diag::err_delegating_initializer_alone)
5495 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5496 // We will treat this as being the only initializer.
5497 }
5498 SetDelegatingInitializer(Constructor, MemInits[i]);
5499 // Return immediately as the initializer is set.
5500 return;
5501 }
5502 }
5503
5504 if (HadError)
5505 return;
5506
5507 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5508
5509 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5510
5511 DiagnoseUninitializedFields(*this, Constructor);
5512}
5513
5514void
5515Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5516 CXXRecordDecl *ClassDecl) {
5517 // Ignore dependent contexts. Also ignore unions, since their members never
5518 // have destructors implicitly called.
5519 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5520 return;
5521
5522 // FIXME: all the access-control diagnostics are positioned on the
5523 // field/base declaration. That's probably good; that said, the
5524 // user might reasonably want to know why the destructor is being
5525 // emitted, and we currently don't say.
5526
5527 // Non-static data members.
5528 for (auto *Field : ClassDecl->fields()) {
5529 if (Field->isInvalidDecl())
5530 continue;
5531
5532 // Don't destroy incomplete or zero-length arrays.
5533 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5534 continue;
5535
5536 QualType FieldType = Context.getBaseElementType(Field->getType());
5537
5538 const RecordType* RT = FieldType->getAs<RecordType>();
5539 if (!RT)
5540 continue;
5541
5542 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5543 if (FieldClassDecl->isInvalidDecl())
5544 continue;
5545 if (FieldClassDecl->hasIrrelevantDestructor())
5546 continue;
5547 // The destructor for an implicit anonymous union member is never invoked.
5548 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5549 continue;
5550
5551 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5552 assert(Dtor && "No dtor found for FieldClassDecl!")((Dtor && "No dtor found for FieldClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for FieldClassDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 5552, __PRETTY_FUNCTION__))
;
5553 CheckDestructorAccess(Field->getLocation(), Dtor,
5554 PDiag(diag::err_access_dtor_field)
5555 << Field->getDeclName()
5556 << FieldType);
5557
5558 MarkFunctionReferenced(Location, Dtor);
5559 DiagnoseUseOfDecl(Dtor, Location);
5560 }
5561
5562 // We only potentially invoke the destructors of potentially constructed
5563 // subobjects.
5564 bool VisitVirtualBases = !ClassDecl->isAbstract();
5565
5566 // If the destructor exists and has already been marked used in the MS ABI,
5567 // then virtual base destructors have already been checked and marked used.
5568 // Skip checking them again to avoid duplicate diagnostics.
5569 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5570 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5571 if (Dtor && Dtor->isUsed())
5572 VisitVirtualBases = false;
5573 }
5574
5575 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5576
5577 // Bases.
5578 for (const auto &Base : ClassDecl->bases()) {
5579 const RecordType *RT = Base.getType()->getAs<RecordType>();
5580 if (!RT)
5581 continue;
5582
5583 // Remember direct virtual bases.
5584 if (Base.isVirtual()) {
5585 if (!VisitVirtualBases)
5586 continue;
5587 DirectVirtualBases.insert(RT);
5588 }
5589
5590 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5591 // If our base class is invalid, we probably can't get its dtor anyway.
5592 if (BaseClassDecl->isInvalidDecl())
5593 continue;
5594 if (BaseClassDecl->hasIrrelevantDestructor())
5595 continue;
5596
5597 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5598 assert(Dtor && "No dtor found for BaseClassDecl!")((Dtor && "No dtor found for BaseClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 5598, __PRETTY_FUNCTION__))
;
5599
5600 // FIXME: caret should be on the start of the class name
5601 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5602 PDiag(diag::err_access_dtor_base)
5603 << Base.getType() << Base.getSourceRange(),
5604 Context.getTypeDeclType(ClassDecl));
5605
5606 MarkFunctionReferenced(Location, Dtor);
5607 DiagnoseUseOfDecl(Dtor, Location);
5608 }
5609
5610 if (VisitVirtualBases)
5611 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5612 &DirectVirtualBases);
5613}
5614
5615void Sema::MarkVirtualBaseDestructorsReferenced(
5616 SourceLocation Location, CXXRecordDecl *ClassDecl,
5617 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5618 // Virtual bases.
5619 for (const auto &VBase : ClassDecl->vbases()) {
5620 // Bases are always records in a well-formed non-dependent class.
5621 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5622
5623 // Ignore already visited direct virtual bases.
5624 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5625 continue;
5626
5627 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5628 // If our base class is invalid, we probably can't get its dtor anyway.
5629 if (BaseClassDecl->isInvalidDecl())
5630 continue;
5631 if (BaseClassDecl->hasIrrelevantDestructor())
5632 continue;
5633
5634 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5635 assert(Dtor && "No dtor found for BaseClassDecl!")((Dtor && "No dtor found for BaseClassDecl!") ? static_cast
<void> (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 5635, __PRETTY_FUNCTION__))
;
5636 if (CheckDestructorAccess(
5637 ClassDecl->getLocation(), Dtor,
5638 PDiag(diag::err_access_dtor_vbase)
5639 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5640 Context.getTypeDeclType(ClassDecl)) ==
5641 AR_accessible) {
5642 CheckDerivedToBaseConversion(
5643 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5644 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5645 SourceRange(), DeclarationName(), nullptr);
5646 }
5647
5648 MarkFunctionReferenced(Location, Dtor);
5649 DiagnoseUseOfDecl(Dtor, Location);
5650 }
5651}
5652
5653void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5654 if (!CDtorDecl)
5655 return;
5656
5657 if (CXXConstructorDecl *Constructor
5658 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5659 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5660 DiagnoseUninitializedFields(*this, Constructor);
5661 }
5662}
5663
5664bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5665 if (!getLangOpts().CPlusPlus)
5666 return false;
5667
5668 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5669 if (!RD)
5670 return false;
5671
5672 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5673 // class template specialization here, but doing so breaks a lot of code.
5674
5675 // We can't answer whether something is abstract until it has a
5676 // definition. If it's currently being defined, we'll walk back
5677 // over all the declarations when we have a full definition.
5678 const CXXRecordDecl *Def = RD->getDefinition();
5679 if (!Def || Def->isBeingDefined())
5680 return false;
5681
5682 return RD->isAbstract();
5683}
5684
5685bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5686 TypeDiagnoser &Diagnoser) {
5687 if (!isAbstractType(Loc, T))
5688 return false;
5689
5690 T = Context.getBaseElementType(T);
5691 Diagnoser.diagnose(*this, Loc, T);
5692 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5693 return true;
5694}
5695
5696void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5697 // Check if we've already emitted the list of pure virtual functions
5698 // for this class.
5699 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5700 return;
5701
5702 // If the diagnostic is suppressed, don't emit the notes. We're only
5703 // going to emit them once, so try to attach them to a diagnostic we're
5704 // actually going to show.
5705 if (Diags.isLastDiagnosticIgnored())
5706 return;
5707
5708 CXXFinalOverriderMap FinalOverriders;
5709 RD->getFinalOverriders(FinalOverriders);
5710
5711 // Keep a set of seen pure methods so we won't diagnose the same method
5712 // more than once.
5713 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5714
5715 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5716 MEnd = FinalOverriders.end();
5717 M != MEnd;
5718 ++M) {
5719 for (OverridingMethods::iterator SO = M->second.begin(),
5720 SOEnd = M->second.end();
5721 SO != SOEnd; ++SO) {
5722 // C++ [class.abstract]p4:
5723 // A class is abstract if it contains or inherits at least one
5724 // pure virtual function for which the final overrider is pure
5725 // virtual.
5726
5727 //
5728 if (SO->second.size() != 1)
5729 continue;
5730
5731 if (!SO->second.front().Method->isPure())
5732 continue;
5733
5734 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5735 continue;
5736
5737 Diag(SO->second.front().Method->getLocation(),
5738 diag::note_pure_virtual_function)
5739 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5740 }
5741 }
5742
5743 if (!PureVirtualClassDiagSet)
5744 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5745 PureVirtualClassDiagSet->insert(RD);
5746}
5747
5748namespace {
5749struct AbstractUsageInfo {
5750 Sema &S;
5751 CXXRecordDecl *Record;
5752 CanQualType AbstractType;
5753 bool Invalid;
5754
5755 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5756 : S(S), Record(Record),
5757 AbstractType(S.Context.getCanonicalType(
5758 S.Context.getTypeDeclType(Record))),
5759 Invalid(false) {}
5760
5761 void DiagnoseAbstractType() {
5762 if (Invalid) return;
5763 S.DiagnoseAbstractType(Record);
5764 Invalid = true;
5765 }
5766
5767 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5768};
5769
5770struct CheckAbstractUsage {
5771 AbstractUsageInfo &Info;
5772 const NamedDecl *Ctx;
5773
5774 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5775 : Info(Info), Ctx(Ctx) {}
5776
5777 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5778 switch (TL.getTypeLocClass()) {
5779#define ABSTRACT_TYPELOC(CLASS, PARENT)
5780#define TYPELOC(CLASS, PARENT) \
5781 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5782#include "clang/AST/TypeLocNodes.def"
5783 }
5784 }
5785
5786 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5787 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5788 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5789 if (!TL.getParam(I))
5790 continue;
5791
5792 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5793 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5794 }
5795 }
5796
5797 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5798 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5799 }
5800
5801 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5802 // Visit the type parameters from a permissive context.
5803 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5804 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5805 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5806 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5807 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5808 // TODO: other template argument types?
5809 }
5810 }
5811
5812 // Visit pointee types from a permissive context.
5813#define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc
(), Sema::AbstractNone); }
\
5814 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5815 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5816 }
5817 CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5818 CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5819 CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5820 CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5821 CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5822
5823 /// Handle all the types we haven't given a more specific
5824 /// implementation for above.
5825 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5826 // Every other kind of type that we haven't called out already
5827 // that has an inner type is either (1) sugar or (2) contains that
5828 // inner type in some way as a subobject.
5829 if (TypeLoc Next = TL.getNextTypeLoc())
5830 return Visit(Next, Sel);
5831
5832 // If there's no inner type and we're in a permissive context,
5833 // don't diagnose.
5834 if (Sel == Sema::AbstractNone) return;
5835
5836 // Check whether the type matches the abstract type.
5837 QualType T = TL.getType();
5838 if (T->isArrayType()) {
5839 Sel = Sema::AbstractArrayType;
5840 T = Info.S.Context.getBaseElementType(T);
5841 }
5842 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5843 if (CT != Info.AbstractType) return;
5844
5845 // It matched; do some magic.
5846 if (Sel == Sema::AbstractArrayType) {
5847 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5848 << T << TL.getSourceRange();
5849 } else {
5850 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5851 << Sel << T << TL.getSourceRange();
5852 }
5853 Info.DiagnoseAbstractType();
5854 }
5855};
5856
5857void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5858 Sema::AbstractDiagSelID Sel) {
5859 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5860}
5861
5862}
5863
5864/// Check for invalid uses of an abstract type in a method declaration.
5865static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5866 CXXMethodDecl *MD) {
5867 // No need to do the check on definitions, which require that
5868 // the return/param types be complete.
5869 if (MD->doesThisDeclarationHaveABody())
5870 return;
5871
5872 // For safety's sake, just ignore it if we don't have type source
5873 // information. This should never happen for non-implicit methods,
5874 // but...
5875 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5876 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5877}
5878
5879/// Check for invalid uses of an abstract type within a class definition.
5880static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5881 CXXRecordDecl *RD) {
5882 for (auto *D : RD->decls()) {
5883 if (D->isImplicit()) continue;
5884
5885 // Methods and method templates.
5886 if (isa<CXXMethodDecl>(D)) {
5887 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5888 } else if (isa<FunctionTemplateDecl>(D)) {
5889 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5890 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5891
5892 // Fields and static variables.
5893 } else if (isa<FieldDecl>(D)) {
5894 FieldDecl *FD = cast<FieldDecl>(D);
5895 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5896 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5897 } else if (isa<VarDecl>(D)) {
5898 VarDecl *VD = cast<VarDecl>(D);
5899 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5900 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5901
5902 // Nested classes and class templates.
5903 } else if (isa<CXXRecordDecl>(D)) {
5904 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5905 } else if (isa<ClassTemplateDecl>(D)) {
5906 CheckAbstractClassUsage(Info,
5907 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5908 }
5909 }
5910}
5911
5912static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5913 Attr *ClassAttr = getDLLAttr(Class);
5914 if (!ClassAttr)
5915 return;
5916
5917 assert(ClassAttr->getKind() == attr::DLLExport)((ClassAttr->getKind() == attr::DLLExport) ? static_cast<
void> (0) : __assert_fail ("ClassAttr->getKind() == attr::DLLExport"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Sema/SemaDeclCXX.cpp"
, 5917, __PRETTY_FUNCTION__))
;
5918
5919 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5920
5921 if (TSK == TSK_ExplicitInstantiationDeclaration)
5922 // Don't go any further if this is just an explicit instantiation
5923 // declaration.
5924 return;
5925
5926 // Add a context note to explain how we got to any diagnostics produced below.
5927 struct MarkingClassDllexported {
5928 Sema &S;
5929 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5930 SourceLocation AttrLoc)
5931 : S(S) {
5932 Sema::CodeSynthesisContext Ctx;
5933 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5934 Ctx.PointOfInstantiation = AttrLoc;
5935 Ctx.Entity = Class;
5936 S.pushCodeSynthesisContext(Ctx);
5937 }
5938 ~MarkingClassDllexported() {
5939 S.popCodeSynthesisContext();
5940 }
5941 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5942
5943 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5944 S.MarkVTableUsed(Class->getLocation(), Class, true);
5945
5946 for (Decl *Member : Class->decls()) {
5947 // Defined static variables that are members of an exported base
5948 // class must be marked export too.
5949 auto *VD = dyn_cast<VarDecl>(Member);
5950 if (VD && Member->getAttr<DLLExportAttr>() &&
5951 VD->getStorageClass() == SC_Static &&
5952 TSK == TSK_ImplicitInstantiation)
5953 S.MarkVariableReferenced(VD->getLocation(), VD);
5954
5955 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5956 if (!MD)
5957 continue;
5958
5959 if (Member->getAttr<DLLExportAttr>()) {
5960 if (MD->isUserProvided()) {
5961 // Instantiate non-default class member functions ...
5962
5963 // .. except for certain kinds of template specializations.
5964 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5965 continue;
5966
5967 S.MarkFunctionReferenced(Class->getLocation(), MD);
5968
5969 // The function will be passed to the consumer when its definition is
5970 // encountered.
5971 } else if (MD->isExplicitlyDefaulted()) {
5972 // Synthesize and instantiate explicitly defaulted methods.
5973 S.MarkFunctionReferenced(Class->getLocation(), MD);
5974
5975 if (TSK != TSK_ExplicitInstantiationDefinition) {
5976 // Except for explicit instantiation defs, we will not see the
5977 // definition again later, so pass it to the consumer now.
5978 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5979 }
5980 } else if (!MD->isTrivial() ||
5981 MD->isCopyAssignmentOperator() ||
5982 MD->isMoveAssignmentOperator()) {
5983 // Synthesize and instantiate non-trivial implicit methods, and the copy
5984 // and move assignment operators. The latter are exported even if they
5985 // are trivial, because the address of an operator can be taken and
5986 // should compare equal across libraries.
5987 S.MarkFunctionReferenced(Class->getLocation(), MD);
5988
5989 // There is no later point when we will see the definition of this
5990 // function, so pass it to the consumer now.
5991 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5992 }
5993 }
5994 }
5995}
5996
5997static void checkForMultipleExportedDefaultConstructors(Sema &S,
5998 CXXRecordDecl *Class) {
5999 // Only the MS ABI has default constructor closures, so we don't need to do
6000 // this semantic checking anywhere else.
6001 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6002 return;
6003
6004 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6005 for (Decl *Member : Class->decls()) {
6006 // Look for exported default constructors.
6007 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6008 if (!CD || !CD->isDefaultConstructor())
6009 continue;
6010 auto *Attr = CD->getAttr<DLLExportAttr>();
6011 if (!Attr)
6012 continue;
6013
6014 // If the class is non-dependent, mark the default arguments as ODR-used so
6015 // that we can properly codegen the constructor closure.
6016 if (!Class->isDependentContext()) {
6017 for (ParmVarDecl *PD : CD->parameters()) {
6018 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6019 S.DiscardCleanupsInEvaluationContext();
6020 }
6021 }
6022
6023 if (LastExportedDefaultCtor) {
6024 S.Diag(LastExportedDefaultCtor->getLocation(),
6025 diag::err_attribute_dll_ambiguous_default_ctor)
6026 << Class;
6027 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6028 << CD->getDeclName();
6029 return;
6030 }
6031 LastExportedDefaultCtor = CD;
6032 }
6033}
6034
6035static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6036 CXXRecordDecl *Class) {
6037 bool ErrorReported = false;
6038 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6039 ClassTemplateDecl *TD) {
6040 if (ErrorReported)
6041 return;
6042 S.Diag(TD->getLocation(),
6043 diag::err_cuda_device_builtin_surftex_cls_template)
6044 << /*surface*/ 0 << TD;
6045 ErrorReported = true;
6046 };
6047
6048 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6049 if (!TD) {
6050 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6051 if (!SD) {
6052 S.Diag(Class->getLocation(),
6053 diag::err_cuda_device_builtin_surftex_ref_decl)
6054 << /*surface*/ 0 << Class;
6055 S.Diag(Class->getLocation(),
6056 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6057 << Class;
6058 return;
6059 }
6060 TD = SD->getSpecializedTemplate();
6061 }
6062
6063 TemplateParameterList *Params = TD->getTemplateParameters();
6064 unsigned N = Params->size();
6065
6066 if (N != 2) {
6067 reportIllegalClassTemplate(S, TD);
6068 S.Diag(TD->getLocation(),
6069 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6070 << TD << 2;
6071 }
6072 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6073 reportIllegalClassTemplate(S, TD);
6074 S.Diag(TD->getLocation(),
6075 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6076 << TD << /*1st*/ 0 << /*type*/ 0;
6077 }
6078 if (N > 1) {
6079 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6080 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6081 reportIllegalClassTemplate(S, TD);
6082 S.Diag(TD->getLocation(),
6083 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6084 << TD << /*2nd*/ 1 << /*integer*/ 1;
6085 }
6086 }
6087}
6088
6089static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6090 CXXRecordDecl *Class) {
6091 bool ErrorReported = false;
6092 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6093 ClassTemplateDecl *TD) {
6094 if (ErrorReported)
6095 return;
6096 S.Diag(TD->getLocation(),
6097 diag::err_cuda_device_builtin_surftex_cls_template)
6098 << /*texture*/ 1 << TD;
6099 ErrorReported = true;
6100 };
6101
6102 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6103 if (!TD) {
6104 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6105 if (!SD) {
6106 S.Diag(Class->getLocation(),
6107 diag::err_cuda_device_builtin_surftex_ref_decl)
6108 << /*texture*/ 1 << Class;
6109 S.Diag(Class->getLocation(),
6110 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6111 << Class;
6112 return;
6113 }
6114 TD = SD->getSpecializedTemplate();
6115 }
6116
6117 TemplateParameterList *Params = TD->getTemplateParameters();
6118 unsigned N = Params->size();
6119
6120 if (N != 3) {
6121 reportIllegalClassTemplate(S, TD);
6122 S.Diag(TD->getLocation(),
6123 diag::note_cuda_device_builtin_surftex_cls_should_have