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