Bug Summary

File:clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 5495, column 56
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 CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/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~++20200926111128+c6c5629f2fb/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb=. -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-09-26-161721-17566-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaDeclCXX.cpp

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