Bug Summary

File:tools/clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 14113, column 7
Value stored to 'IsMemberSpecialization' is never read

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