Bug Summary

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