Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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