Bug Summary

File:clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 15555, column 10
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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