Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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