Bug Summary

File:tools/clang/lib/Sema/SemaDeclCXX.cpp
Warning:line 10884, column 7
Passed-by-value struct argument contains uninitialized data (e.g., field: 'SavedInNonInstantiationSFINAEContext')

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