Bug Summary

File:tools/clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 15539, column 29
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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -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~svn373517/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn373517/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~svn373517/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn373517=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -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-10-02-234743-9763-1 -x c++ /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclCXX.cpp

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