/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp
Line | Count | Source (jump to first uncovered line) |
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 | 93.7k | : 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 | 99.2k | bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) { |
79 | 99.2k | bool IsInvalid = false; |
80 | 99.2k | for (const Stmt *SubStmt : Node->children()) |
81 | 36.5k | IsInvalid |= Visit(SubStmt); |
82 | 99.2k | return IsInvalid; |
83 | 99.2k | } |
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 | 30.7k | bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) { |
89 | 30.7k | const NamedDecl *Decl = DRE->getDecl(); |
90 | 30.7k | 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 | 19 | if (DRE->isNonOdrUse() != NOUR_Unevaluated) |
100 | 13 | return S.Diag(DRE->getBeginLoc(), |
101 | 13 | diag::err_param_default_argument_references_param) |
102 | 13 | << Param->getDeclName() << DefaultArg->getSourceRange(); |
103 | 30.7k | } 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 | 13.4k | if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse()13 ) |
116 | 5 | return S.Diag(DRE->getBeginLoc(), |
117 | 5 | diag::err_param_default_argument_references_local) |
118 | 5 | << VDecl->getDeclName() << DefaultArg->getSourceRange(); |
119 | 13.4k | } |
120 | | |
121 | 30.7k | return false; |
122 | 30.7k | } |
123 | | |
124 | | /// VisitCXXThisExpr - Visit a C++ "this" expression. |
125 | 7 | 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 | 7 | return S.Diag(ThisE->getBeginLoc(), |
130 | 7 | diag::err_param_default_argument_references_this) |
131 | 7 | << ThisE->getSourceRange(); |
132 | 7 | } |
133 | | |
134 | | bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr( |
135 | 1 | const PseudoObjectExpr *POE) { |
136 | 1 | bool Invalid = false; |
137 | 2 | for (const Expr *E : POE->semantics()) { |
138 | | // Look through bindings. |
139 | 2 | if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) { |
140 | 1 | E = OVE->getSourceExpr(); |
141 | 1 | assert(E && "pseudo-object binding without source expression?"); |
142 | 1 | } |
143 | | |
144 | 0 | Invalid |= Visit(E); |
145 | 2 | } |
146 | 1 | return Invalid; |
147 | 1 | } |
148 | | |
149 | 324 | 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 | 324 | if (Lambda->capture_begin() == Lambda->capture_end()) |
154 | 321 | return false; |
155 | | |
156 | 3 | return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); |
157 | 324 | } |
158 | | } // namespace |
159 | | |
160 | | void |
161 | | Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, |
162 | 72.7k | const CXXMethodDecl *Method) { |
163 | | // If we have an MSAny spec already, don't bother. |
164 | 72.7k | if (!Method || ComputedEST == EST_MSAny) |
165 | 0 | return; |
166 | | |
167 | 72.7k | const FunctionProtoType *Proto |
168 | 72.7k | = Method->getType()->getAs<FunctionProtoType>(); |
169 | 72.7k | Proto = Self->ResolveExceptionSpec(CallLoc, Proto); |
170 | 72.7k | if (!Proto) |
171 | 1 | return; |
172 | | |
173 | 72.7k | ExceptionSpecificationType EST = Proto->getExceptionSpecType(); |
174 | | |
175 | | // If we have a throw-all spec at this point, ignore the function. |
176 | 72.7k | if (ComputedEST == EST_None) |
177 | 409 | return; |
178 | | |
179 | 72.3k | if (EST == EST_None && Method->hasAttr<NoThrowAttr>()1.49k ) |
180 | 0 | EST = EST_BasicNoexcept; |
181 | | |
182 | 72.3k | switch (EST) { |
183 | 0 | case EST_Unparsed: |
184 | 0 | case EST_Uninstantiated: |
185 | 0 | case EST_Unevaluated: |
186 | 0 | llvm_unreachable("should not see unresolved exception specs here"); |
187 | | |
188 | | // If this function can throw any exceptions, make a note of that. |
189 | 0 | case EST_MSAny: |
190 | 1.49k | 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 | 1.49k | ClearExceptions(); |
194 | 1.49k | ComputedEST = EST; |
195 | 1.49k | return; |
196 | 287 | case EST_NoexceptFalse: |
197 | 287 | ClearExceptions(); |
198 | 287 | ComputedEST = EST_None; |
199 | 287 | 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 | 69.8k | case EST_BasicNoexcept: |
204 | 69.8k | case EST_NoexceptTrue: |
205 | 69.8k | case EST_NoThrow: |
206 | 69.8k | return; |
207 | | // If we're still at noexcept(true) and there's a throw() callee, |
208 | | // change to that specification. |
209 | 669 | case EST_DynamicNone: |
210 | 669 | if (ComputedEST == EST_BasicNoexcept) |
211 | 18 | ComputedEST = EST_DynamicNone; |
212 | 669 | return; |
213 | 0 | case EST_DependentNoexcept: |
214 | 0 | llvm_unreachable( |
215 | 0 | "should not generate implicit declarations for dependent cases"); |
216 | 24 | case EST_Dynamic: |
217 | 24 | break; |
218 | 72.3k | } |
219 | 24 | assert(EST == EST_Dynamic && "EST case not considered earlier."); |
220 | 0 | assert(ComputedEST != EST_None && |
221 | 24 | "Shouldn't collect exceptions when throw-all is guaranteed."); |
222 | 0 | ComputedEST = EST_Dynamic; |
223 | | // Record the exceptions in this function's exception specification. |
224 | 24 | for (const auto &E : Proto->exceptions()) |
225 | 24 | if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) |
226 | 24 | Exceptions.push_back(E); |
227 | 24 | } |
228 | | |
229 | 1.37k | void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) { |
230 | 1.37k | if (!S || ComputedEST == EST_MSAny) |
231 | 0 | 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 | 1.37k | if (Self->canThrow(S)) |
255 | 272 | ComputedEST = EST_None; |
256 | 1.37k | } |
257 | | |
258 | | ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, |
259 | 93.8k | SourceLocation EqualLoc) { |
260 | 93.8k | if (RequireCompleteType(Param->getLocation(), Param->getType(), |
261 | 93.8k | diag::err_typecheck_decl_incomplete_type)) |
262 | 18 | 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 | 93.7k | InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, |
271 | 93.7k | Param); |
272 | 93.7k | InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), |
273 | 93.7k | EqualLoc); |
274 | 93.7k | InitializationSequence InitSeq(*this, Entity, Kind, Arg); |
275 | 93.7k | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); |
276 | 93.7k | if (Result.isInvalid()) |
277 | 37 | return true; |
278 | 93.7k | Arg = Result.getAs<Expr>(); |
279 | | |
280 | 93.7k | CheckCompletedExpr(Arg, EqualLoc); |
281 | 93.7k | Arg = MaybeCreateExprWithCleanups(Arg); |
282 | | |
283 | 93.7k | return Arg; |
284 | 93.7k | } |
285 | | |
286 | | void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, |
287 | 93.7k | SourceLocation EqualLoc) { |
288 | | // Add the default argument to the parameter |
289 | 93.7k | Param->setDefaultArg(Arg); |
290 | | |
291 | | // We have already instantiated this parameter; provide each of the |
292 | | // instantiations with the uninstantiated default argument. |
293 | 93.7k | UnparsedDefaultArgInstantiationsMap::iterator InstPos |
294 | 93.7k | = UnparsedDefaultArgInstantiations.find(Param); |
295 | 93.7k | if (InstPos != UnparsedDefaultArgInstantiations.end()) { |
296 | 14 | for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I9 ) |
297 | 9 | InstPos->second[I]->setUninstantiatedDefaultArg(Arg); |
298 | | |
299 | | // We're done tracking this parameter's instantiations. |
300 | 5 | UnparsedDefaultArgInstantiations.erase(InstPos); |
301 | 5 | } |
302 | 93.7k | } |
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 | 93.7k | Expr *DefaultArg) { |
310 | 93.7k | if (!param || !DefaultArg) |
311 | 0 | return; |
312 | | |
313 | 93.7k | ParmVarDecl *Param = cast<ParmVarDecl>(param); |
314 | 93.7k | UnparsedDefaultArgLocs.erase(Param); |
315 | | |
316 | 93.7k | auto Fail = [&] { |
317 | 102 | Param->setInvalidDecl(); |
318 | 102 | Param->setDefaultArg(new (Context) OpaqueValueExpr( |
319 | 102 | EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue)); |
320 | 102 | }; |
321 | | |
322 | | // Default arguments are only permitted in C++ |
323 | 93.7k | if (!getLangOpts().CPlusPlus) { |
324 | 1 | Diag(EqualLoc, diag::err_param_default_argument) |
325 | 1 | << DefaultArg->getSourceRange(); |
326 | 1 | return Fail(); |
327 | 1 | } |
328 | | |
329 | | // Check for unexpanded parameter packs. |
330 | 93.7k | if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { |
331 | 26 | return Fail(); |
332 | 26 | } |
333 | | |
334 | | // C++11 [dcl.fct.default]p3 |
335 | | // A default argument expression [...] shall not be specified for a |
336 | | // parameter pack. |
337 | 93.7k | if (Param->isParameterPack()) { |
338 | 1 | Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) |
339 | 1 | << DefaultArg->getSourceRange(); |
340 | | // Recover by discarding the default argument. |
341 | 1 | Param->setDefaultArg(nullptr); |
342 | 1 | return; |
343 | 1 | } |
344 | | |
345 | 93.7k | ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc); |
346 | 93.7k | if (Result.isInvalid()) |
347 | 48 | return Fail(); |
348 | | |
349 | 93.7k | DefaultArg = Result.getAs<Expr>(); |
350 | | |
351 | | // Check that the default argument is well-formed |
352 | 93.7k | CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg); |
353 | 93.7k | if (DefaultArgChecker.Visit(DefaultArg)) |
354 | 27 | return Fail(); |
355 | | |
356 | 93.6k | SetParamDefaultArgument(Param, DefaultArg, EqualLoc); |
357 | 93.6k | } |
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 | 76.3k | SourceLocation ArgLoc) { |
366 | 76.3k | if (!param) |
367 | 0 | return; |
368 | | |
369 | 76.3k | ParmVarDecl *Param = cast<ParmVarDecl>(param); |
370 | 76.3k | Param->setUnparsedDefaultArg(); |
371 | 76.3k | UnparsedDefaultArgLocs[Param] = ArgLoc; |
372 | 76.3k | } |
373 | | |
374 | | /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of |
375 | | /// the default argument for the parameter param failed. |
376 | | void Sema::ActOnParamDefaultArgumentError(Decl *param, |
377 | 305 | SourceLocation EqualLoc) { |
378 | 305 | if (!param) |
379 | 0 | return; |
380 | | |
381 | 305 | ParmVarDecl *Param = cast<ParmVarDecl>(param); |
382 | 305 | Param->setInvalidDecl(); |
383 | 305 | UnparsedDefaultArgLocs.erase(Param); |
384 | 305 | Param->setDefaultArg(new (Context) OpaqueValueExpr( |
385 | 305 | EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue)); |
386 | 305 | } |
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 | 49.5M | 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 | 49.5M | bool MightBeFunction = D.isFunctionDeclarationContext(); |
402 | 65.8M | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i16.2M ) { |
403 | 16.2M | DeclaratorChunk &chunk = D.getTypeObject(i); |
404 | 16.2M | if (chunk.Kind == DeclaratorChunk::Function) { |
405 | 11.2M | 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 | 11.0M | MightBeFunction = false; |
410 | 11.0M | continue; |
411 | 11.0M | } |
412 | 412k | for (unsigned argIdx = 0, e = chunk.Fun.NumParams; 157k argIdx != e; |
413 | 255k | ++argIdx) { |
414 | 255k | ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); |
415 | 255k | if (Param->hasUnparsedDefaultArg()) { |
416 | 3 | std::unique_ptr<CachedTokens> Toks = |
417 | 3 | std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); |
418 | 3 | SourceRange SR; |
419 | 3 | if (Toks->size() > 1) |
420 | 2 | SR = SourceRange((*Toks)[1].getLocation(), |
421 | 2 | Toks->back().getLocation()); |
422 | 1 | else |
423 | 1 | SR = UnparsedDefaultArgLocs[Param]; |
424 | 3 | Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) |
425 | 3 | << SR; |
426 | 255k | } else if (Param->getDefaultArg()) { |
427 | 10 | Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) |
428 | 10 | << Param->getDefaultArg()->getSourceRange(); |
429 | 10 | Param->setDefaultArg(nullptr); |
430 | 10 | } |
431 | 255k | } |
432 | 5.08M | } else if (chunk.Kind != DeclaratorChunk::Paren) { |
433 | 4.94M | MightBeFunction = false; |
434 | 4.94M | } |
435 | 16.2M | } |
436 | 49.5M | } |
437 | | |
438 | 45.1k | static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { |
439 | 88.6k | return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) { |
440 | 88.6k | return P->hasDefaultArg() && !P->hasInheritedDefaultArg()56 ; |
441 | 88.6k | }); |
442 | 45.1k | } |
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 | 285k | Scope *S) { |
450 | 285k | 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 | 285k | DeclContext *ScopeDC = New->isLocalExternDecl() |
456 | 285k | ? New->getLexicalDeclContext()222 |
457 | 285k | : New->getDeclContext()284k ; |
458 | | |
459 | | // Find the previous declaration for the purpose of default arguments. |
460 | 285k | FunctionDecl *PrevForDefaultArgs = Old; |
461 | 285k | 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 | 285k | PrevForDefaultArgs = 702 New->isLocalExternDecl()702 |
465 | 702 | ? nullptr181 |
466 | 285k | : PrevForDefaultArgs->getPreviousDecl()521 ) { |
467 | | // Ignore hidden declarations. |
468 | 285k | if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) |
469 | 447 | continue; |
470 | | |
471 | 284k | if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S)273k && |
472 | 284k | !New->isCXXClassMember()224 ) { |
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 | 224 | continue; |
477 | 224 | } |
478 | | |
479 | 284k | 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 | 31 | continue; |
485 | 31 | } |
486 | | |
487 | | // We found the right previous declaration. |
488 | 284k | break; |
489 | 284k | } |
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 | 285k | for (unsigned p = 0, NumParams = PrevForDefaultArgs |
510 | 285k | ? PrevForDefaultArgs->getNumParams()284k |
511 | 285k | : 0435 ; |
512 | 732k | p < NumParams; ++p447k ) { |
513 | 447k | ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); |
514 | 447k | ParmVarDecl *NewParam = New->getParamDecl(p); |
515 | | |
516 | 447k | bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false0 ; |
517 | 447k | bool NewParamHasDfl = NewParam->hasDefaultArg(); |
518 | | |
519 | 447k | if (OldParamHasDfl && NewParamHasDfl27.5k ) { |
520 | 14 | unsigned DiagDefaultParamID = |
521 | 14 | 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 | 14 | Invalid = true; |
526 | 14 | if (getLangOpts().MicrosoftExt) { |
527 | 3 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); |
528 | 3 | if (MD && MD->getParent()->getDescribedClassTemplate()) { |
529 | | // Merge the old default argument into the new parameter. |
530 | 3 | NewParam->setHasInheritedDefaultArg(); |
531 | 3 | if (OldParam->hasUninstantiatedDefaultArg()) |
532 | 0 | NewParam->setUninstantiatedDefaultArg( |
533 | 0 | OldParam->getUninstantiatedDefaultArg()); |
534 | 3 | else |
535 | 3 | NewParam->setDefaultArg(OldParam->getInit()); |
536 | 3 | DiagDefaultParamID = diag::ext_param_default_argument_redefinition; |
537 | 3 | Invalid = false; |
538 | 3 | } |
539 | 3 | } |
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 | 14 | Diag(NewParam->getLocation(), DiagDefaultParamID) |
550 | 14 | << 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 | 14 | for (auto Older = PrevForDefaultArgs; |
555 | 16 | OldParam->hasInheritedDefaultArg(); /**/) { |
556 | 2 | Older = Older->getPreviousDecl(); |
557 | 2 | OldParam = Older->getParamDecl(p); |
558 | 2 | } |
559 | | |
560 | 14 | Diag(OldParam->getLocation(), diag::note_previous_definition) |
561 | 14 | << OldParam->getDefaultArgRange(); |
562 | 447k | } 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 | 27.5k | if (New->getFriendObjectKind() == Decl::FOK_None || |
568 | 27.5k | !New->getLexicalDeclContext()->isDependentContext()333 ) { |
569 | | // It's important to use getInit() here; getDefaultArg() |
570 | | // strips off any top-level ExprWithCleanups. |
571 | 27.5k | NewParam->setHasInheritedDefaultArg(); |
572 | 27.5k | if (OldParam->hasUnparsedDefaultArg()) |
573 | 7 | NewParam->setUnparsedDefaultArg(); |
574 | 27.5k | else if (OldParam->hasUninstantiatedDefaultArg()) |
575 | 31 | NewParam->setUninstantiatedDefaultArg( |
576 | 31 | OldParam->getUninstantiatedDefaultArg()); |
577 | 27.5k | else |
578 | 27.5k | NewParam->setDefaultArg(OldParam->getInit()); |
579 | 27.5k | } |
580 | 419k | } else if (NewParamHasDfl) { |
581 | 104 | if (New->getDescribedFunctionTemplate()) { |
582 | | // Paragraph 4, quoted above, only applies to non-template functions. |
583 | 6 | Diag(NewParam->getLocation(), |
584 | 6 | diag::err_param_default_argument_template_redecl) |
585 | 6 | << NewParam->getDefaultArgRange(); |
586 | 6 | Diag(PrevForDefaultArgs->getLocation(), |
587 | 6 | diag::note_template_prev_declaration) |
588 | 6 | << false; |
589 | 98 | } else if (New->getTemplateSpecializationKind() |
590 | 98 | != TSK_ImplicitInstantiation && |
591 | 98 | 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 | 2 | Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) |
602 | 2 | << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) |
603 | 2 | << New->getDeclName() |
604 | 2 | << NewParam->getDefaultArgRange(); |
605 | 96 | } 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 | 7 | int WhichKind = 2; |
616 | 7 | if (CXXRecordDecl *Record |
617 | 7 | = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { |
618 | 7 | if (Record->getDescribedClassTemplate()) |
619 | 6 | WhichKind = 0; |
620 | 1 | else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) |
621 | 0 | WhichKind = 1; |
622 | 1 | else |
623 | 1 | WhichKind = 2; |
624 | 7 | } |
625 | | |
626 | 7 | Diag(NewParam->getLocation(), |
627 | 7 | diag::err_param_default_argument_member_template_redecl) |
628 | 7 | << WhichKind |
629 | 7 | << NewParam->getDefaultArgRange(); |
630 | 7 | } |
631 | 104 | } |
632 | 447k | } |
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 | 285k | if (isa<CXXConstructorDecl>(New) && |
638 | 285k | New->getMinRequiredArguments() < Old->getMinRequiredArguments()46.7k ) { |
639 | 7 | CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), |
640 | 7 | OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); |
641 | 7 | if (NewSM != OldSM) { |
642 | 7 | ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); |
643 | 7 | assert(NewParam->hasDefaultArg()); |
644 | 0 | Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) |
645 | 7 | << NewParam->getDefaultArgRange() << NewSM; |
646 | 7 | Diag(Old->getLocation(), diag::note_previous_declaration); |
647 | 7 | } |
648 | 7 | } |
649 | | |
650 | 0 | 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 | 285k | if (New->getConstexprKind() != Old->getConstexprKind()) { |
655 | 97 | Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) |
656 | 97 | << New << static_cast<int>(New->getConstexprKind()) |
657 | 97 | << static_cast<int>(Old->getConstexprKind()); |
658 | 97 | Diag(Old->getLocation(), diag::note_previous_declaration); |
659 | 97 | Invalid = true; |
660 | 284k | } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined()238k && |
661 | 284k | Old->isDefined(Def)76.8k && |
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 | 284k | (21 New->isInlineSpecified()21 || |
666 | 21 | New->getFriendObjectKind() == Decl::FOK_None2 )) { |
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 | 19 | Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; |
671 | 19 | Diag(Def->getLocation(), diag::note_previous_definition); |
672 | 19 | Invalid = true; |
673 | 19 | } |
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 | 285k | if (isa<CXXDeductionGuideDecl>(New) && |
680 | 285k | !New->isFunctionTemplateSpecialization()7 && isVisible(Old)3 ) { |
681 | 2 | Diag(New->getLocation(), diag::err_deduction_guide_redeclared); |
682 | 2 | Diag(Old->getLocation(), diag::note_previous_declaration); |
683 | 2 | } |
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 | 285k | if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && |
690 | 285k | functionDeclHasDefaultArgument(Old)2.19k ) { |
691 | 6 | Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); |
692 | 6 | Diag(Old->getLocation(), diag::note_previous_declaration); |
693 | 6 | Invalid = true; |
694 | 6 | } |
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 | 285k | const FunctionDecl *OldDefinition = nullptr; |
703 | 285k | if (New->isThisDeclarationInstantiatedFromAFriendDefinition() && |
704 | 285k | Old->isDefined(OldDefinition, true)43 ) |
705 | 25 | CheckForFunctionRedefinition(New, OldDefinition); |
706 | | |
707 | 285k | return Invalid; |
708 | 285k | } |
709 | | |
710 | | NamedDecl * |
711 | | Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, |
712 | 481 | MultiTemplateParamsArg TemplateParamLists) { |
713 | 481 | assert(D.isDecompositionDeclarator()); |
714 | 0 | 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 | 481 | if (!D.mayHaveDecompositionDeclarator()) { |
720 | 2 | Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) |
721 | 2 | << Decomp.getSourceRange(); |
722 | 2 | return nullptr; |
723 | 2 | } |
724 | | |
725 | 479 | 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 | 2 | Diag(TemplateParamLists.front()->getTemplateLoc(), |
729 | 2 | diag::err_decomp_decl_template); |
730 | 2 | return nullptr; |
731 | 2 | } |
732 | | |
733 | 477 | Diag(Decomp.getLSquareLoc(), |
734 | 477 | !getLangOpts().CPlusPlus17 |
735 | 477 | ? diag::ext_decomp_decl17 |
736 | 477 | : D.getContext() == DeclaratorContext::Condition460 |
737 | 460 | ? diag::ext_decomp_decl_cond30 |
738 | 460 | : diag::warn_cxx14_compat_decomp_decl430 ) |
739 | 477 | << Decomp.getSourceRange(); |
740 | | |
741 | | // The semantic context is always just the current context. |
742 | 477 | 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 | 477 | auto &DS = D.getDeclSpec(); |
751 | 477 | { |
752 | 477 | SmallVector<StringRef, 8> BadSpecifiers; |
753 | 477 | SmallVector<SourceLocation, 8> BadSpecifierLocs; |
754 | 477 | SmallVector<StringRef, 8> CPlusPlus20Specifiers; |
755 | 477 | SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; |
756 | 477 | if (auto SCS = DS.getStorageClassSpec()) { |
757 | 22 | if (SCS == DeclSpec::SCS_static) { |
758 | 17 | CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); |
759 | 17 | CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); |
760 | 17 | } else { |
761 | 5 | BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); |
762 | 5 | BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); |
763 | 5 | } |
764 | 22 | } |
765 | 477 | if (auto TSCS = DS.getThreadStorageClassSpec()) { |
766 | 8 | CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); |
767 | 8 | CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); |
768 | 8 | } |
769 | 477 | if (DS.hasConstexprSpecifier()) { |
770 | 4 | BadSpecifiers.push_back( |
771 | 4 | DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); |
772 | 4 | BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); |
773 | 4 | } |
774 | 477 | if (DS.isInlineSpecified()) { |
775 | 4 | BadSpecifiers.push_back("inline"); |
776 | 4 | BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); |
777 | 4 | } |
778 | 477 | if (!BadSpecifiers.empty()) { |
779 | 11 | auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); |
780 | 11 | Err << (int)BadSpecifiers.size() |
781 | 11 | << 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 | 11 | for (auto Loc : BadSpecifierLocs) |
785 | 13 | Err << SourceRange(Loc, Loc); |
786 | 466 | } else if (!CPlusPlus20Specifiers.empty()) { |
787 | 17 | auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), |
788 | 17 | getLangOpts().CPlusPlus20 |
789 | 17 | ? diag::warn_cxx17_compat_decomp_decl_spec5 |
790 | 17 | : diag::ext_decomp_decl_spec12 ); |
791 | 17 | Warn << (int)CPlusPlus20Specifiers.size() |
792 | 17 | << llvm::join(CPlusPlus20Specifiers.begin(), |
793 | 17 | CPlusPlus20Specifiers.end(), " "); |
794 | 17 | for (auto Loc : CPlusPlus20SpecifierLocs) |
795 | 21 | Warn << SourceRange(Loc, Loc); |
796 | 17 | } |
797 | | // We can't recover from it being declared as a typedef. |
798 | 477 | if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) |
799 | 2 | return nullptr; |
800 | 477 | } |
801 | | |
802 | | // C++2a [dcl.struct.bind]p1: |
803 | | // A cv that includes volatile is deprecated |
804 | 475 | if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && |
805 | 475 | getLangOpts().CPlusPlus205 ) |
806 | 1 | Diag(DS.getVolatileSpecLoc(), |
807 | 1 | diag::warn_deprecated_volatile_structured_binding); |
808 | | |
809 | 475 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); |
810 | 475 | QualType R = TInfo->getType(); |
811 | | |
812 | 475 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, |
813 | 475 | UPPC_DeclarationType)) |
814 | 0 | 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 | 475 | if (DS.getTypeSpecType() != DeclSpec::TST_auto || |
820 | 475 | D.hasGroupingParens()458 || D.getNumTypeObjects() > 1458 || |
821 | 475 | (458 D.getNumTypeObjects() == 1458 && |
822 | 458 | D.getTypeObject(0).Kind != DeclaratorChunk::Reference167 )) { |
823 | 23 | Diag(Decomp.getLSquareLoc(), |
824 | 23 | (D.hasGroupingParens() || |
825 | 23 | (D.getNumTypeObjects() && |
826 | 23 | D.getTypeObject(0).Kind == DeclaratorChunk::Paren6 )) |
827 | 23 | ? diag::err_decomp_decl_parens2 |
828 | 23 | : diag::err_decomp_decl_type21 ) |
829 | 23 | << 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 | 23 | if (R->isFunctionType()) |
835 | 0 | D.setInvalidType(); |
836 | 23 | } |
837 | | |
838 | | // Build the BindingDecls. |
839 | 475 | SmallVector<BindingDecl*, 8> Bindings; |
840 | | |
841 | | // Build the BindingDecls. |
842 | 972 | for (auto &B : D.getDecompositionDeclarator().bindings()) { |
843 | | // Check for name conflicts. |
844 | 972 | DeclarationNameInfo NameInfo(B.Name, B.NameLoc); |
845 | 972 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, |
846 | 972 | ForVisibleRedeclaration); |
847 | 972 | LookupName(Previous, S, |
848 | 972 | /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); |
849 | | |
850 | | // It's not permitted to shadow a template parameter name. |
851 | 972 | if (Previous.isSingleResult() && |
852 | 972 | Previous.getFoundDecl()->isTemplateParameter()62 ) { |
853 | 0 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), |
854 | 0 | Previous.getFoundDecl()); |
855 | 0 | Previous.clear(); |
856 | 0 | } |
857 | | |
858 | 972 | auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); |
859 | | |
860 | | // Find the shadowed declaration before filtering for scope. |
861 | 972 | NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() |
862 | 972 | ? getShadowedDeclaration(BD, Previous) |
863 | 972 | : nullptr0 ; |
864 | | |
865 | 972 | bool ConsiderLinkage = DC->isFunctionOrMethod() && |
866 | 972 | DS.getStorageClassSpec() == DeclSpec::SCS_extern888 ; |
867 | 972 | FilterLookupForScope(Previous, DC, S, ConsiderLinkage, |
868 | 972 | /*AllowInlineNamespace*/false); |
869 | | |
870 | 972 | if (!Previous.empty()) { |
871 | 1 | auto *Old = Previous.getRepresentativeDecl(); |
872 | 1 | Diag(B.NameLoc, diag::err_redefinition) << B.Name; |
873 | 1 | Diag(Old->getLocation(), diag::note_previous_definition); |
874 | 971 | } else if (ShadowedDecl && !D.isRedeclaration()8 ) { |
875 | 8 | CheckShadow(BD, ShadowedDecl, Previous); |
876 | 8 | } |
877 | 972 | PushOnScopeChains(BD, S, true); |
878 | 972 | Bindings.push_back(BD); |
879 | 972 | ParsingInitForAutoVars.insert(BD); |
880 | 972 | } |
881 | | |
882 | | // There are no prior lookup results for the variable itself, because it |
883 | | // is unnamed. |
884 | 475 | DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, |
885 | 475 | Decomp.getLSquareLoc()); |
886 | 475 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, |
887 | 475 | ForVisibleRedeclaration); |
888 | | |
889 | | // Build the variable that holds the non-decomposed object. |
890 | 475 | bool AddToScope = true; |
891 | 475 | NamedDecl *New = |
892 | 475 | ActOnVariableDeclarator(S, D, DC, TInfo, Previous, |
893 | 475 | MultiTemplateParamsArg(), AddToScope, Bindings); |
894 | 475 | if (AddToScope) { |
895 | 475 | S->AddDecl(New); |
896 | 475 | CurContext->addHiddenDecl(New); |
897 | 475 | } |
898 | | |
899 | 475 | if (isInOpenMPDeclareTargetContext()) |
900 | 0 | checkDeclIsAllowedInOpenMPTarget(nullptr, New); |
901 | | |
902 | 475 | return New; |
903 | 477 | } |
904 | | |
905 | | static bool checkSimpleDecomposition( |
906 | | Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, |
907 | | QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, |
908 | 145 | llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { |
909 | 145 | if ((int64_t)Bindings.size() != NumElems) { |
910 | 7 | S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) |
911 | 7 | << DecompType << (unsigned)Bindings.size() |
912 | 7 | << (unsigned)NumElems.getLimitedValue(UINT_MAX) |
913 | 7 | << toString(NumElems, 10) << (NumElems < Bindings.size()); |
914 | 7 | return true; |
915 | 7 | } |
916 | | |
917 | 138 | unsigned I = 0; |
918 | 334 | for (auto *B : Bindings) { |
919 | 334 | SourceLocation Loc = B->getLocation(); |
920 | 334 | ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); |
921 | 334 | if (E.isInvalid()) |
922 | 0 | return true; |
923 | 334 | E = GetInit(Loc, E.get(), I++); |
924 | 334 | if (E.isInvalid()) |
925 | 0 | return true; |
926 | 334 | B->setBinding(ElemType, E.get()); |
927 | 334 | } |
928 | | |
929 | 138 | return false; |
930 | 138 | } |
931 | | |
932 | | static bool checkArrayLikeDecomposition(Sema &S, |
933 | | ArrayRef<BindingDecl *> Bindings, |
934 | | ValueDecl *Src, QualType DecompType, |
935 | | const llvm::APSInt &NumElems, |
936 | 142 | QualType ElemType) { |
937 | 142 | return checkSimpleDecomposition( |
938 | 142 | S, Bindings, Src, DecompType, NumElems, ElemType, |
939 | 328 | [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { |
940 | 328 | ExprResult E = S.ActOnIntegerConstant(Loc, I); |
941 | 328 | if (E.isInvalid()) |
942 | 0 | return ExprError(); |
943 | 328 | return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); |
944 | 328 | }); |
945 | 142 | } |
946 | | |
947 | | static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, |
948 | | ValueDecl *Src, QualType DecompType, |
949 | 140 | const ConstantArrayType *CAT) { |
950 | 140 | return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, |
951 | 140 | llvm::APSInt(CAT->getSize()), |
952 | 140 | CAT->getElementType()); |
953 | 140 | } |
954 | | |
955 | | static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, |
956 | | ValueDecl *Src, QualType DecompType, |
957 | 2 | const VectorType *VT) { |
958 | 2 | return checkArrayLikeDecomposition( |
959 | 2 | S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), |
960 | 2 | S.Context.getQualifiedType(VT->getElementType(), |
961 | 2 | DecompType.getQualifiers())); |
962 | 2 | } |
963 | | |
964 | | static bool checkComplexDecomposition(Sema &S, |
965 | | ArrayRef<BindingDecl *> Bindings, |
966 | | ValueDecl *Src, QualType DecompType, |
967 | 3 | const ComplexType *CT) { |
968 | 3 | return checkSimpleDecomposition( |
969 | 3 | S, Bindings, Src, DecompType, llvm::APSInt::get(2), |
970 | 3 | S.Context.getQualifiedType(CT->getElementType(), |
971 | 3 | DecompType.getQualifiers()), |
972 | 6 | [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { |
973 | 6 | return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag3 : UO_Real3 , Base); |
974 | 6 | }); |
975 | 3 | } |
976 | | |
977 | | static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, |
978 | | TemplateArgumentListInfo &Args, |
979 | 4 | const TemplateParameterList *Params) { |
980 | 4 | SmallString<128> SS; |
981 | 4 | llvm::raw_svector_ostream OS(SS); |
982 | 4 | bool First = true; |
983 | 4 | unsigned I = 0; |
984 | 7 | for (auto &Arg : Args.arguments()) { |
985 | 7 | if (!First) |
986 | 3 | OS << ", "; |
987 | 7 | Arg.getArgument().print(PrintingPolicy, OS, |
988 | 7 | TemplateParameterList::shouldIncludeTypeForArgument( |
989 | 7 | PrintingPolicy, Params, I)); |
990 | 7 | First = false; |
991 | 7 | I++; |
992 | 7 | } |
993 | 4 | return std::string(OS.str()); |
994 | 4 | } |
995 | | |
996 | | static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, |
997 | | SourceLocation Loc, StringRef Trait, |
998 | | TemplateArgumentListInfo &Args, |
999 | 397 | unsigned DiagID) { |
1000 | 397 | auto DiagnoseMissing = [&] { |
1001 | 186 | if (DiagID) |
1002 | 1 | S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), |
1003 | 1 | Args, /*Params*/ nullptr); |
1004 | 186 | return true; |
1005 | 186 | }; |
1006 | | |
1007 | | // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. |
1008 | 397 | NamespaceDecl *Std = S.getStdNamespace(); |
1009 | 397 | if (!Std) |
1010 | 170 | 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 | 227 | LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), |
1018 | 227 | Loc, Sema::LookupOrdinaryName); |
1019 | 227 | if (!S.LookupQualifiedName(Result, Std)) |
1020 | 16 | return DiagnoseMissing(); |
1021 | 211 | if (Result.isAmbiguous()) |
1022 | 0 | return true; |
1023 | | |
1024 | 211 | ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); |
1025 | 211 | if (!TraitTD) { |
1026 | 0 | Result.suppressDiagnostics(); |
1027 | 0 | NamedDecl *Found = *Result.begin(); |
1028 | 0 | S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; |
1029 | 0 | S.Diag(Found->getLocation(), diag::note_declared_at); |
1030 | 0 | return true; |
1031 | 0 | } |
1032 | | |
1033 | | // Build the template-id. |
1034 | 211 | QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); |
1035 | 211 | if (TraitTy.isNull()) |
1036 | 0 | return true; |
1037 | 211 | if (!S.isCompleteType(Loc, TraitTy)) { |
1038 | 45 | if (DiagID) |
1039 | 2 | S.RequireCompleteType( |
1040 | 2 | Loc, TraitTy, DiagID, |
1041 | 2 | printTemplateArgs(S.Context.getPrintingPolicy(), Args, |
1042 | 2 | TraitTD->getTemplateParameters())); |
1043 | 45 | return true; |
1044 | 45 | } |
1045 | | |
1046 | 166 | CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); |
1047 | 166 | assert(RD && "specialization of class template is not a class?"); |
1048 | | |
1049 | | // Look up the member of the trait type. |
1050 | 0 | S.LookupQualifiedName(TraitMemberLookup, RD); |
1051 | 166 | return TraitMemberLookup.isAmbiguous(); |
1052 | 211 | } |
1053 | | |
1054 | | static TemplateArgumentLoc |
1055 | | getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, |
1056 | 209 | uint64_t I) { |
1057 | 209 | TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); |
1058 | 209 | return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); |
1059 | 209 | } |
1060 | | |
1061 | | static TemplateArgumentLoc |
1062 | 397 | getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { |
1063 | 397 | return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); |
1064 | 397 | } |
1065 | | |
1066 | | namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } |
1067 | | |
1068 | | static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, |
1069 | 294 | llvm::APSInt &Size) { |
1070 | 294 | EnterExpressionEvaluationContext ContextRAII( |
1071 | 294 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
1072 | | |
1073 | 294 | DeclarationName Value = S.PP.getIdentifierInfo("value"); |
1074 | 294 | LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); |
1075 | | |
1076 | | // Form template argument list for tuple_size<T>. |
1077 | 294 | TemplateArgumentListInfo Args(Loc, Loc); |
1078 | 294 | 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 | 294 | if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || |
1083 | 294 | R.empty()66 ) |
1084 | 230 | 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 | 64 | struct ICEDiagnoser : Sema::VerifyICEDiagnoser { |
1090 | 64 | LookupResult &R; |
1091 | 64 | TemplateArgumentListInfo &Args; |
1092 | 64 | ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) |
1093 | 64 | : R(R), Args(Args) {} |
1094 | 64 | Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, |
1095 | 64 | SourceLocation Loc) override { |
1096 | 1 | return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) |
1097 | 1 | << printTemplateArgs(S.Context.getPrintingPolicy(), Args, |
1098 | 1 | /*Params*/ nullptr); |
1099 | 1 | } |
1100 | 64 | } Diagnoser(R, Args); |
1101 | | |
1102 | 64 | ExprResult E = |
1103 | 64 | S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); |
1104 | 64 | if (E.isInvalid()) |
1105 | 0 | return IsTupleLike::Error; |
1106 | | |
1107 | 64 | E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser); |
1108 | 64 | if (E.isInvalid()) |
1109 | 1 | return IsTupleLike::Error; |
1110 | | |
1111 | 63 | return IsTupleLike::TupleLike; |
1112 | 64 | } |
1113 | | |
1114 | | /// \return std::tuple_element<I, T>::type. |
1115 | | static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, |
1116 | 103 | unsigned I, QualType T) { |
1117 | | // Form template argument list for tuple_element<I, T>. |
1118 | 103 | TemplateArgumentListInfo Args(Loc, Loc); |
1119 | 103 | Args.addArgument( |
1120 | 103 | getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); |
1121 | 103 | Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); |
1122 | | |
1123 | 103 | DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); |
1124 | 103 | LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); |
1125 | 103 | if (lookupStdTypeTraitMember( |
1126 | 103 | S, R, Loc, "tuple_element", Args, |
1127 | 103 | diag::err_decomp_decl_std_tuple_element_not_specialized)) |
1128 | 3 | return QualType(); |
1129 | | |
1130 | 100 | auto *TD = R.getAsSingle<TypeDecl>(); |
1131 | 100 | if (!TD) { |
1132 | 0 | R.suppressDiagnostics(); |
1133 | 0 | S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) |
1134 | 0 | << printTemplateArgs(S.Context.getPrintingPolicy(), Args, |
1135 | 0 | /*Params*/ nullptr); |
1136 | 0 | if (!R.empty()) |
1137 | 0 | S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); |
1138 | 0 | return QualType(); |
1139 | 0 | } |
1140 | | |
1141 | 100 | return S.Context.getTypeDeclType(TD); |
1142 | 100 | } |
1143 | | |
1144 | | namespace { |
1145 | | struct InitializingBinding { |
1146 | | Sema &S; |
1147 | 106 | InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { |
1148 | 106 | Sema::CodeSynthesisContext Ctx; |
1149 | 106 | Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; |
1150 | 106 | Ctx.PointOfInstantiation = BD->getLocation(); |
1151 | 106 | Ctx.Entity = BD; |
1152 | 106 | S.pushCodeSynthesisContext(Ctx); |
1153 | 106 | } |
1154 | 106 | ~InitializingBinding() { |
1155 | 106 | S.popCodeSynthesisContext(); |
1156 | 106 | } |
1157 | | }; |
1158 | | } |
1159 | | |
1160 | | static bool checkTupleLikeDecomposition(Sema &S, |
1161 | | ArrayRef<BindingDecl *> Bindings, |
1162 | | VarDecl *Src, QualType DecompType, |
1163 | 63 | const llvm::APSInt &TupleSize) { |
1164 | 63 | if ((int64_t)Bindings.size() != TupleSize) { |
1165 | 3 | S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) |
1166 | 3 | << DecompType << (unsigned)Bindings.size() |
1167 | 3 | << (unsigned)TupleSize.getLimitedValue(UINT_MAX) |
1168 | 3 | << toString(TupleSize, 10) << (TupleSize < Bindings.size()); |
1169 | 3 | return true; |
1170 | 3 | } |
1171 | | |
1172 | 60 | if (Bindings.empty()) |
1173 | 0 | return false; |
1174 | | |
1175 | 60 | 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 | 60 | LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); |
1181 | 60 | bool UseMemberGet = false; |
1182 | 60 | if (S.isCompleteType(Src->getLocation(), DecompType)) { |
1183 | 60 | if (auto *RD = DecompType->getAsCXXRecordDecl()) |
1184 | 60 | S.LookupQualifiedName(MemberGet, RD); |
1185 | 60 | if (MemberGet.isAmbiguous()) |
1186 | 1 | 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 | 59 | for (NamedDecl *D : MemberGet) { |
1190 | 35 | if (FunctionTemplateDecl *FTD = |
1191 | 35 | dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { |
1192 | 31 | TemplateParameterList *TPL = FTD->getTemplateParameters(); |
1193 | 31 | if (TPL->size() != 0 && |
1194 | 31 | isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { |
1195 | | // ... the initializer is e.get<i>(). |
1196 | 29 | UseMemberGet = true; |
1197 | 29 | break; |
1198 | 29 | } |
1199 | 31 | } |
1200 | 35 | } |
1201 | 59 | } |
1202 | | |
1203 | 59 | unsigned I = 0; |
1204 | 106 | for (auto *B : Bindings) { |
1205 | 106 | InitializingBinding InitContext(S, B); |
1206 | 106 | SourceLocation Loc = B->getLocation(); |
1207 | | |
1208 | 106 | ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); |
1209 | 106 | if (E.isInvalid()) |
1210 | 0 | return true; |
1211 | | |
1212 | | // e is an lvalue if the type of the entity is an lvalue reference and |
1213 | | // an xvalue otherwise |
1214 | 106 | if (!Src->getType()->isLValueReferenceType()) |
1215 | 77 | E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, |
1216 | 77 | E.get(), nullptr, VK_XValue, |
1217 | 77 | FPOptionsOverride()); |
1218 | | |
1219 | 106 | TemplateArgumentListInfo Args(Loc, Loc); |
1220 | 106 | Args.addArgument( |
1221 | 106 | getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); |
1222 | | |
1223 | 106 | if (UseMemberGet) { |
1224 | | // if [lookup of member get] finds at least one declaration, the |
1225 | | // initializer is e.get<i-1>(). |
1226 | 37 | E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, |
1227 | 37 | CXXScopeSpec(), SourceLocation(), nullptr, |
1228 | 37 | MemberGet, &Args, nullptr); |
1229 | 37 | if (E.isInvalid()) |
1230 | 0 | return true; |
1231 | | |
1232 | 37 | E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); |
1233 | 69 | } else { |
1234 | | // Otherwise, the initializer is get<i-1>(e), where get is looked up |
1235 | | // in the associated namespaces. |
1236 | 69 | Expr *Get = UnresolvedLookupExpr::Create( |
1237 | 69 | S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), |
1238 | 69 | DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, |
1239 | 69 | UnresolvedSetIterator(), UnresolvedSetIterator()); |
1240 | | |
1241 | 69 | Expr *Arg = E.get(); |
1242 | 69 | E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); |
1243 | 69 | } |
1244 | 106 | if (E.isInvalid()) |
1245 | 3 | return true; |
1246 | 103 | Expr *Init = E.get(); |
1247 | | |
1248 | | // Given the type T designated by std::tuple_element<i - 1, E>::type, |
1249 | 103 | QualType T = getTupleLikeElementType(S, Loc, I, DecompType); |
1250 | 103 | if (T.isNull()) |
1251 | 3 | 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 | 100 | QualType RefType = |
1257 | 100 | S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); |
1258 | 100 | if (RefType.isNull()) |
1259 | 0 | return true; |
1260 | 100 | auto *RefVD = VarDecl::Create( |
1261 | 100 | S.Context, Src->getDeclContext(), Loc, Loc, |
1262 | 100 | B->getDeclName().getAsIdentifierInfo(), RefType, |
1263 | 100 | S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); |
1264 | 100 | RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); |
1265 | 100 | RefVD->setTSCSpec(Src->getTSCSpec()); |
1266 | 100 | RefVD->setImplicit(); |
1267 | 100 | if (Src->isInlineSpecified()) |
1268 | 0 | RefVD->setInlineSpecified(); |
1269 | 100 | RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); |
1270 | | |
1271 | 100 | InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); |
1272 | 100 | InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); |
1273 | 100 | InitializationSequence Seq(S, Entity, Kind, Init); |
1274 | 100 | E = Seq.Perform(S, Entity, Kind, Init); |
1275 | 100 | if (E.isInvalid()) |
1276 | 2 | return true; |
1277 | 98 | E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); |
1278 | 98 | if (E.isInvalid()) |
1279 | 0 | return true; |
1280 | 98 | RefVD->setInit(E.get()); |
1281 | 98 | S.CheckCompleteVariableDeclaration(RefVD); |
1282 | | |
1283 | 98 | E = S.BuildDeclarationNameExpr(CXXScopeSpec(), |
1284 | 98 | DeclarationNameInfo(B->getDeclName(), Loc), |
1285 | 98 | RefVD); |
1286 | 98 | if (E.isInvalid()) |
1287 | 0 | return true; |
1288 | | |
1289 | 98 | B->setBinding(T, E.get()); |
1290 | 98 | I++; |
1291 | 98 | } |
1292 | | |
1293 | 51 | return false; |
1294 | 59 | } |
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 | 223 | CXXCastPath &BasePath) { |
1302 | 223 | auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, |
1303 | 223 | CXXBasePath &Path) { |
1304 | 33 | return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); |
1305 | 33 | }; |
1306 | | |
1307 | 223 | const CXXRecordDecl *ClassWithFields = nullptr; |
1308 | 223 | AccessSpecifier AS = AS_public; |
1309 | 223 | 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 | 198 | ClassWithFields = RD; |
1314 | 25 | else { |
1315 | | // ... or of ... |
1316 | 25 | CXXBasePaths Paths; |
1317 | 25 | Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); |
1318 | 25 | 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 | 7 | return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); |
1322 | 7 | } |
1323 | | |
1324 | 18 | CXXBasePath *BestPath = nullptr; |
1325 | 22 | for (auto &P : Paths) { |
1326 | 22 | if (!BestPath) |
1327 | 18 | BestPath = &P; |
1328 | 4 | else if (!S.Context.hasSameType(P.back().Base->getType(), |
1329 | 4 | BestPath->back().Base->getType())) { |
1330 | | // ... the same ... |
1331 | 1 | S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) |
1332 | 1 | << false << RD << BestPath->back().Base->getType() |
1333 | 1 | << P.back().Base->getType(); |
1334 | 1 | return DeclAccessPair(); |
1335 | 3 | } else if (P.Access < BestPath->Access) { |
1336 | 0 | BestPath = &P; |
1337 | 0 | } |
1338 | 22 | } |
1339 | | |
1340 | | // ... unambiguous ... |
1341 | 17 | QualType BaseType = BestPath->back().Base->getType(); |
1342 | 17 | if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { |
1343 | 2 | S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) |
1344 | 2 | << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); |
1345 | 2 | return DeclAccessPair(); |
1346 | 2 | } |
1347 | | |
1348 | | // ... [accessible, implied by other rules] base class of E. |
1349 | 15 | S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), |
1350 | 15 | *BestPath, diag::err_decomp_decl_inaccessible_base); |
1351 | 15 | AS = BestPath->Access; |
1352 | | |
1353 | 15 | ClassWithFields = BaseType->getAsCXXRecordDecl(); |
1354 | 15 | S.BuildBasePathArray(Paths, BasePath); |
1355 | 15 | } |
1356 | | |
1357 | | // The above search did not check whether the selected class itself has base |
1358 | | // classes with fields, so check that now. |
1359 | 213 | CXXBasePaths Paths; |
1360 | 213 | if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { |
1361 | 2 | S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) |
1362 | 2 | << (ClassWithFields == RD) << RD << ClassWithFields |
1363 | 2 | << Paths.front().back().Base->getType(); |
1364 | 2 | return DeclAccessPair(); |
1365 | 2 | } |
1366 | | |
1367 | 211 | return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); |
1368 | 213 | } |
1369 | | |
1370 | | static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, |
1371 | | ValueDecl *Src, QualType DecompType, |
1372 | 223 | const CXXRecordDecl *OrigRD) { |
1373 | 223 | if (S.RequireCompleteType(Src->getLocation(), DecompType, |
1374 | 223 | diag::err_incomplete_type)) |
1375 | 0 | return true; |
1376 | | |
1377 | 223 | CXXCastPath BasePath; |
1378 | 223 | DeclAccessPair BasePair = |
1379 | 223 | findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); |
1380 | 223 | const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); |
1381 | 223 | if (!RD) |
1382 | 5 | return true; |
1383 | 218 | QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), |
1384 | 218 | DecompType.getQualifiers()); |
1385 | | |
1386 | 218 | auto DiagnoseBadNumberOfBindings = [&]() -> bool { |
1387 | 8 | unsigned NumFields = llvm::count_if( |
1388 | 10 | RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); |
1389 | 8 | assert(Bindings.size() != NumFields); |
1390 | 0 | S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) |
1391 | 8 | << DecompType << (unsigned)Bindings.size() << NumFields << NumFields |
1392 | 8 | << (NumFields < Bindings.size()); |
1393 | 8 | return true; |
1394 | 8 | }; |
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 | 218 | unsigned I = 0; |
1400 | 437 | for (auto *FD : RD->fields()) { |
1401 | 437 | if (FD->isUnnamedBitfield()) |
1402 | 2 | continue; |
1403 | | |
1404 | | // All the non-static data members are required to be nameable, so they |
1405 | | // must all have names. |
1406 | 435 | if (!FD->getDeclName()) { |
1407 | 4 | if (RD->isLambda()) { |
1408 | 2 | S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda); |
1409 | 2 | S.Diag(RD->getLocation(), diag::note_lambda_decl); |
1410 | 2 | return true; |
1411 | 2 | } |
1412 | | |
1413 | 2 | if (FD->isAnonymousStructOrUnion()) { |
1414 | 2 | S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) |
1415 | 2 | << DecompType << FD->getType()->isUnionType(); |
1416 | 2 | S.Diag(FD->getLocation(), diag::note_declared_at); |
1417 | 2 | return true; |
1418 | 2 | } |
1419 | | |
1420 | | // FIXME: Are there any other ways we could have an anonymous member? |
1421 | 2 | } |
1422 | | |
1423 | | // We have a real field to bind. |
1424 | 431 | if (I >= Bindings.size()) |
1425 | 2 | return DiagnoseBadNumberOfBindings(); |
1426 | 429 | auto *B = Bindings[I++]; |
1427 | 429 | 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 | 429 | S.CheckStructuredBindingMemberAccess( |
1434 | 429 | Loc, const_cast<CXXRecordDecl *>(OrigRD), |
1435 | 429 | DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( |
1436 | 429 | BasePair.getAccess(), FD->getAccess()))); |
1437 | | |
1438 | | // Initialize the binding to Src.FD. |
1439 | 429 | ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); |
1440 | 429 | if (E.isInvalid()) |
1441 | 0 | return true; |
1442 | 429 | E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, |
1443 | 429 | VK_LValue, &BasePath); |
1444 | 429 | if (E.isInvalid()) |
1445 | 0 | return true; |
1446 | 429 | E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, |
1447 | 429 | CXXScopeSpec(), FD, |
1448 | 429 | DeclAccessPair::make(FD, FD->getAccess()), |
1449 | 429 | DeclarationNameInfo(FD->getDeclName(), Loc)); |
1450 | 429 | if (E.isInvalid()) |
1451 | 0 | 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 | 429 | Qualifiers Q = DecompType.getQualifiers(); |
1459 | 429 | if (FD->isMutable()) |
1460 | 11 | Q.removeConst(); |
1461 | 429 | B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); |
1462 | 429 | } |
1463 | | |
1464 | 212 | if (I != Bindings.size()) |
1465 | 6 | return DiagnoseBadNumberOfBindings(); |
1466 | | |
1467 | 206 | return false; |
1468 | 212 | } |
1469 | | |
1470 | 465 | void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { |
1471 | 465 | QualType DecompType = DD->getType(); |
1472 | | |
1473 | | // If the type of the decomposition is dependent, then so is the type of |
1474 | | // each binding. |
1475 | 465 | if (DecompType->isDependentType()) { |
1476 | 26 | for (auto *B : DD->bindings()) |
1477 | 48 | B->setType(Context.DependentTy); |
1478 | 26 | return; |
1479 | 26 | } |
1480 | | |
1481 | 439 | DecompType = DecompType.getNonReferenceType(); |
1482 | 439 | 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 | 439 | if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { |
1489 | 140 | if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) |
1490 | 7 | DD->setInvalidDecl(); |
1491 | 140 | return; |
1492 | 140 | } |
1493 | 299 | if (auto *VT = DecompType->getAs<VectorType>()) { |
1494 | 2 | if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) |
1495 | 0 | DD->setInvalidDecl(); |
1496 | 2 | return; |
1497 | 2 | } |
1498 | 297 | if (auto *CT = DecompType->getAs<ComplexType>()) { |
1499 | 3 | if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) |
1500 | 0 | DD->setInvalidDecl(); |
1501 | 3 | return; |
1502 | 3 | } |
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 | 294 | llvm::APSInt TupleSize(32); |
1508 | 294 | switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { |
1509 | 1 | case IsTupleLike::Error: |
1510 | 1 | DD->setInvalidDecl(); |
1511 | 1 | return; |
1512 | | |
1513 | 63 | case IsTupleLike::TupleLike: |
1514 | 63 | if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) |
1515 | 12 | DD->setInvalidDecl(); |
1516 | 63 | return; |
1517 | | |
1518 | 230 | case IsTupleLike::NotTupleLike: |
1519 | 230 | break; |
1520 | 294 | } |
1521 | | |
1522 | | // C++1z [dcl.dcl]/8: |
1523 | | // [E shall be of array or non-union class type] |
1524 | 230 | CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); |
1525 | 230 | if (!RD || RD->isUnion()223 ) { |
1526 | 7 | Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) |
1527 | 7 | << DD << !RD << DecompType; |
1528 | 7 | DD->setInvalidDecl(); |
1529 | 7 | return; |
1530 | 7 | } |
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 | 223 | if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) |
1536 | 17 | DD->setInvalidDecl(); |
1537 | 223 | } |
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 | 64.7k | void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { |
1545 | | // Shortcut if exceptions are disabled. |
1546 | 64.7k | if (!getLangOpts().CXXExceptions) |
1547 | 5.27k | return; |
1548 | | |
1549 | 59.5k | assert(Context.hasSameType(New->getType(), Old->getType()) && |
1550 | 59.5k | "Should only be called if types are otherwise the same."); |
1551 | | |
1552 | 0 | QualType NewType = New->getType(); |
1553 | 59.5k | 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 | 59.5k | if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { |
1558 | 16 | NewType = R->getPointeeType(); |
1559 | 16 | OldType = OldType->castAs<ReferenceType>()->getPointeeType(); |
1560 | 59.4k | } else if (const PointerType *P = NewType->getAs<PointerType>()) { |
1561 | 238 | NewType = P->getPointeeType(); |
1562 | 238 | OldType = OldType->castAs<PointerType>()->getPointeeType(); |
1563 | 59.2k | } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { |
1564 | 0 | NewType = M->getPointeeType(); |
1565 | 0 | OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); |
1566 | 0 | } |
1567 | | |
1568 | 59.5k | if (!NewType->isFunctionProtoType()) |
1569 | 59.4k | 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 | 24 | if (CheckEquivalentExceptionSpec( |
1575 | 24 | OldType->getAs<FunctionProtoType>(), Old->getLocation(), |
1576 | 24 | NewType->getAs<FunctionProtoType>(), New->getLocation())) { |
1577 | 7 | New->setInvalidDecl(); |
1578 | 7 | } |
1579 | 24 | } |
1580 | | |
1581 | | /// CheckCXXDefaultArguments - Verify that the default arguments for a |
1582 | | /// function declaration are well-formed according to C++ |
1583 | | /// [dcl.fct.default]. |
1584 | 10.1M | void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { |
1585 | 10.1M | unsigned NumParams = FD->getNumParams(); |
1586 | 10.1M | 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 | 10.1M | if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) |
1592 | 4.88k | return; |
1593 | 10.1M | if (auto *FTD = FD->getDescribedFunctionTemplate()) |
1594 | 522k | if (FTD->isMemberSpecialization()) |
1595 | 61 | return; |
1596 | | |
1597 | | // Find first parameter with a default argument |
1598 | 36.2M | for (; 10.1M ParamIdx < NumParams; ++ParamIdx26.0M ) { |
1599 | 26.1M | ParmVarDecl *Param = FD->getParamDecl(ParamIdx); |
1600 | 26.1M | if (Param->hasDefaultArg()) |
1601 | 116k | break; |
1602 | 26.1M | } |
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 | 10.2M | for (; ParamIdx < NumParams; ++ParamIdx133k ) { |
1610 | 133k | ParmVarDecl *Param = FD->getParamDecl(ParamIdx); |
1611 | 133k | if (!Param->hasDefaultArg() && !Param->isParameterPack()125 && |
1612 | 133k | !(75 CurrentInstantiationScope75 && |
1613 | 75 | CurrentInstantiationScope->isLocalPackExpansion(Param)55 )) { |
1614 | 20 | if (Param->isInvalidDecl()) |
1615 | 0 | /* We already complained about this parameter. */; |
1616 | 20 | else if (Param->getIdentifier()) |
1617 | 12 | Diag(Param->getLocation(), |
1618 | 12 | diag::err_param_default_argument_missing_name) |
1619 | 12 | << Param->getIdentifier(); |
1620 | 8 | else |
1621 | 8 | Diag(Param->getLocation(), |
1622 | 8 | diag::err_param_default_argument_missing); |
1623 | 20 | } |
1624 | 133k | } |
1625 | 10.1M | } |
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 | 337k | Ts &&...DiagArgs) { |
1634 | 337k | if (T->isDependentType()) |
1635 | 196k | return false; |
1636 | | |
1637 | 141k | switch (Kind) { |
1638 | 139k | case Sema::CheckConstexprKind::Diagnose: |
1639 | 139k | return SemaRef.RequireLiteralType(Loc, T, DiagID, |
1640 | 139k | std::forward<Ts>(DiagArgs)...); |
1641 | | |
1642 | 2.21k | case Sema::CheckConstexprKind::CheckValid: |
1643 | 2.21k | return !T->isLiteralType(SemaRef.Context); |
1644 | 141k | } |
1645 | | |
1646 | 0 | llvm_unreachable("unknown CheckConstexprKind"); |
1647 | 0 | } SemaDeclCXX.cpp:bool CheckLiteralType<bool>(clang::Sema&, clang::Sema::CheckConstexprKind, clang::SourceLocation, clang::QualType, unsigned int, bool&&) Line | Count | Source | 1633 | 169k | Ts &&...DiagArgs) { | 1634 | 169k | if (T->isDependentType()) | 1635 | 82.0k | return false; | 1636 | | | 1637 | 87.2k | switch (Kind) { | 1638 | 85.4k | case Sema::CheckConstexprKind::Diagnose: | 1639 | 85.4k | return SemaRef.RequireLiteralType(Loc, T, DiagID, | 1640 | 85.4k | std::forward<Ts>(DiagArgs)...); | 1641 | | | 1642 | 1.84k | case Sema::CheckConstexprKind::CheckValid: | 1643 | 1.84k | return !T->isLiteralType(SemaRef.Context); | 1644 | 87.2k | } | 1645 | | | 1646 | 0 | llvm_unreachable("unknown CheckConstexprKind"); | 1647 | 0 | } |
SemaDeclCXX.cpp:bool CheckLiteralType<unsigned int, clang::SourceRange, bool, bool>(clang::Sema&, clang::Sema::CheckConstexprKind, clang::SourceLocation, clang::QualType, unsigned int, unsigned int&&, clang::SourceRange&&, bool&&, bool&&) Line | Count | Source | 1633 | 168k | Ts &&...DiagArgs) { | 1634 | 168k | if (T->isDependentType()) | 1635 | 114k | return false; | 1636 | | | 1637 | 53.9k | switch (Kind) { | 1638 | 53.5k | case Sema::CheckConstexprKind::Diagnose: | 1639 | 53.5k | return SemaRef.RequireLiteralType(Loc, T, DiagID, | 1640 | 53.5k | std::forward<Ts>(DiagArgs)...); | 1641 | | | 1642 | 356 | case Sema::CheckConstexprKind::CheckValid: | 1643 | 356 | return !T->isLiteralType(SemaRef.Context); | 1644 | 53.9k | } | 1645 | | | 1646 | 0 | llvm_unreachable("unknown CheckConstexprKind"); | 1647 | 0 | } |
SemaDeclCXX.cpp:bool CheckLiteralType<bool, int>(clang::Sema&, clang::Sema::CheckConstexprKind, clang::SourceLocation, clang::QualType, unsigned int, bool&&, int&&) Line | Count | Source | 1633 | 153 | Ts &&...DiagArgs) { | 1634 | 153 | if (T->isDependentType()) | 1635 | 10 | return false; | 1636 | | | 1637 | 143 | switch (Kind) { | 1638 | 129 | case Sema::CheckConstexprKind::Diagnose: | 1639 | 129 | return SemaRef.RequireLiteralType(Loc, T, DiagID, | 1640 | 129 | std::forward<Ts>(DiagArgs)...); | 1641 | | | 1642 | 14 | case Sema::CheckConstexprKind::CheckValid: | 1643 | 14 | return !T->isLiteralType(SemaRef.Context); | 1644 | 143 | } | 1645 | | | 1646 | 0 | llvm_unreachable("unknown CheckConstexprKind"); | 1647 | 0 | } |
|
1648 | | |
1649 | | /// Determine whether a destructor cannot be constexpr due to |
1650 | | static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, |
1651 | | const CXXDestructorDecl *DD, |
1652 | 4 | Sema::CheckConstexprKind Kind) { |
1653 | 4 | auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { |
1654 | 4 | const CXXRecordDecl *RD = |
1655 | 4 | T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); |
1656 | 4 | if (!RD || RD->hasConstexprDestructor()) |
1657 | 0 | return true; |
1658 | | |
1659 | 4 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
1660 | 4 | SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) |
1661 | 4 | << static_cast<int>(DD->getConstexprKind()) << !FD |
1662 | 4 | << (FD ? FD->getDeclName()2 : DeclarationName()2 ) << T; |
1663 | 4 | SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) |
1664 | 4 | << !FD << (FD ? FD->getDeclName()2 : DeclarationName()2 ) << T; |
1665 | 4 | } |
1666 | 4 | return false; |
1667 | 4 | }; |
1668 | | |
1669 | 4 | const CXXRecordDecl *RD = DD->getParent(); |
1670 | 4 | for (const CXXBaseSpecifier &B : RD->bases()) |
1671 | 2 | if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) |
1672 | 2 | return false; |
1673 | 2 | for (const FieldDecl *FD : RD->fields()) |
1674 | 2 | if (!Check(FD->getLocation(), FD->getType(), FD)) |
1675 | 2 | return false; |
1676 | 0 | return true; |
1677 | 2 | } |
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 | 190k | Sema::CheckConstexprKind Kind) { |
1684 | 190k | unsigned ArgIndex = 0; |
1685 | 190k | const auto *FT = FD->getType()->castAs<FunctionProtoType>(); |
1686 | 190k | for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), |
1687 | 190k | e = FT->param_type_end(); |
1688 | 359k | i != e; ++i, ++ArgIndex168k ) { |
1689 | 168k | const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); |
1690 | 168k | SourceLocation ParamLoc = PD->getLocation(); |
1691 | 168k | if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, |
1692 | 168k | diag::err_constexpr_non_literal_param, ArgIndex + 1, |
1693 | 168k | PD->getSourceRange(), isa<CXXConstructorDecl>(FD), |
1694 | 168k | FD->isConsteval())) |
1695 | 59 | return false; |
1696 | 168k | } |
1697 | 190k | return true; |
1698 | 190k | } |
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 | 162k | Sema::CheckConstexprKind Kind) { |
1704 | 162k | if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), |
1705 | 162k | diag::err_constexpr_non_literal_return, |
1706 | 162k | FD->isConsteval())) |
1707 | 24 | return false; |
1708 | 162k | return true; |
1709 | 162k | } |
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 | 26 | static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { |
1717 | 26 | switch (Tag) { |
1718 | 21 | case TTK_Struct: return 0; |
1719 | 1 | case TTK_Interface: return 1; |
1720 | 4 | case TTK_Class: return 2; |
1721 | 0 | default: llvm_unreachable("Invalid tag kind for record diagnostic!"); |
1722 | 26 | } |
1723 | 26 | } |
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 | 190k | CheckConstexprKind Kind) { |
1737 | 190k | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); |
1738 | 190k | if (MD && MD->isInstance()134k ) { |
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 | 57.7k | const CXXRecordDecl *RD = MD->getParent(); |
1747 | 57.7k | if (RD->getNumVBases()) { |
1748 | 15 | if (Kind == CheckConstexprKind::CheckValid) |
1749 | 0 | return false; |
1750 | | |
1751 | 15 | Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) |
1752 | 15 | << isa<CXXConstructorDecl>(NewFD) |
1753 | 15 | << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); |
1754 | 15 | for (const auto &I : RD->vbases()) |
1755 | 15 | Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) |
1756 | 15 | << I.getSourceRange(); |
1757 | 15 | return false; |
1758 | 15 | } |
1759 | 57.7k | } |
1760 | | |
1761 | 190k | 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 | 162k | const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); |
1767 | 162k | if (Method && Method->isVirtual()106k ) { |
1768 | 44 | if (getLangOpts().CPlusPlus20) { |
1769 | 31 | if (Kind == CheckConstexprKind::Diagnose) |
1770 | 31 | Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); |
1771 | 31 | } else { |
1772 | 13 | if (Kind == CheckConstexprKind::CheckValid) |
1773 | 0 | return false; |
1774 | | |
1775 | 13 | Method = Method->getCanonicalDecl(); |
1776 | 13 | 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 | 13 | const CXXMethodDecl *WrittenVirtual = Method; |
1781 | 20 | while (!WrittenVirtual->isVirtualAsWritten()) |
1782 | 7 | WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); |
1783 | 13 | if (WrittenVirtual != Method) |
1784 | 5 | Diag(WrittenVirtual->getLocation(), |
1785 | 5 | diag::note_overridden_virtual_function); |
1786 | 13 | return false; |
1787 | 13 | } |
1788 | 44 | } |
1789 | | |
1790 | | // - its return type shall be a literal type; |
1791 | 162k | if (!CheckConstexprReturnType(*this, NewFD, Kind)) |
1792 | 24 | return false; |
1793 | 162k | } |
1794 | | |
1795 | 190k | 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 | 87 | if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { |
1800 | 4 | if (Kind == CheckConstexprKind::CheckValid) |
1801 | 0 | return false; |
1802 | 4 | if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) |
1803 | 4 | return false; |
1804 | 4 | } |
1805 | 87 | } |
1806 | | |
1807 | | // - each of its parameter types shall be a literal type; |
1808 | 190k | if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) |
1809 | 59 | return false; |
1810 | | |
1811 | 190k | Stmt *Body = NewFD->getBody(); |
1812 | 190k | assert(Body && |
1813 | 190k | "CheckConstexprFunctionDefinition called on function with no body"); |
1814 | 0 | return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); |
1815 | 190k | } |
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 | 22.5k | 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 | 22.5k | for (const auto *DclIt : DS->decls()) { |
1829 | 22.5k | switch (DclIt->getKind()) { |
1830 | 5.43k | case Decl::StaticAssert: |
1831 | 5.64k | case Decl::Using: |
1832 | 5.64k | case Decl::UsingShadow: |
1833 | 5.65k | case Decl::UsingDirective: |
1834 | 5.65k | case Decl::UnresolvedUsingTypename: |
1835 | 5.65k | case Decl::UnresolvedUsingValue: |
1836 | 5.65k | case Decl::UsingEnum: |
1837 | | // - static_assert-declarations |
1838 | | // - using-declarations, |
1839 | | // - using-directives, |
1840 | | // - using-enum-declaration |
1841 | 5.65k | continue; |
1842 | | |
1843 | 9.10k | case Decl::Typedef: |
1844 | 9.61k | case Decl::TypeAlias: { |
1845 | | // - typedef declarations and alias-declarations that do not define |
1846 | | // classes or enumerations, |
1847 | 9.61k | const auto *TN = cast<TypedefNameDecl>(DclIt); |
1848 | 9.61k | if (TN->getUnderlyingType()->isVariablyModifiedType()) { |
1849 | | // Don't allow variably-modified types in constexpr functions. |
1850 | 0 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
1851 | 0 | TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); |
1852 | 0 | SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) |
1853 | 0 | << TL.getSourceRange() << TL.getType() |
1854 | 0 | << isa<CXXConstructorDecl>(Dcl); |
1855 | 0 | } |
1856 | 0 | return false; |
1857 | 0 | } |
1858 | 9.61k | continue; |
1859 | 9.61k | } |
1860 | | |
1861 | 9.61k | case Decl::Enum: |
1862 | 120 | case Decl::CXXRecord: |
1863 | | // C++1y allows types to be defined, not just declared. |
1864 | 120 | if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { |
1865 | 105 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
1866 | 72 | SemaRef.Diag(DS->getBeginLoc(), |
1867 | 72 | SemaRef.getLangOpts().CPlusPlus14 |
1868 | 72 | ? diag::warn_cxx11_compat_constexpr_type_definition66 |
1869 | 72 | : diag::ext_constexpr_type_definition6 ) |
1870 | 72 | << isa<CXXConstructorDecl>(Dcl); |
1871 | 72 | } else if (33 !SemaRef.getLangOpts().CPlusPlus1433 ) { |
1872 | 0 | return false; |
1873 | 0 | } |
1874 | 105 | } |
1875 | 120 | continue; |
1876 | | |
1877 | 120 | case Decl::EnumConstant: |
1878 | 0 | case Decl::IndirectField: |
1879 | 0 | 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 | 0 | continue; |
1883 | | |
1884 | 7.16k | case Decl::Var: |
1885 | 7.18k | 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 | 7.18k | const auto *VD = cast<VarDecl>(DclIt); |
1891 | 7.18k | if (VD->isThisDeclarationADefinition()) { |
1892 | 7.13k | if (VD->isStaticLocal()) { |
1893 | 51 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
1894 | 42 | SemaRef.Diag(VD->getLocation(), |
1895 | 42 | SemaRef.getLangOpts().CPlusPlus2b |
1896 | 42 | ? diag::warn_cxx20_compat_constexpr_var25 |
1897 | 42 | : diag::ext_constexpr_static_var17 ) |
1898 | 42 | << isa<CXXConstructorDecl>(Dcl) |
1899 | 42 | << (VD->getTLSKind() == VarDecl::TLS_Dynamic); |
1900 | 42 | } else if (9 !SemaRef.getLangOpts().CPlusPlus2b9 ) { |
1901 | 8 | return false; |
1902 | 8 | } |
1903 | 51 | } |
1904 | 7.13k | if (SemaRef.LangOpts.CPlusPlus2b) { |
1905 | 153 | CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), |
1906 | 153 | diag::warn_cxx20_compat_constexpr_var, |
1907 | 153 | isa<CXXConstructorDecl>(Dcl), |
1908 | 153 | /*variable of non-literal type*/ 2); |
1909 | 6.97k | } else if (CheckLiteralType( |
1910 | 6.97k | SemaRef, Kind, VD->getLocation(), VD->getType(), |
1911 | 6.97k | diag::err_constexpr_local_var_non_literal_type, |
1912 | 6.97k | isa<CXXConstructorDecl>(Dcl))) { |
1913 | 22 | return false; |
1914 | 22 | } |
1915 | 7.10k | if (!VD->getType()->isDependentType() && |
1916 | 7.10k | !VD->hasInit()2.31k && !VD->isCXXForRangeDecl()98 ) { |
1917 | 96 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
1918 | 58 | SemaRef.Diag( |
1919 | 58 | VD->getLocation(), |
1920 | 58 | SemaRef.getLangOpts().CPlusPlus20 |
1921 | 58 | ? diag::warn_cxx17_compat_constexpr_local_var_no_init52 |
1922 | 58 | : diag::ext_constexpr_local_var_no_init6 ) |
1923 | 58 | << isa<CXXConstructorDecl>(Dcl); |
1924 | 58 | } else if (38 !SemaRef.getLangOpts().CPlusPlus2038 ) { |
1925 | 10 | return false; |
1926 | 10 | } |
1927 | 86 | continue; |
1928 | 96 | } |
1929 | 7.10k | } |
1930 | 7.05k | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
1931 | 6.70k | SemaRef.Diag(VD->getLocation(), |
1932 | 6.70k | SemaRef.getLangOpts().CPlusPlus14 |
1933 | 6.70k | ? diag::warn_cxx11_compat_constexpr_local_var6.69k |
1934 | 6.70k | : diag::ext_constexpr_local_var9 ) |
1935 | 6.70k | << isa<CXXConstructorDecl>(Dcl); |
1936 | 6.70k | } else if (352 !SemaRef.getLangOpts().CPlusPlus14352 ) { |
1937 | 0 | return false; |
1938 | 0 | } |
1939 | 7.05k | continue; |
1940 | 7.05k | } |
1941 | | |
1942 | 7.05k | case Decl::NamespaceAlias: |
1943 | 25 | case Decl::Function: |
1944 | | // These are disallowed in C++11 and permitted in C++1y. Allow them |
1945 | | // everywhere as an extension. |
1946 | 25 | if (!Cxx1yLoc.isValid()) |
1947 | 25 | Cxx1yLoc = DS->getBeginLoc(); |
1948 | 25 | continue; |
1949 | | |
1950 | 0 | default: |
1951 | 0 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
1952 | 0 | SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) |
1953 | 0 | << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); |
1954 | 0 | } |
1955 | 0 | return false; |
1956 | 22.5k | } |
1957 | 22.5k | } |
1958 | | |
1959 | 22.4k | return true; |
1960 | 22.5k | } |
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 | 435 | Sema::CheckConstexprKind Kind) { |
1981 | | // In C++20 onwards, there's nothing to check for validity. |
1982 | 435 | if (Kind == Sema::CheckConstexprKind::CheckValid && |
1983 | 435 | SemaRef.getLangOpts().CPlusPlus200 ) |
1984 | 0 | return true; |
1985 | | |
1986 | 435 | if (Field->isInvalidDecl()) |
1987 | 2 | return true; |
1988 | | |
1989 | 433 | if (Field->isUnnamedBitfield()) |
1990 | 8 | 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 | 425 | if (Field->isAnonymousStructOrUnion() && |
1996 | 425 | (196 Field->getType()->isUnionType()196 |
1997 | 196 | ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()139 |
1998 | 196 | : Field->getType()->getAsCXXRecordDecl()->isEmpty()57 )) |
1999 | 6 | return true; |
2000 | | |
2001 | 419 | if (!Inits.count(Field)) { |
2002 | 41 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
2003 | 41 | if (!Diagnosed) { |
2004 | 26 | SemaRef.Diag(Dcl->getLocation(), |
2005 | 26 | SemaRef.getLangOpts().CPlusPlus20 |
2006 | 26 | ? diag::warn_cxx17_compat_constexpr_ctor_missing_init10 |
2007 | 26 | : diag::ext_constexpr_ctor_missing_init16 ); |
2008 | 26 | Diagnosed = true; |
2009 | 26 | } |
2010 | 41 | SemaRef.Diag(Field->getLocation(), |
2011 | 41 | diag::note_constexpr_ctor_missing_init); |
2012 | 41 | } else if (0 !SemaRef.getLangOpts().CPlusPlus200 ) { |
2013 | 0 | return false; |
2014 | 0 | } |
2015 | 378 | } else if (Field->isAnonymousStructOrUnion()) { |
2016 | 167 | const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); |
2017 | 167 | 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 | 365 | if (!RD->isUnion() || Inits.count(I)251 ) |
2021 | 230 | if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, |
2022 | 230 | Kind)) |
2023 | 0 | return false; |
2024 | 167 | } |
2025 | 419 | return true; |
2026 | 419 | } |
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 | 219k | Sema::CheckConstexprKind Kind) { |
2036 | | // - its function-body shall be [...] a compound-statement that contains only |
2037 | 219k | switch (S->getStmtClass()) { |
2038 | 111 | case Stmt::NullStmtClass: |
2039 | | // - null statements, |
2040 | 111 | return true; |
2041 | | |
2042 | 22.5k | 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 | 22.5k | if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) |
2049 | 40 | return false; |
2050 | 22.4k | return true; |
2051 | | |
2052 | 162k | case Stmt::ReturnStmtClass: |
2053 | | // - and exactly one return statement; |
2054 | 162k | if (isa<CXXConstructorDecl>(Dcl)) { |
2055 | | // C++1y allows return statements in constexpr constructors. |
2056 | 3 | if (!Cxx1yLoc.isValid()) |
2057 | 3 | Cxx1yLoc = S->getBeginLoc(); |
2058 | 3 | return true; |
2059 | 3 | } |
2060 | | |
2061 | 162k | ReturnStmts.push_back(S->getBeginLoc()); |
2062 | 162k | return true; |
2063 | | |
2064 | 10 | 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 | 10 | return CheckConstexprFunctionStmt( |
2068 | 10 | SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts, |
2069 | 10 | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind); |
2070 | | |
2071 | 4.89k | case Stmt::CompoundStmtClass: { |
2072 | | // C++1y allows compound-statements. |
2073 | 4.89k | if (!Cxx1yLoc.isValid()) |
2074 | 32 | Cxx1yLoc = S->getBeginLoc(); |
2075 | | |
2076 | 4.89k | CompoundStmt *CompStmt = cast<CompoundStmt>(S); |
2077 | 12.0k | for (auto *BodyIt : CompStmt->body()) { |
2078 | 12.0k | if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, |
2079 | 12.0k | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2080 | 0 | return false; |
2081 | 12.0k | } |
2082 | 4.89k | return true; |
2083 | 4.89k | } |
2084 | | |
2085 | 7.24k | case Stmt::IfStmtClass: { |
2086 | | // C++1y allows if-statements. |
2087 | 7.24k | if (!Cxx1yLoc.isValid()) |
2088 | 2.28k | Cxx1yLoc = S->getBeginLoc(); |
2089 | | |
2090 | 7.24k | IfStmt *If = cast<IfStmt>(S); |
2091 | 7.24k | if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, |
2092 | 7.24k | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2093 | 3 | return false; |
2094 | 7.24k | if (If->getElse() && |
2095 | 7.24k | !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, |
2096 | 1.26k | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2097 | 0 | return false; |
2098 | 7.24k | return true; |
2099 | 7.24k | } |
2100 | | |
2101 | 1.16k | case Stmt::WhileStmtClass: |
2102 | 1.27k | case Stmt::DoStmtClass: |
2103 | 2.27k | case Stmt::ForStmtClass: |
2104 | 2.30k | case Stmt::CXXForRangeStmtClass: |
2105 | 2.33k | 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 | 2.33k | if (!SemaRef.getLangOpts().CPlusPlus14) |
2109 | 3 | break; |
2110 | 2.33k | if (!Cxx1yLoc.isValid()) |
2111 | 882 | Cxx1yLoc = S->getBeginLoc(); |
2112 | 7.78k | for (Stmt *SubStmt : S->children()) { |
2113 | 7.78k | if (SubStmt && |
2114 | 7.78k | !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, |
2115 | 5.98k | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2116 | 0 | return false; |
2117 | 7.78k | } |
2118 | 2.33k | return true; |
2119 | | |
2120 | 88 | case Stmt::SwitchStmtClass: |
2121 | 448 | case Stmt::CaseStmtClass: |
2122 | 470 | case Stmt::DefaultStmtClass: |
2123 | 1.15k | 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 | 1.15k | if (!Cxx1yLoc.isValid()) |
2127 | 53 | Cxx1yLoc = S->getBeginLoc(); |
2128 | 1.15k | for (Stmt *SubStmt : S->children()) { |
2129 | 926 | if (SubStmt && |
2130 | 926 | !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, |
2131 | 926 | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2132 | 0 | return false; |
2133 | 926 | } |
2134 | 1.15k | return true; |
2135 | | |
2136 | 20 | case Stmt::LabelStmtClass: |
2137 | 32 | case Stmt::GotoStmtClass: |
2138 | 32 | if (Cxx2bLoc.isInvalid()) |
2139 | 20 | Cxx2bLoc = S->getBeginLoc(); |
2140 | 32 | for (Stmt *SubStmt : S->children()) { |
2141 | 20 | if (SubStmt && |
2142 | 20 | !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, |
2143 | 20 | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2144 | 0 | return false; |
2145 | 20 | } |
2146 | 32 | return true; |
2147 | | |
2148 | 13 | case Stmt::GCCAsmStmtClass: |
2149 | 13 | case Stmt::MSAsmStmtClass: |
2150 | | // C++2a allows inline assembly statements. |
2151 | 35 | case Stmt::CXXTryStmtClass: |
2152 | 35 | if (Cxx2aLoc.isInvalid()) |
2153 | 35 | Cxx2aLoc = S->getBeginLoc(); |
2154 | 44 | for (Stmt *SubStmt : S->children()) { |
2155 | 44 | if (SubStmt && |
2156 | 44 | !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, |
2157 | 44 | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2158 | 0 | return false; |
2159 | 44 | } |
2160 | 35 | return true; |
2161 | | |
2162 | 29 | case Stmt::CXXCatchStmtClass: |
2163 | | // Do not bother checking the language mode (already covered by the |
2164 | | // try block check). |
2165 | 29 | if (!CheckConstexprFunctionStmt( |
2166 | 29 | SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts, |
2167 | 29 | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2168 | 0 | return false; |
2169 | 29 | return true; |
2170 | | |
2171 | 18.1k | default: |
2172 | 18.1k | if (!isa<Expr>(S)) |
2173 | 0 | break; |
2174 | | |
2175 | | // C++1y allows expression-statements. |
2176 | 18.1k | if (!Cxx1yLoc.isValid()) |
2177 | 5.58k | Cxx1yLoc = S->getBeginLoc(); |
2178 | 18.1k | return true; |
2179 | 219k | } |
2180 | | |
2181 | 3 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
2182 | 3 | SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) |
2183 | 3 | << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); |
2184 | 3 | } |
2185 | 3 | return false; |
2186 | 219k | } |
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 | 190k | Sema::CheckConstexprKind Kind) { |
2196 | 190k | SmallVector<SourceLocation, 4> ReturnStmts; |
2197 | | |
2198 | 190k | 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 | 7 | switch (Kind) { |
2212 | 0 | case Sema::CheckConstexprKind::CheckValid: |
2213 | 0 | if (!SemaRef.getLangOpts().CPlusPlus20) |
2214 | 0 | return false; |
2215 | 0 | break; |
2216 | | |
2217 | 7 | case Sema::CheckConstexprKind::Diagnose: |
2218 | 7 | SemaRef.Diag(Body->getBeginLoc(), |
2219 | 7 | !SemaRef.getLangOpts().CPlusPlus20 |
2220 | 7 | ? diag::ext_constexpr_function_try_block_cxx205 |
2221 | 7 | : diag::warn_cxx17_compat_constexpr_function_try_block2 ) |
2222 | 7 | << isa<CXXConstructorDecl>(Dcl); |
2223 | 7 | break; |
2224 | 7 | } |
2225 | 7 | } |
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 | 190k | SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc; |
2233 | 191k | for (Stmt *SubStmt : Body->children()) { |
2234 | 191k | if (SubStmt && |
2235 | 191k | !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, |
2236 | 191k | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2237 | 43 | return false; |
2238 | 191k | } |
2239 | | |
2240 | 190k | 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 | 2.12k | if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2b2 ) || |
2244 | 2.12k | (2.12k Cxx2aLoc.isValid()2.12k && !SemaRef.getLangOpts().CPlusPlus209 ) || |
2245 | 2.12k | (2.11k Cxx1yLoc.isValid()2.11k && !SemaRef.getLangOpts().CPlusPlus17555 )) |
2246 | 7 | return false; |
2247 | 188k | } else if (Cxx2bLoc.isValid()) { |
2248 | 18 | SemaRef.Diag(Cxx2bLoc, |
2249 | 18 | SemaRef.getLangOpts().CPlusPlus2b |
2250 | 18 | ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt9 |
2251 | 18 | : diag::ext_constexpr_body_invalid_stmt_cxx2b9 ) |
2252 | 18 | << isa<CXXConstructorDecl>(Dcl); |
2253 | 188k | } else if (Cxx2aLoc.isValid()) { |
2254 | 26 | SemaRef.Diag(Cxx2aLoc, |
2255 | 26 | SemaRef.getLangOpts().CPlusPlus20 |
2256 | 26 | ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt20 |
2257 | 26 | : diag::ext_constexpr_body_invalid_stmt_cxx206 ) |
2258 | 26 | << isa<CXXConstructorDecl>(Dcl); |
2259 | 188k | } else if (Cxx1yLoc.isValid()) { |
2260 | 8.27k | SemaRef.Diag(Cxx1yLoc, |
2261 | 8.27k | SemaRef.getLangOpts().CPlusPlus14 |
2262 | 8.27k | ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt8.26k |
2263 | 8.27k | : diag::ext_constexpr_body_invalid_stmt7 ) |
2264 | 8.27k | << isa<CXXConstructorDecl>(Dcl); |
2265 | 8.27k | } |
2266 | | |
2267 | 190k | if (const CXXConstructorDecl *Constructor |
2268 | 190k | = dyn_cast<CXXConstructorDecl>(Dcl)) { |
2269 | 28.6k | 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 | 28.6k | if (RD->isUnion()) { |
2277 | 181 | if (Constructor->getNumCtorInitializers() == 0 && |
2278 | 181 | RD->hasVariantMembers()9 ) { |
2279 | 2 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
2280 | 2 | SemaRef.Diag( |
2281 | 2 | Dcl->getLocation(), |
2282 | 2 | SemaRef.getLangOpts().CPlusPlus20 |
2283 | 2 | ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init |
2284 | 2 | : diag::ext_constexpr_union_ctor_no_init0 ); |
2285 | 2 | } else if (0 !SemaRef.getLangOpts().CPlusPlus200 ) { |
2286 | 0 | return false; |
2287 | 0 | } |
2288 | 2 | } |
2289 | 28.4k | } else if (!Constructor->isDependentContext() && |
2290 | 28.4k | !Constructor->isDelegatingConstructor()3.15k ) { |
2291 | 3.12k | assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); |
2292 | | |
2293 | | // Skip detailed checking if we have enough initializers, and we would |
2294 | | // allow at most one initializer per member. |
2295 | 0 | bool AnyAnonStructUnionMembers = false; |
2296 | 3.12k | unsigned Fields = 0; |
2297 | 3.12k | for (CXXRecordDecl::field_iterator I = RD->field_begin(), |
2298 | 5.99k | E = RD->field_end(); I != E; ++I, ++Fields2.87k ) { |
2299 | 2.94k | if (I->isAnonymousStructOrUnion()) { |
2300 | 79 | AnyAnonStructUnionMembers = true; |
2301 | 79 | break; |
2302 | 79 | } |
2303 | 2.94k | } |
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 | 3.12k | if (AnyAnonStructUnionMembers || |
2309 | 3.12k | Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields3.04k ) { |
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 | 95 | llvm::SmallSet<Decl*, 16> Inits; |
2314 | 212 | for (const auto *I: Constructor->inits()) { |
2315 | 212 | if (FieldDecl *FD = I->getMember()) |
2316 | 44 | Inits.insert(FD); |
2317 | 168 | else if (IndirectFieldDecl *ID = I->getIndirectMember()) |
2318 | 167 | Inits.insert(ID->chain_begin(), ID->chain_end()); |
2319 | 212 | } |
2320 | | |
2321 | 95 | bool Diagnosed = false; |
2322 | 95 | for (auto *I : RD->fields()) |
2323 | 205 | if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, |
2324 | 205 | Kind)) |
2325 | 0 | return false; |
2326 | 95 | } |
2327 | 3.12k | } |
2328 | 162k | } else { |
2329 | 162k | 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 | 3.25k | bool OK = SemaRef.getLangOpts().CPlusPlus14 && |
2335 | 3.25k | (3.25k Dcl->getReturnType()->isVoidType()3.25k || |
2336 | 3.25k | Dcl->getReturnType()->isDependentType()564 ); |
2337 | 3.25k | switch (Kind) { |
2338 | 2.17k | case Sema::CheckConstexprKind::Diagnose: |
2339 | 2.17k | SemaRef.Diag(Dcl->getLocation(), |
2340 | 2.17k | OK ? diag::warn_cxx11_compat_constexpr_body_no_return2.15k |
2341 | 2.17k | : diag::err_constexpr_body_no_return21 ) |
2342 | 2.17k | << Dcl->isConsteval(); |
2343 | 2.17k | if (!OK) |
2344 | 21 | return false; |
2345 | 2.15k | break; |
2346 | | |
2347 | 2.15k | 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 | 1.07k | if (!SemaRef.getLangOpts().CPlusPlus14) |
2352 | 0 | return false; |
2353 | 1.07k | break; |
2354 | 3.25k | } |
2355 | 158k | } else if (ReturnStmts.size() > 1) { |
2356 | 1.91k | switch (Kind) { |
2357 | 1.87k | case Sema::CheckConstexprKind::Diagnose: |
2358 | 1.87k | SemaRef.Diag( |
2359 | 1.87k | ReturnStmts.back(), |
2360 | 1.87k | SemaRef.getLangOpts().CPlusPlus14 |
2361 | 1.87k | ? diag::warn_cxx11_compat_constexpr_body_multiple_return1.87k |
2362 | 1.87k | : diag::ext_constexpr_body_multiple_return2 ); |
2363 | 5.62k | for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I3.74k ) |
2364 | 3.74k | SemaRef.Diag(ReturnStmts[I], |
2365 | 3.74k | diag::note_constexpr_body_previous_return); |
2366 | 1.87k | break; |
2367 | | |
2368 | 39 | case Sema::CheckConstexprKind::CheckValid: |
2369 | 39 | if (!SemaRef.getLangOpts().CPlusPlus14) |
2370 | 0 | return false; |
2371 | 39 | break; |
2372 | 1.91k | } |
2373 | 1.91k | } |
2374 | 162k | } |
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 | 190k | SmallVector<PartialDiagnosticAt, 8> Diags; |
2390 | 190k | if (Kind == Sema::CheckConstexprKind::Diagnose && |
2391 | 190k | !Expr::isPotentialConstantExpr(Dcl, Diags)188k ) { |
2392 | 334 | SemaRef.Diag(Dcl->getLocation(), |
2393 | 334 | diag::ext_constexpr_function_never_constant_expr) |
2394 | 334 | << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); |
2395 | 730 | for (size_t I = 0, N = Diags.size(); I != N; ++I396 ) |
2396 | 396 | SemaRef.Diag(Diags[I].first, Diags[I].second); |
2397 | | // Don't return false here: we allow this for compatibility in |
2398 | | // system headers. |
2399 | 334 | } |
2400 | | |
2401 | 190k | return true; |
2402 | 190k | } |
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 | 3.08M | CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { |
2413 | 3.08M | assert(getLangOpts().CPlusPlus && "No class names in C!"); |
2414 | | |
2415 | 3.08M | if (SS && SS->isInvalid()1.23M ) |
2416 | 40 | return nullptr; |
2417 | | |
2418 | 3.08M | if (SS && SS->isNotEmpty()1.23M ) { |
2419 | 581k | DeclContext *DC = computeDeclContext(*SS, true); |
2420 | 581k | return dyn_cast_or_null<CXXRecordDecl>(DC); |
2421 | 581k | } |
2422 | | |
2423 | 2.50M | return dyn_cast_or_null<CXXRecordDecl>(CurContext); |
2424 | 3.08M | } |
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 | 2.72M | const CXXScopeSpec *SS) { |
2432 | 2.72M | CXXRecordDecl *CurDecl = getCurrentClass(S, SS); |
2433 | 2.72M | return CurDecl && &II == CurDecl->getIdentifier()2.31M ; |
2434 | 2.72M | } |
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 | 45 | bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { |
2440 | 45 | assert(getLangOpts().CPlusPlus && "No class names in C!"); |
2441 | | |
2442 | 45 | if (!getLangOpts().SpellChecking) |
2443 | 0 | return false; |
2444 | | |
2445 | 45 | CXXRecordDecl *CurDecl; |
2446 | 45 | if (SS && SS->isSet()29 && !SS->isInvalid()19 ) { |
2447 | 19 | DeclContext *DC = computeDeclContext(*SS, true); |
2448 | 19 | CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); |
2449 | 19 | } else |
2450 | 26 | CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); |
2451 | | |
2452 | 45 | if (CurDecl && CurDecl->getIdentifier()40 && II != CurDecl->getIdentifier()35 && |
2453 | 45 | 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) |
2454 | 35 | < II->getLength()) { |
2455 | 10 | II = CurDecl->getIdentifier(); |
2456 | 10 | return true; |
2457 | 10 | } |
2458 | | |
2459 | 35 | return false; |
2460 | 45 | } |
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 | 26 | const CXXRecordDecl *Current) { |
2466 | 26 | SmallVector<const CXXRecordDecl*, 8> Queue; |
2467 | | |
2468 | 26 | Class = Class->getCanonicalDecl(); |
2469 | 28 | while (true) { |
2470 | 28 | for (const auto &I : Current->bases()) { |
2471 | 8 | CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); |
2472 | 8 | if (!Base) |
2473 | 5 | continue; |
2474 | | |
2475 | 3 | Base = Base->getDefinition(); |
2476 | 3 | if (!Base) |
2477 | 0 | continue; |
2478 | | |
2479 | 3 | if (Base->getCanonicalDecl() == Class) |
2480 | 1 | return true; |
2481 | | |
2482 | 2 | Queue.push_back(Base); |
2483 | 2 | } |
2484 | | |
2485 | 27 | if (Queue.empty()) |
2486 | 25 | return false; |
2487 | | |
2488 | 2 | Current = Queue.pop_back_val(); |
2489 | 2 | } |
2490 | | |
2491 | 0 | return false; |
2492 | 26 | } |
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 | 547k | SourceLocation EllipsisLoc) { |
2504 | | // In HLSL, unspecified class access is public rather than private. |
2505 | 547k | if (getLangOpts().HLSL && Class->getTagKind() == TTK_Class8 && |
2506 | 547k | Access == AS_none4 ) |
2507 | 1 | Access = AS_public; |
2508 | | |
2509 | 547k | QualType BaseType = TInfo->getType(); |
2510 | 547k | if (BaseType->containsErrors()) { |
2511 | | // Already emitted a diagnostic when parsing the error type. |
2512 | 3 | return nullptr; |
2513 | 3 | } |
2514 | | // C++ [class.union]p1: |
2515 | | // A union shall not have base classes. |
2516 | 547k | if (Class->isUnion()) { |
2517 | 1 | Diag(Class->getLocation(), diag::err_base_clause_on_union) |
2518 | 1 | << SpecifierRange; |
2519 | 1 | return nullptr; |
2520 | 1 | } |
2521 | | |
2522 | 547k | if (EllipsisLoc.isValid() && |
2523 | 547k | !TInfo->getType()->containsUnexpandedParameterPack()527 ) { |
2524 | 2 | Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) |
2525 | 2 | << TInfo->getTypeLoc().getSourceRange(); |
2526 | 2 | EllipsisLoc = SourceLocation(); |
2527 | 2 | } |
2528 | | |
2529 | 547k | SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); |
2530 | | |
2531 | 547k | if (BaseType->isDependentType()) { |
2532 | | // Make sure that we don't have circular inheritance among our dependent |
2533 | | // bases. For non-dependent bases, the check for completeness below handles |
2534 | | // this. |
2535 | 139k | if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { |
2536 | 37 | if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || |
2537 | 37 | (35 (BaseDecl = BaseDecl->getDefinition())35 && |
2538 | 35 | findCircularInheritance(Class, BaseDecl)26 )) { |
2539 | 3 | Diag(BaseLoc, diag::err_circular_inheritance) |
2540 | 3 | << BaseType << Context.getTypeDeclType(Class); |
2541 | | |
2542 | 3 | if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) |
2543 | 1 | Diag(BaseDecl->getLocation(), diag::note_previous_decl) |
2544 | 1 | << BaseType; |
2545 | | |
2546 | 3 | return nullptr; |
2547 | 3 | } |
2548 | 37 | } |
2549 | | |
2550 | | // Make sure that we don't make an ill-formed AST where the type of the |
2551 | | // Class is non-dependent and its attached base class specifier is an |
2552 | | // dependent type, which violates invariants in many clang code paths (e.g. |
2553 | | // constexpr evaluator). If this case happens (in errory-recovery mode), we |
2554 | | // explicitly mark the Class decl invalid. The diagnostic was already |
2555 | | // emitted. |
2556 | 139k | if (!Class->getTypeForDecl()->isDependentType()) |
2557 | 2 | Class->setInvalidDecl(); |
2558 | 139k | return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, |
2559 | 139k | Class->getTagKind() == TTK_Class, |
2560 | 139k | Access, TInfo, EllipsisLoc); |
2561 | 139k | } |
2562 | | |
2563 | | // Base specifiers must be record types. |
2564 | 408k | if (!BaseType->isRecordType()) { |
2565 | 6 | Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; |
2566 | 6 | return nullptr; |
2567 | 6 | } |
2568 | | |
2569 | | // C++ [class.union]p1: |
2570 | | // A union shall not be used as a base class. |
2571 | 408k | if (BaseType->isUnionType()) { |
2572 | 1 | Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; |
2573 | 1 | return nullptr; |
2574 | 1 | } |
2575 | | |
2576 | | // For the MS ABI, propagate DLL attributes to base class templates. |
2577 | 408k | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
2578 | 4.14k | if (Attr *ClassAttr = getDLLAttr(Class)) { |
2579 | 297 | if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( |
2580 | 297 | BaseType->getAsCXXRecordDecl())) { |
2581 | 241 | propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, |
2582 | 241 | BaseLoc); |
2583 | 241 | } |
2584 | 297 | } |
2585 | 4.14k | } |
2586 | | |
2587 | | // C++ [class.derived]p2: |
2588 | | // The class-name in a base-specifier shall not be an incompletely |
2589 | | // defined class. |
2590 | 408k | if (RequireCompleteType(BaseLoc, BaseType, |
2591 | 408k | diag::err_incomplete_base_class, SpecifierRange)) { |
2592 | 1.22k | Class->setInvalidDecl(); |
2593 | 1.22k | return nullptr; |
2594 | 1.22k | } |
2595 | | |
2596 | | // If the base class is polymorphic or isn't empty, the new one is/isn't, too. |
2597 | 406k | RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); |
2598 | 406k | assert(BaseDecl && "Record type has no declaration"); |
2599 | 0 | BaseDecl = BaseDecl->getDefinition(); |
2600 | 406k | assert(BaseDecl && "Base type is not incomplete, but has no definition"); |
2601 | 0 | CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); |
2602 | 406k | assert(CXXBaseDecl && "Base type is not a C++ type"); |
2603 | | |
2604 | | // Microsoft docs say: |
2605 | | // "If a base-class has a code_seg attribute, derived classes must have the |
2606 | | // same attribute." |
2607 | 0 | const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); |
2608 | 406k | const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); |
2609 | 406k | if ((DerivedCSA || BaseCSA406k ) && |
2610 | 406k | (34 !BaseCSA34 || !DerivedCSA30 || BaseCSA->getName() != DerivedCSA->getName()26 )) { |
2611 | 19 | Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); |
2612 | 19 | Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) |
2613 | 19 | << CXXBaseDecl; |
2614 | 19 | return nullptr; |
2615 | 19 | } |
2616 | | |
2617 | | // A class which contains a flexible array member is not suitable for use as a |
2618 | | // base class: |
2619 | | // - If the layout determines that a base comes before another base, |
2620 | | // the flexible array member would index into the subsequent base. |
2621 | | // - If the layout determines that base comes before the derived class, |
2622 | | // the flexible array member would index into the derived class. |
2623 | 406k | if (CXXBaseDecl->hasFlexibleArrayMember()) { |
2624 | 1 | Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) |
2625 | 1 | << CXXBaseDecl->getDeclName(); |
2626 | 1 | return nullptr; |
2627 | 1 | } |
2628 | | |
2629 | | // C++ [class]p3: |
2630 | | // If a class is marked final and it appears as a base-type-specifier in |
2631 | | // base-clause, the program is ill-formed. |
2632 | 406k | if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { |
2633 | 11 | Diag(BaseLoc, diag::err_class_marked_final_used_as_base) |
2634 | 11 | << CXXBaseDecl->getDeclName() |
2635 | 11 | << FA->isSpelledAsSealed(); |
2636 | 11 | Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) |
2637 | 11 | << CXXBaseDecl->getDeclName() << FA->getRange(); |
2638 | 11 | return nullptr; |
2639 | 11 | } |
2640 | | |
2641 | 406k | if (BaseDecl->isInvalidDecl()) |
2642 | 51 | Class->setInvalidDecl(); |
2643 | | |
2644 | | // Create the base specifier. |
2645 | 406k | return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, |
2646 | 406k | Class->getTagKind() == TTK_Class, |
2647 | 406k | Access, TInfo, EllipsisLoc); |
2648 | 406k | } |
2649 | | |
2650 | | /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is |
2651 | | /// one entry in the base class list of a class specifier, for |
2652 | | /// example: |
2653 | | /// class foo : public bar, virtual private baz { |
2654 | | /// 'public bar' and 'virtual private baz' are each base-specifiers. |
2655 | | BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, |
2656 | | const ParsedAttributesView &Attributes, |
2657 | | bool Virtual, AccessSpecifier Access, |
2658 | | ParsedType basetype, SourceLocation BaseLoc, |
2659 | 265k | SourceLocation EllipsisLoc) { |
2660 | 265k | if (!classdecl) |
2661 | 55 | return true; |
2662 | | |
2663 | 265k | AdjustDeclIfTemplate(classdecl); |
2664 | 265k | CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); |
2665 | 265k | if (!Class) |
2666 | 0 | return true; |
2667 | | |
2668 | | // We haven't yet attached the base specifiers. |
2669 | 265k | Class->setIsParsingBaseSpecifiers(); |
2670 | | |
2671 | | // We do not support any C++11 attributes on base-specifiers yet. |
2672 | | // Diagnose any attributes we see. |
2673 | 265k | for (const ParsedAttr &AL : Attributes) { |
2674 | 18 | if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) |
2675 | 0 | continue; |
2676 | 18 | Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute |
2677 | 18 | ? (unsigned)diag::warn_unknown_attribute_ignored17 |
2678 | 18 | : (unsigned)diag::err_base_specifier_attribute1 ) |
2679 | 18 | << AL << AL.getRange(); |
2680 | 18 | } |
2681 | | |
2682 | 265k | TypeSourceInfo *TInfo = nullptr; |
2683 | 265k | GetTypeFromParser(basetype, &TInfo); |
2684 | | |
2685 | 265k | if (EllipsisLoc.isInvalid() && |
2686 | 265k | DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, |
2687 | 265k | UPPC_BaseType)) |
2688 | 1 | return true; |
2689 | | |
2690 | 265k | if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, |
2691 | 265k | Virtual, Access, TInfo, |
2692 | 265k | EllipsisLoc)) |
2693 | 265k | return BaseSpec; |
2694 | 197 | else |
2695 | 197 | Class->setInvalidDecl(); |
2696 | | |
2697 | 197 | return true; |
2698 | 265k | } |
2699 | | |
2700 | | /// Use small set to collect indirect bases. As this is only used |
2701 | | /// locally, there's no need to abstract the small size parameter. |
2702 | | typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; |
2703 | | |
2704 | | /// Recursively add the bases of Type. Don't add Type itself. |
2705 | | static void |
2706 | | NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, |
2707 | | const QualType &Type) |
2708 | 32.8k | { |
2709 | | // Even though the incoming type is a base, it might not be |
2710 | | // a class -- it could be a template parm, for instance. |
2711 | 32.8k | if (auto Rec = Type->getAs<RecordType>()) { |
2712 | 32.8k | auto Decl = Rec->getAsCXXRecordDecl(); |
2713 | | |
2714 | | // Iterate over its bases. |
2715 | 32.8k | for (const auto &BaseSpec : Decl->bases()) { |
2716 | 12.2k | QualType Base = Context.getCanonicalType(BaseSpec.getType()) |
2717 | 12.2k | .getUnqualifiedType(); |
2718 | 12.2k | if (Set.insert(Base).second) |
2719 | | // If we've not already seen it, recurse. |
2720 | 11.4k | NoteIndirectBases(Context, Set, Base); |
2721 | 12.2k | } |
2722 | 32.8k | } |
2723 | 32.8k | } |
2724 | | |
2725 | | /// Performs the actual work of attaching the given base class |
2726 | | /// specifiers to a C++ class. |
2727 | | bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, |
2728 | 1.18M | MutableArrayRef<CXXBaseSpecifier *> Bases) { |
2729 | 1.18M | if (Bases.empty()) |
2730 | 562k | return false; |
2731 | | |
2732 | | // Used to keep track of which base types we have already seen, so |
2733 | | // that we can properly diagnose redundant direct base types. Note |
2734 | | // that the key is always the unqualified canonical type of the base |
2735 | | // class. |
2736 | 624k | std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; |
2737 | | |
2738 | | // Used to track indirect bases so we can see if a direct base is |
2739 | | // ambiguous. |
2740 | 624k | IndirectBaseSet IndirectBaseTypes; |
2741 | | |
2742 | | // Copy non-redundant base specifiers into permanent storage. |
2743 | 624k | unsigned NumGoodBases = 0; |
2744 | 624k | bool Invalid = false; |
2745 | 1.26M | for (unsigned idx = 0; idx < Bases.size(); ++idx639k ) { |
2746 | 639k | QualType NewBaseType |
2747 | 639k | = Context.getCanonicalType(Bases[idx]->getType()); |
2748 | 639k | NewBaseType = NewBaseType.getLocalUnqualifiedType(); |
2749 | | |
2750 | 639k | CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; |
2751 | 639k | if (KnownBase) { |
2752 | | // C++ [class.mi]p3: |
2753 | | // A class shall not be specified as a direct base class of a |
2754 | | // derived class more than once. |
2755 | 2 | Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) |
2756 | 2 | << KnownBase->getType() << Bases[idx]->getSourceRange(); |
2757 | | |
2758 | | // Delete the duplicate base class specifier; we're going to |
2759 | | // overwrite its pointer later. |
2760 | 2 | Context.Deallocate(Bases[idx]); |
2761 | | |
2762 | 2 | Invalid = true; |
2763 | 639k | } else { |
2764 | | // Okay, add this new base class. |
2765 | 639k | KnownBase = Bases[idx]; |
2766 | 639k | Bases[NumGoodBases++] = Bases[idx]; |
2767 | | |
2768 | 639k | if (NewBaseType->isDependentType()) |
2769 | 139k | continue; |
2770 | | // Note this base's direct & indirect bases, if there could be ambiguity. |
2771 | 499k | if (Bases.size() > 1) |
2772 | 21.4k | NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); |
2773 | | |
2774 | 499k | if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { |
2775 | 499k | const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); |
2776 | 499k | if (Class->isInterface() && |
2777 | 499k | (25 !RD->isInterfaceLike()25 || |
2778 | 25 | KnownBase->getAccessSpecifier() != AS_public15 )) { |
2779 | | // The Microsoft extension __interface does not permit bases that |
2780 | | // are not themselves public interfaces. |
2781 | 11 | Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) |
2782 | 11 | << getRecordDiagFromTagKind(RD->getTagKind()) << RD |
2783 | 11 | << RD->getSourceRange(); |
2784 | 11 | Invalid = true; |
2785 | 11 | } |
2786 | 499k | if (RD->hasAttr<WeakAttr>()) |
2787 | 4 | Class->addAttr(WeakAttr::CreateImplicit(Context)); |
2788 | 499k | } |
2789 | 499k | } |
2790 | 639k | } |
2791 | | |
2792 | | // Attach the remaining base class specifiers to the derived class. |
2793 | 624k | Class->setBases(Bases.data(), NumGoodBases); |
2794 | | |
2795 | | // Check that the only base classes that are duplicate are virtual. |
2796 | 1.26M | for (unsigned idx = 0; idx < NumGoodBases; ++idx639k ) { |
2797 | | // Check whether this direct base is inaccessible due to ambiguity. |
2798 | 639k | QualType BaseType = Bases[idx]->getType(); |
2799 | | |
2800 | | // Skip all dependent types in templates being used as base specifiers. |
2801 | | // Checks below assume that the base specifier is a CXXRecord. |
2802 | 639k | if (BaseType->isDependentType()) |
2803 | 139k | continue; |
2804 | | |
2805 | 499k | CanQualType CanonicalBase = Context.getCanonicalType(BaseType) |
2806 | 499k | .getUnqualifiedType(); |
2807 | | |
2808 | 499k | if (IndirectBaseTypes.count(CanonicalBase)) { |
2809 | 366 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, |
2810 | 366 | /*DetectVirtual=*/true); |
2811 | 366 | bool found |
2812 | 366 | = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); |
2813 | 366 | assert(found); |
2814 | 0 | (void)found; |
2815 | | |
2816 | 366 | if (Paths.isAmbiguous(CanonicalBase)) |
2817 | 254 | Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) |
2818 | 254 | << BaseType << getAmbiguousPathsDisplayString(Paths) |
2819 | 254 | << Bases[idx]->getSourceRange(); |
2820 | 112 | else |
2821 | 112 | assert(Bases[idx]->isVirtual()); |
2822 | 366 | } |
2823 | | |
2824 | | // Delete the base class specifier, since its data has been copied |
2825 | | // into the CXXRecordDecl. |
2826 | 0 | Context.Deallocate(Bases[idx]); |
2827 | 499k | } |
2828 | | |
2829 | 624k | return Invalid; |
2830 | 1.18M | } |
2831 | | |
2832 | | /// ActOnBaseSpecifiers - Attach the given base specifiers to the |
2833 | | /// class, after checking whether there are any duplicate base |
2834 | | /// classes. |
2835 | | void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, |
2836 | 258k | MutableArrayRef<CXXBaseSpecifier *> Bases) { |
2837 | 258k | if (!ClassDecl || Bases.empty()258k ) |
2838 | 539 | return; |
2839 | | |
2840 | 257k | AdjustDeclIfTemplate(ClassDecl); |
2841 | 257k | AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); |
2842 | 257k | } |
2843 | | |
2844 | | /// Determine whether the type \p Derived is a C++ class that is |
2845 | | /// derived from the type \p Base. |
2846 | 6.37M | bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { |
2847 | 6.37M | if (!getLangOpts().CPlusPlus) |
2848 | 699 | return false; |
2849 | | |
2850 | 6.36M | CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); |
2851 | 6.36M | if (!DerivedRD) |
2852 | 1.44M | return false; |
2853 | | |
2854 | 4.92M | CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); |
2855 | 4.92M | if (!BaseRD) |
2856 | 4.33M | return false; |
2857 | | |
2858 | | // If either the base or the derived type is invalid, don't try to |
2859 | | // check whether one is derived from the other. |
2860 | 587k | if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()587k ) |
2861 | 13 | return false; |
2862 | | |
2863 | | // FIXME: In a modules build, do we need the entire path to be visible for us |
2864 | | // to be able to use the inheritance relationship? |
2865 | 587k | if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()7.40k ) |
2866 | 6.65k | return false; |
2867 | | |
2868 | 580k | return DerivedRD->isDerivedFrom(BaseRD); |
2869 | 587k | } |
2870 | | |
2871 | | /// Determine whether the type \p Derived is a C++ class that is |
2872 | | /// derived from the type \p Base. |
2873 | | bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, |
2874 | 96.8k | CXXBasePaths &Paths) { |
2875 | 96.8k | if (!getLangOpts().CPlusPlus) |
2876 | 202 | return false; |
2877 | | |
2878 | 96.6k | CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); |
2879 | 96.6k | if (!DerivedRD) |
2880 | 0 | return false; |
2881 | | |
2882 | 96.6k | CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); |
2883 | 96.6k | if (!BaseRD) |
2884 | 1 | return false; |
2885 | | |
2886 | 96.6k | if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()69 ) |
2887 | 1 | return false; |
2888 | | |
2889 | 96.6k | return DerivedRD->isDerivedFrom(BaseRD, Paths); |
2890 | 96.6k | } |
2891 | | |
2892 | | static void BuildBasePathArray(const CXXBasePath &Path, |
2893 | 36.3k | CXXCastPath &BasePathArray) { |
2894 | | // We first go backward and check if we have a virtual base. |
2895 | | // FIXME: It would be better if CXXBasePath had the base specifier for |
2896 | | // the nearest virtual base. |
2897 | 36.3k | unsigned Start = 0; |
2898 | 77.8k | for (unsigned I = Path.size(); I != 0; --I41.5k ) { |
2899 | 42.2k | if (Path[I - 1].Base->isVirtual()) { |
2900 | 726 | Start = I - 1; |
2901 | 726 | break; |
2902 | 726 | } |
2903 | 42.2k | } |
2904 | | |
2905 | | // Now add all bases. |
2906 | 78.5k | for (unsigned I = Start, E = Path.size(); I != E; ++I42.2k ) |
2907 | 42.2k | BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); |
2908 | 36.3k | } |
2909 | | |
2910 | | |
2911 | | void Sema::BuildBasePathArray(const CXXBasePaths &Paths, |
2912 | 1.61k | CXXCastPath &BasePathArray) { |
2913 | 1.61k | assert(BasePathArray.empty() && "Base path array must be empty!"); |
2914 | 0 | assert(Paths.isRecordingPaths() && "Must record paths!"); |
2915 | 0 | return ::BuildBasePathArray(Paths.front(), BasePathArray); |
2916 | 1.61k | } |
2917 | | /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base |
2918 | | /// conversion (where Derived and Base are class types) is |
2919 | | /// well-formed, meaning that the conversion is unambiguous (and |
2920 | | /// that all of the base classes are accessible). Returns true |
2921 | | /// and emits a diagnostic if the code is ill-formed, returns false |
2922 | | /// otherwise. Loc is the location where this routine should point to |
2923 | | /// if there is an error, and Range is the source range to highlight |
2924 | | /// if there is an error. |
2925 | | /// |
2926 | | /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the |
2927 | | /// diagnostic for the respective type of error will be suppressed, but the |
2928 | | /// check for ill-formed code will still be performed. |
2929 | | bool |
2930 | | Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, |
2931 | | unsigned InaccessibleBaseID, |
2932 | | unsigned AmbiguousBaseConvID, |
2933 | | SourceLocation Loc, SourceRange Range, |
2934 | | DeclarationName Name, |
2935 | | CXXCastPath *BasePath, |
2936 | 35.3k | bool IgnoreAccess) { |
2937 | | // First, determine whether the path from Derived to Base is |
2938 | | // ambiguous. This is slightly more expensive than checking whether |
2939 | | // the Derived to Base conversion exists, because here we need to |
2940 | | // explore multiple paths to determine if there is an ambiguity. |
2941 | 35.3k | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, |
2942 | 35.3k | /*DetectVirtual=*/false); |
2943 | 35.3k | bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); |
2944 | 35.3k | if (!DerivationOkay) |
2945 | 1 | return true; |
2946 | | |
2947 | 35.3k | const CXXBasePath *Path = nullptr; |
2948 | 35.3k | if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) |
2949 | 35.2k | Path = &Paths.front(); |
2950 | | |
2951 | | // For MSVC compatibility, check if Derived directly inherits from Base. Clang |
2952 | | // warns about this hierarchy under -Winaccessible-base, but MSVC allows the |
2953 | | // user to access such bases. |
2954 | 35.3k | if (!Path && getLangOpts().MSVCCompat62 ) { |
2955 | 9 | for (const CXXBasePath &PossiblePath : Paths) { |
2956 | 9 | if (PossiblePath.size() == 1) { |
2957 | 5 | Path = &PossiblePath; |
2958 | 5 | if (AmbiguousBaseConvID) |
2959 | 5 | Diag(Loc, diag::ext_ms_ambiguous_direct_base) |
2960 | 5 | << Base << Derived << Range; |
2961 | 5 | break; |
2962 | 5 | } |
2963 | 9 | } |
2964 | 5 | } |
2965 | | |
2966 | 35.3k | if (Path) { |
2967 | 35.2k | if (!IgnoreAccess) { |
2968 | | // Check that the base class can be accessed. |
2969 | 24.4k | switch ( |
2970 | 24.4k | CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { |
2971 | 55 | case AR_inaccessible: |
2972 | 55 | return true; |
2973 | 24.3k | case AR_accessible: |
2974 | 24.3k | case AR_dependent: |
2975 | 24.4k | case AR_delayed: |
2976 | 24.4k | break; |
2977 | 24.4k | } |
2978 | 24.4k | } |
2979 | | |
2980 | | // Build a base path if necessary. |
2981 | 35.1k | if (BasePath) |
2982 | 34.7k | ::BuildBasePathArray(*Path, *BasePath); |
2983 | 35.1k | return false; |
2984 | 35.2k | } |
2985 | | |
2986 | 57 | if (AmbiguousBaseConvID) { |
2987 | | // We know that the derived-to-base conversion is ambiguous, and |
2988 | | // we're going to produce a diagnostic. Perform the derived-to-base |
2989 | | // search just one more time to compute all of the possible paths so |
2990 | | // that we can print them out. This is more expensive than any of |
2991 | | // the previous derived-to-base checks we've done, but at this point |
2992 | | // performance isn't as much of an issue. |
2993 | 53 | Paths.clear(); |
2994 | 53 | Paths.setRecordingPaths(true); |
2995 | 53 | bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); |
2996 | 53 | assert(StillOkay && "Can only be used with a derived-to-base conversion"); |
2997 | 0 | (void)StillOkay; |
2998 | | |
2999 | | // Build up a textual representation of the ambiguous paths, e.g., |
3000 | | // D -> B -> A, that will be used to illustrate the ambiguous |
3001 | | // conversions in the diagnostic. We only print one of the paths |
3002 | | // to each base class subobject. |
3003 | 53 | std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); |
3004 | | |
3005 | 53 | Diag(Loc, AmbiguousBaseConvID) |
3006 | 53 | << Derived << Base << PathDisplayStr << Range << Name; |
3007 | 53 | } |
3008 | 0 | return true; |
3009 | 35.3k | } |
3010 | | |
3011 | | bool |
3012 | | Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, |
3013 | | SourceLocation Loc, SourceRange Range, |
3014 | | CXXCastPath *BasePath, |
3015 | 29.0k | bool IgnoreAccess) { |
3016 | 29.0k | return CheckDerivedToBaseConversion( |
3017 | 29.0k | Derived, Base, diag::err_upcast_to_inaccessible_base, |
3018 | 29.0k | diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), |
3019 | 29.0k | BasePath, IgnoreAccess); |
3020 | 29.0k | } |
3021 | | |
3022 | | |
3023 | | /// Builds a string representing ambiguous paths from a |
3024 | | /// specific derived class to different subobjects of the same base |
3025 | | /// class. |
3026 | | /// |
3027 | | /// This function builds a string that can be used in error messages |
3028 | | /// to show the different paths that one can take through the |
3029 | | /// inheritance hierarchy to go from the derived class to different |
3030 | | /// subobjects of a base class. The result looks something like this: |
3031 | | /// @code |
3032 | | /// struct D -> struct B -> struct A |
3033 | | /// struct D -> struct C -> struct A |
3034 | | /// @endcode |
3035 | 339 | std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { |
3036 | 339 | std::string PathDisplayStr; |
3037 | 339 | std::set<unsigned> DisplayedPaths; |
3038 | 339 | for (CXXBasePaths::paths_iterator Path = Paths.begin(); |
3039 | 1.20k | Path != Paths.end(); ++Path864 ) { |
3040 | 864 | if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { |
3041 | | // We haven't displayed a path to this particular base |
3042 | | // class subobject yet. |
3043 | 800 | PathDisplayStr += "\n "; |
3044 | 800 | PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); |
3045 | 800 | for (CXXBasePath::const_iterator Element = Path->begin(); |
3046 | 2.46k | Element != Path->end(); ++Element1.66k ) |
3047 | 1.66k | PathDisplayStr += " -> " + Element->Base->getType().getAsString(); |
3048 | 800 | } |
3049 | 864 | } |
3050 | | |
3051 | 339 | return PathDisplayStr; |
3052 | 339 | } |
3053 | | |
3054 | | //===----------------------------------------------------------------------===// |
3055 | | // C++ class member Handling |
3056 | | //===----------------------------------------------------------------------===// |
3057 | | |
3058 | | /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. |
3059 | | bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, |
3060 | | SourceLocation ColonLoc, |
3061 | 186k | const ParsedAttributesView &Attrs) { |
3062 | 186k | assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); |
3063 | 0 | AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, |
3064 | 186k | ASLoc, ColonLoc); |
3065 | 186k | CurContext->addHiddenDecl(ASDecl); |
3066 | 186k | return ProcessAccessDeclAttributeList(ASDecl, Attrs); |
3067 | 186k | } |
3068 | | |
3069 | | /// CheckOverrideControl - Check C++11 override control semantics. |
3070 | 4.10M | void Sema::CheckOverrideControl(NamedDecl *D) { |
3071 | 4.10M | if (D->isInvalidDecl()) |
3072 | 1.02k | return; |
3073 | | |
3074 | | // We only care about "override" and "final" declarations. |
3075 | 4.10M | if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()4.10M ) |
3076 | 4.10M | return; |
3077 | | |
3078 | 636 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); |
3079 | | |
3080 | | // We can't check dependent instance methods. |
3081 | 636 | if (MD && MD->isInstance()634 && |
3082 | 636 | (633 MD->getParent()->hasAnyDependentBases()633 || |
3083 | 633 | MD->getType()->isDependentType()615 )) |
3084 | 24 | return; |
3085 | | |
3086 | 612 | if (MD && !MD->isVirtual()610 ) { |
3087 | | // If we have a non-virtual method, check if if hides a virtual method. |
3088 | | // (In that case, it's most likely the method has the wrong type.) |
3089 | 18 | SmallVector<CXXMethodDecl *, 8> OverloadedMethods; |
3090 | 18 | FindHiddenVirtualMethods(MD, OverloadedMethods); |
3091 | | |
3092 | 18 | if (!OverloadedMethods.empty()) { |
3093 | 4 | if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { |
3094 | 3 | Diag(OA->getLocation(), |
3095 | 3 | diag::override_keyword_hides_virtual_member_function) |
3096 | 3 | << "override" << (OverloadedMethods.size() > 1); |
3097 | 3 | } else if (FinalAttr *1 FA1 = D->getAttr<FinalAttr>()) { |
3098 | 1 | Diag(FA->getLocation(), |
3099 | 1 | diag::override_keyword_hides_virtual_member_function) |
3100 | 1 | << (FA->isSpelledAsSealed() ? "sealed"0 : "final") |
3101 | 1 | << (OverloadedMethods.size() > 1); |
3102 | 1 | } |
3103 | 4 | NoteHiddenVirtualMethods(MD, OverloadedMethods); |
3104 | 4 | MD->setInvalidDecl(); |
3105 | 4 | return; |
3106 | 4 | } |
3107 | | // Fall through into the general case diagnostic. |
3108 | | // FIXME: We might want to attempt typo correction here. |
3109 | 18 | } |
3110 | | |
3111 | 608 | if (!MD || !MD->isVirtual()606 ) { |
3112 | 16 | if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { |
3113 | 10 | Diag(OA->getLocation(), |
3114 | 10 | diag::override_keyword_only_allowed_on_virtual_member_functions) |
3115 | 10 | << "override" << FixItHint::CreateRemoval(OA->getLocation()); |
3116 | 10 | D->dropAttr<OverrideAttr>(); |
3117 | 10 | } |
3118 | 16 | if (FinalAttr *FA = D->getAttr<FinalAttr>()) { |
3119 | 6 | Diag(FA->getLocation(), |
3120 | 6 | diag::override_keyword_only_allowed_on_virtual_member_functions) |
3121 | 6 | << (FA->isSpelledAsSealed() ? "sealed"0 : "final") |
3122 | 6 | << FixItHint::CreateRemoval(FA->getLocation()); |
3123 | 6 | D->dropAttr<FinalAttr>(); |
3124 | 6 | } |
3125 | 16 | return; |
3126 | 16 | } |
3127 | | |
3128 | | // C++11 [class.virtual]p5: |
3129 | | // If a function is marked with the virt-specifier override and |
3130 | | // does not override a member function of a base class, the program is |
3131 | | // ill-formed. |
3132 | 592 | bool HasOverriddenMethods = MD->size_overridden_methods() != 0; |
3133 | 592 | if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods520 ) |
3134 | 4 | Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) |
3135 | 4 | << MD->getDeclName(); |
3136 | 592 | } |
3137 | | |
3138 | 150k | void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { |
3139 | 150k | if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()150k ) |
3140 | 40 | return; |
3141 | 150k | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); |
3142 | 150k | if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()117k ) |
3143 | 33.4k | return; |
3144 | | |
3145 | 117k | SourceLocation Loc = MD->getLocation(); |
3146 | 117k | SourceLocation SpellingLoc = Loc; |
3147 | 117k | if (getSourceManager().isMacroArgExpansion(Loc)) |
3148 | 1 | SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); |
3149 | 117k | SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); |
3150 | 117k | if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) |
3151 | 114k | return; |
3152 | | |
3153 | 2.86k | if (MD->size_overridden_methods() > 0) { |
3154 | 1.84k | auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { |
3155 | 1.84k | unsigned DiagID = |
3156 | 1.84k | Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())6 |
3157 | 1.84k | ? DiagInconsistent4 |
3158 | 1.84k | : DiagSuggest1.84k ; |
3159 | 1.84k | Diag(MD->getLocation(), DiagID) << MD->getDeclName(); |
3160 | 1.84k | const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); |
3161 | 1.84k | Diag(OMD->getLocation(), diag::note_overridden_virtual_function); |
3162 | 1.84k | }; |
3163 | 1.84k | if (isa<CXXDestructorDecl>(MD)) |
3164 | 374 | EmitDiag( |
3165 | 374 | diag::warn_inconsistent_destructor_marked_not_override_overriding, |
3166 | 374 | diag::warn_suggest_destructor_marked_not_override_overriding); |
3167 | 1.47k | else |
3168 | 1.47k | EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, |
3169 | 1.47k | diag::warn_suggest_function_marked_not_override_overriding); |
3170 | 1.84k | } |
3171 | 2.86k | } |
3172 | | |
3173 | | /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member |
3174 | | /// function overrides a virtual member function marked 'final', according to |
3175 | | /// C++11 [class.virtual]p4. |
3176 | | bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, |
3177 | 35.3k | const CXXMethodDecl *Old) { |
3178 | 35.3k | FinalAttr *FA = Old->getAttr<FinalAttr>(); |
3179 | 35.3k | if (!FA) |
3180 | 35.3k | return false; |
3181 | | |
3182 | 7 | Diag(New->getLocation(), diag::err_final_function_overridden) |
3183 | 7 | << New->getDeclName() |
3184 | 7 | << FA->isSpelledAsSealed(); |
3185 | 7 | Diag(Old->getLocation(), diag::note_overridden_virtual_function); |
3186 | 7 | return true; |
3187 | 35.3k | } |
3188 | | |
3189 | 195 | static bool InitializationHasSideEffects(const FieldDecl &FD) { |
3190 | 195 | const Type *T = FD.getType()->getBaseElementTypeUnsafe(); |
3191 | | // FIXME: Destruction of ObjC lifetime types has side-effects. |
3192 | 195 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) |
3193 | 38 | return !RD->isCompleteDefinition() || |
3194 | 38 | !RD->hasTrivialDefaultConstructor() || |
3195 | 38 | !RD->hasTrivialDestructor()32 ; |
3196 | 157 | return false; |
3197 | 195 | } |
3198 | | |
3199 | 3.01M | static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { |
3200 | 3.01M | ParsedAttributesView::const_iterator Itr = |
3201 | 3.01M | llvm::find_if(list, [](const ParsedAttr &AL) { |
3202 | 2.22M | return AL.isDeclspecPropertyAttribute(); |
3203 | 2.22M | }); |
3204 | 3.01M | if (Itr != list.end()) |
3205 | 99 | return &*Itr; |
3206 | 3.01M | return nullptr; |
3207 | 3.01M | } |
3208 | | |
3209 | | // Check if there is a field shadowing. |
3210 | | void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, |
3211 | | DeclarationName FieldName, |
3212 | | const CXXRecordDecl *RD, |
3213 | 2.28M | bool DeclIsField) { |
3214 | 2.28M | if (Diags.isIgnored(diag::warn_shadow_field, Loc)) |
3215 | 2.28M | return; |
3216 | | |
3217 | | // To record a shadowed field in a base |
3218 | 56 | std::map<CXXRecordDecl*, NamedDecl*> Bases; |
3219 | 56 | auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, |
3220 | 83 | CXXBasePath &Path) { |
3221 | 83 | const auto Base = Specifier->getType()->getAsCXXRecordDecl(); |
3222 | | // Record an ambiguous path directly |
3223 | 83 | if (Bases.find(Base) != Bases.end()) |
3224 | 10 | return true; |
3225 | 73 | for (const auto Field : Base->lookup(FieldName)) { |
3226 | 23 | if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)3 ) && |
3227 | 23 | Field->getAccess() != AS_private21 ) { |
3228 | 15 | assert(Field->getAccess() != AS_none); |
3229 | 0 | assert(Bases.find(Base) == Bases.end()); |
3230 | 0 | Bases[Base] = Field; |
3231 | 15 | return true; |
3232 | 15 | } |
3233 | 23 | } |
3234 | 58 | return false; |
3235 | 73 | }; |
3236 | | |
3237 | 56 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, |
3238 | 56 | /*DetectVirtual=*/true); |
3239 | 56 | if (!RD->lookupInBases(FieldShadowed, Paths)) |
3240 | 43 | return; |
3241 | | |
3242 | 25 | for (const auto &P : Paths)13 { |
3243 | 25 | auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); |
3244 | 25 | auto It = Bases.find(Base); |
3245 | | // Skip duplicated bases |
3246 | 25 | if (It == Bases.end()) |
3247 | 7 | continue; |
3248 | 18 | auto BaseField = It->second; |
3249 | 18 | assert(BaseField->getAccess() != AS_private); |
3250 | 18 | if (AS_none != |
3251 | 18 | CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { |
3252 | 14 | Diag(Loc, diag::warn_shadow_field) |
3253 | 14 | << FieldName << RD << Base << DeclIsField; |
3254 | 14 | Diag(BaseField->getLocation(), diag::note_shadow_field); |
3255 | 14 | Bases.erase(It); |
3256 | 14 | } |
3257 | 18 | } |
3258 | 13 | } |
3259 | | |
3260 | | /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member |
3261 | | /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the |
3262 | | /// bitfield width if there is one, 'InitExpr' specifies the initializer if |
3263 | | /// one has been parsed, and 'InitStyle' is set if an in-class initializer is |
3264 | | /// present (but parsing it has been deferred). |
3265 | | NamedDecl * |
3266 | | Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, |
3267 | | MultiTemplateParamsArg TemplateParameterLists, |
3268 | | Expr *BW, const VirtSpecifiers &VS, |
3269 | 3.01M | InClassInitStyle InitStyle) { |
3270 | 3.01M | const DeclSpec &DS = D.getDeclSpec(); |
3271 | 3.01M | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); |
3272 | 3.01M | DeclarationName Name = NameInfo.getName(); |
3273 | 3.01M | SourceLocation Loc = NameInfo.getLoc(); |
3274 | | |
3275 | | // For anonymous bitfields, the location should point to the type. |
3276 | 3.01M | if (Loc.isInvalid()) |
3277 | 1 | Loc = D.getBeginLoc(); |
3278 | | |
3279 | 3.01M | Expr *BitWidth = static_cast<Expr*>(BW); |
3280 | | |
3281 | 3.01M | assert(isa<CXXRecordDecl>(CurContext)); |
3282 | 0 | assert(!DS.isFriendSpecified()); |
3283 | | |
3284 | 0 | bool isFunc = D.isDeclarationOfFunction(); |
3285 | 3.01M | const ParsedAttr *MSPropertyAttr = |
3286 | 3.01M | getMSPropertyAttr(D.getDeclSpec().getAttributes()); |
3287 | | |
3288 | 3.01M | if (cast<CXXRecordDecl>(CurContext)->isInterface()) { |
3289 | | // The Microsoft extension __interface only permits public member functions |
3290 | | // and prohibits constructors, destructors, operators, non-public member |
3291 | | // functions, static methods and data members. |
3292 | 23 | unsigned InvalidDecl; |
3293 | 23 | bool ShowDeclName = true; |
3294 | 23 | if (!isFunc && |
3295 | 23 | (3 DS.getStorageClassSpec() == DeclSpec::SCS_typedef3 || MSPropertyAttr2 )) |
3296 | 2 | InvalidDecl = 0; |
3297 | 21 | else if (!isFunc) |
3298 | 1 | InvalidDecl = 1; |
3299 | 20 | else if (AS != AS_public) |
3300 | 2 | InvalidDecl = 2; |
3301 | 18 | else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) |
3302 | 1 | InvalidDecl = 3; |
3303 | 17 | else switch (Name.getNameKind()) { |
3304 | 1 | case DeclarationName::CXXConstructorName: |
3305 | 1 | InvalidDecl = 4; |
3306 | 1 | ShowDeclName = false; |
3307 | 1 | break; |
3308 | | |
3309 | 1 | case DeclarationName::CXXDestructorName: |
3310 | 1 | InvalidDecl = 5; |
3311 | 1 | ShowDeclName = false; |
3312 | 1 | break; |
3313 | | |
3314 | 1 | case DeclarationName::CXXOperatorName: |
3315 | 2 | case DeclarationName::CXXConversionFunctionName: |
3316 | 2 | InvalidDecl = 6; |
3317 | 2 | break; |
3318 | | |
3319 | 13 | default: |
3320 | 13 | InvalidDecl = 0; |
3321 | 13 | break; |
3322 | 17 | } |
3323 | | |
3324 | 23 | if (InvalidDecl) { |
3325 | 8 | if (ShowDeclName) |
3326 | 6 | Diag(Loc, diag::err_invalid_member_in_interface) |
3327 | 6 | << (InvalidDecl-1) << Name; |
3328 | 2 | else |
3329 | 2 | Diag(Loc, diag::err_invalid_member_in_interface) |
3330 | 2 | << (InvalidDecl-1) << ""; |
3331 | 8 | return nullptr; |
3332 | 8 | } |
3333 | 23 | } |
3334 | | |
3335 | | // C++ 9.2p6: A member shall not be declared to have automatic storage |
3336 | | // duration (auto, register) or with the extern storage-class-specifier. |
3337 | | // C++ 7.1.1p8: The mutable specifier can be applied only to names of class |
3338 | | // data members and cannot be applied to names declared const or static, |
3339 | | // and cannot be applied to reference members. |
3340 | 3.01M | switch (DS.getStorageClassSpec()) { |
3341 | 2.25M | case DeclSpec::SCS_unspecified: |
3342 | 2.65M | case DeclSpec::SCS_typedef: |
3343 | 3.00M | case DeclSpec::SCS_static: |
3344 | 3.00M | break; |
3345 | 3.30k | case DeclSpec::SCS_mutable: |
3346 | 3.30k | if (isFunc) { |
3347 | 4 | Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); |
3348 | | |
3349 | | // FIXME: It would be nicer if the keyword was ignored only for this |
3350 | | // declarator. Otherwise we could get follow-up errors. |
3351 | 4 | D.getMutableDeclSpec().ClearStorageClassSpecs(); |
3352 | 4 | } |
3353 | 3.30k | break; |
3354 | 19 | default: |
3355 | 19 | Diag(DS.getStorageClassSpecLoc(), |
3356 | 19 | diag::err_storageclass_invalid_for_member); |
3357 | 19 | D.getMutableDeclSpec().ClearStorageClassSpecs(); |
3358 | 19 | break; |
3359 | 3.01M | } |
3360 | | |
3361 | 3.01M | bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || |
3362 | 3.01M | DS.getStorageClassSpec() == DeclSpec::SCS_mutable755k ) && |
3363 | 3.01M | !isFunc2.25M ); |
3364 | | |
3365 | 3.01M | if (DS.hasConstexprSpecifier() && isInstField269k ) { |
3366 | 24 | SemaDiagnosticBuilder B = |
3367 | 24 | Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); |
3368 | 24 | SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); |
3369 | 24 | if (InitStyle == ICIS_NoInit) { |
3370 | 13 | B << 0 << 0; |
3371 | 13 | if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) |
3372 | 2 | B << FixItHint::CreateRemoval(ConstexprLoc); |
3373 | 11 | else { |
3374 | 11 | B << FixItHint::CreateReplacement(ConstexprLoc, "const"); |
3375 | 11 | D.getMutableDeclSpec().ClearConstexprSpec(); |
3376 | 11 | const char *PrevSpec; |
3377 | 11 | unsigned DiagID; |
3378 | 11 | bool Failed = D.getMutableDeclSpec().SetTypeQual( |
3379 | 11 | DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); |
3380 | 11 | (void)Failed; |
3381 | 11 | assert(!Failed && "Making a constexpr member const shouldn't fail"); |
3382 | 11 | } |
3383 | 13 | } else { |
3384 | 11 | B << 1; |
3385 | 11 | const char *PrevSpec; |
3386 | 11 | unsigned DiagID; |
3387 | 11 | if (D.getMutableDeclSpec().SetStorageClassSpec( |
3388 | 11 | *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, |
3389 | 11 | Context.getPrintingPolicy())) { |
3390 | 5 | assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && |
3391 | 5 | "This is the only DeclSpec that should fail to be applied"); |
3392 | 0 | B << 1; |
3393 | 6 | } else { |
3394 | 6 | B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); |
3395 | 6 | isInstField = false; |
3396 | 6 | } |
3397 | 11 | } |
3398 | 24 | } |
3399 | | |
3400 | 0 | NamedDecl *Member; |
3401 | 3.01M | if (isInstField) { |
3402 | 1.09M | CXXScopeSpec &SS = D.getCXXScopeSpec(); |
3403 | | |
3404 | | // Data members must have identifiers for names. |
3405 | 1.09M | if (!Name.isIdentifier()) { |
3406 | 9 | Diag(Loc, diag::err_bad_variable_name) |
3407 | 9 | << Name; |
3408 | 9 | return nullptr; |
3409 | 9 | } |
3410 | | |
3411 | 1.09M | IdentifierInfo *II = Name.getAsIdentifierInfo(); |
3412 | | |
3413 | | // Member field could not be with "template" keyword. |
3414 | | // So TemplateParameterLists should be empty in this case. |
3415 | 1.09M | if (TemplateParameterLists.size()) { |
3416 | 20 | TemplateParameterList* TemplateParams = TemplateParameterLists[0]; |
3417 | 20 | if (TemplateParams->size()) { |
3418 | | // There is no such thing as a member field template. |
3419 | 19 | Diag(D.getIdentifierLoc(), diag::err_template_member) |
3420 | 19 | << II |
3421 | 19 | << SourceRange(TemplateParams->getTemplateLoc(), |
3422 | 19 | TemplateParams->getRAngleLoc()); |
3423 | 19 | } else { |
3424 | | // There is an extraneous 'template<>' for this member. |
3425 | 1 | Diag(TemplateParams->getTemplateLoc(), |
3426 | 1 | diag::err_template_member_noparams) |
3427 | 1 | << II |
3428 | 1 | << SourceRange(TemplateParams->getTemplateLoc(), |
3429 | 1 | TemplateParams->getRAngleLoc()); |
3430 | 1 | } |
3431 | 20 | return nullptr; |
3432 | 20 | } |
3433 | | |
3434 | 1.09M | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { |
3435 | 12 | Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments) |
3436 | 12 | << II |
3437 | 12 | << SourceRange(D.getName().TemplateId->LAngleLoc, |
3438 | 12 | D.getName().TemplateId->RAngleLoc) |
3439 | 12 | << D.getName().TemplateId->LAngleLoc; |
3440 | 12 | D.SetIdentifier(II, Loc); |
3441 | 12 | } |
3442 | | |
3443 | 1.09M | if (SS.isSet() && !SS.isInvalid()6 ) { |
3444 | | // The user provided a superfluous scope specifier inside a class |
3445 | | // definition: |
3446 | | // |
3447 | | // class X { |
3448 | | // int X::member; |
3449 | | // }; |
3450 | 6 | if (DeclContext *DC = computeDeclContext(SS, false)) |
3451 | 2 | diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), |
3452 | 2 | D.getName().getKind() == |
3453 | 2 | UnqualifiedIdKind::IK_TemplateId); |
3454 | 4 | else |
3455 | 4 | Diag(D.getIdentifierLoc(), diag::err_member_qualification) |
3456 | 4 | << Name << SS.getRange(); |
3457 | | |
3458 | 6 | SS.clear(); |
3459 | 6 | } |
3460 | | |
3461 | 1.09M | if (MSPropertyAttr) { |
3462 | 99 | Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, |
3463 | 99 | BitWidth, InitStyle, AS, *MSPropertyAttr); |
3464 | 99 | if (!Member) |
3465 | 3 | return nullptr; |
3466 | 96 | isInstField = false; |
3467 | 1.09M | } else { |
3468 | 1.09M | Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, |
3469 | 1.09M | BitWidth, InitStyle, AS); |
3470 | 1.09M | if (!Member) |
3471 | 8 | return nullptr; |
3472 | 1.09M | } |
3473 | | |
3474 | 1.09M | CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); |
3475 | 1.91M | } else { |
3476 | 1.91M | Member = HandleDeclarator(S, D, TemplateParameterLists); |
3477 | 1.91M | if (!Member) |
3478 | 123 | return nullptr; |
3479 | | |
3480 | | // Non-instance-fields can't have a bitfield. |
3481 | 1.91M | if (BitWidth) { |
3482 | 9 | if (Member->isInvalidDecl()) { |
3483 | | // don't emit another diagnostic. |
3484 | 9 | } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)7 ) { |
3485 | | // C++ 9.6p3: A bit-field shall not be a static member. |
3486 | | // "static member 'A' cannot be a bit-field" |
3487 | 5 | Diag(Loc, diag::err_static_not_bitfield) |
3488 | 5 | << Name << BitWidth->getSourceRange(); |
3489 | 5 | } else if (4 isa<TypedefDecl>(Member)4 ) { |
3490 | | // "typedef member 'x' cannot be a bit-field" |
3491 | 2 | Diag(Loc, diag::err_typedef_not_bitfield) |
3492 | 2 | << Name << BitWidth->getSourceRange(); |
3493 | 2 | } else { |
3494 | | // A function typedef ("typedef int f(); f a;"). |
3495 | | // C++ 9.6p3: A bit-field shall have integral or enumeration type. |
3496 | 2 | Diag(Loc, diag::err_not_integral_type_bitfield) |
3497 | 2 | << Name << cast<ValueDecl>(Member)->getType() |
3498 | 2 | << BitWidth->getSourceRange(); |
3499 | 2 | } |
3500 | | |
3501 | 9 | BitWidth = nullptr; |
3502 | 9 | Member->setInvalidDecl(); |
3503 | 9 | } |
3504 | | |
3505 | 1.91M | NamedDecl *NonTemplateMember = Member; |
3506 | 1.91M | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) |
3507 | 209k | NonTemplateMember = FunTmpl->getTemplatedDecl(); |
3508 | 1.70M | else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) |
3509 | 526 | NonTemplateMember = VarTmpl->getTemplatedDecl(); |
3510 | | |
3511 | 1.91M | Member->setAccess(AS); |
3512 | | |
3513 | | // If we have declared a member function template or static data member |
3514 | | // template, set the access of the templated declaration as well. |
3515 | 1.91M | if (NonTemplateMember != Member) |
3516 | 210k | NonTemplateMember->setAccess(AS); |
3517 | | |
3518 | | // C++ [temp.deduct.guide]p3: |
3519 | | // A deduction guide [...] for a member class template [shall be |
3520 | | // declared] with the same access [as the template]. |
3521 | 1.91M | if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { |
3522 | 46 | auto *TD = DG->getDeducedTemplate(); |
3523 | | // Access specifiers are only meaningful if both the template and the |
3524 | | // deduction guide are from the same scope. |
3525 | 46 | if (AS != TD->getAccess() && |
3526 | 46 | TD->getDeclContext()->getRedeclContext()->Equals( |
3527 | 7 | DG->getDeclContext()->getRedeclContext())) { |
3528 | 4 | Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); |
3529 | 4 | Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) |
3530 | 4 | << TD->getAccess(); |
3531 | 4 | const AccessSpecDecl *LastAccessSpec = nullptr; |
3532 | 62 | for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { |
3533 | 62 | if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) |
3534 | 9 | LastAccessSpec = AccessSpec; |
3535 | 62 | } |
3536 | 4 | assert(LastAccessSpec && "differing access with no access specifier"); |
3537 | 0 | Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) |
3538 | 4 | << AS; |
3539 | 4 | } |
3540 | 46 | } |
3541 | 1.91M | } |
3542 | | |
3543 | 3.01M | if (VS.isOverrideSpecified()) |
3544 | 536 | Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), |
3545 | 536 | AttributeCommonInfo::AS_Keyword)); |
3546 | 3.01M | if (VS.isFinalSpecified()) |
3547 | 90 | Member->addAttr(FinalAttr::Create( |
3548 | 90 | Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, |
3549 | 90 | static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); |
3550 | | |
3551 | 3.01M | if (VS.getLastLocation().isValid()) { |
3552 | | // Update the end location of a method that has a virt-specifiers. |
3553 | 624 | if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) |
3554 | 622 | MD->setRangeEnd(VS.getLastLocation()); |
3555 | 624 | } |
3556 | | |
3557 | 3.01M | CheckOverrideControl(Member); |
3558 | | |
3559 | 3.01M | assert((Name || isInstField) && "No identifier for non-field ?"); |
3560 | | |
3561 | 3.01M | if (isInstField) { |
3562 | 1.09M | FieldDecl *FD = cast<FieldDecl>(Member); |
3563 | 1.09M | FieldCollector->Add(FD); |
3564 | | |
3565 | 1.09M | if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { |
3566 | | // Remember all explicit private FieldDecls that have a name, no side |
3567 | | // effects and are not part of a dependent type declaration. |
3568 | 612 | if (!FD->isImplicit() && FD->getDeclName() && |
3569 | 612 | FD->getAccess() == AS_private597 && |
3570 | 612 | !FD->hasAttr<UnusedAttr>()223 && |
3571 | 612 | !FD->getParent()->isDependentContext()214 && |
3572 | 612 | !InitializationHasSideEffects(*FD)195 ) |
3573 | 183 | UnusedPrivateFields.insert(FD); |
3574 | 612 | } |
3575 | 1.09M | } |
3576 | | |
3577 | 3.01M | return Member; |
3578 | 3.01M | } |
3579 | | |
3580 | | namespace { |
3581 | | class UninitializedFieldVisitor |
3582 | | : public EvaluatedExprVisitor<UninitializedFieldVisitor> { |
3583 | | Sema &S; |
3584 | | // List of Decls to generate a warning on. Also remove Decls that become |
3585 | | // initialized. |
3586 | | llvm::SmallPtrSetImpl<ValueDecl*> &Decls; |
3587 | | // List of base classes of the record. Classes are removed after their |
3588 | | // initializers. |
3589 | | llvm::SmallPtrSetImpl<QualType> &BaseClasses; |
3590 | | // Vector of decls to be removed from the Decl set prior to visiting the |
3591 | | // nodes. These Decls may have been initialized in the prior initializer. |
3592 | | llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; |
3593 | | // If non-null, add a note to the warning pointing back to the constructor. |
3594 | | const CXXConstructorDecl *Constructor; |
3595 | | // Variables to hold state when processing an initializer list. When |
3596 | | // InitList is true, special case initialization of FieldDecls matching |
3597 | | // InitListFieldDecl. |
3598 | | bool InitList; |
3599 | | FieldDecl *InitListFieldDecl; |
3600 | | llvm::SmallVector<unsigned, 4> InitFieldIndex; |
3601 | | |
3602 | | public: |
3603 | | typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; |
3604 | | UninitializedFieldVisitor(Sema &S, |
3605 | | llvm::SmallPtrSetImpl<ValueDecl*> &Decls, |
3606 | | llvm::SmallPtrSetImpl<QualType> &BaseClasses) |
3607 | | : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), |
3608 | 35.6k | Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} |
3609 | | |
3610 | | // Returns true if the use of ME is not an uninitialized use. |
3611 | | bool IsInitListMemberExprInitialized(MemberExpr *ME, |
3612 | 65 | bool CheckReferenceOnly) { |
3613 | 65 | llvm::SmallVector<FieldDecl*, 4> Fields; |
3614 | 65 | bool ReferenceField = false; |
3615 | 227 | while (ME) { |
3616 | 162 | FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); |
3617 | 162 | if (!FD) |
3618 | 0 | return false; |
3619 | 162 | Fields.push_back(FD); |
3620 | 162 | if (FD->getType()->isReferenceType()) |
3621 | 12 | ReferenceField = true; |
3622 | 162 | ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); |
3623 | 162 | } |
3624 | | |
3625 | | // Binding a reference to an uninitialized field is not an |
3626 | | // uninitialized use. |
3627 | 65 | if (CheckReferenceOnly && !ReferenceField12 ) |
3628 | 6 | return true; |
3629 | | |
3630 | 59 | llvm::SmallVector<unsigned, 4> UsedFieldIndex; |
3631 | | // Discard the first field since it is the field decl that is being |
3632 | | // initialized. |
3633 | 59 | for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields))) |
3634 | 91 | UsedFieldIndex.push_back(FD->getFieldIndex()); |
3635 | | |
3636 | 59 | for (auto UsedIter = UsedFieldIndex.begin(), |
3637 | 59 | UsedEnd = UsedFieldIndex.end(), |
3638 | 59 | OrigIter = InitFieldIndex.begin(), |
3639 | 59 | OrigEnd = InitFieldIndex.end(); |
3640 | 95 | UsedIter != UsedEnd && OrigIter != OrigEnd75 ; ++UsedIter, ++OrigIter36 ) { |
3641 | 75 | if (*UsedIter < *OrigIter) |
3642 | 18 | return true; |
3643 | 57 | if (*UsedIter > *OrigIter) |
3644 | 21 | break; |
3645 | 57 | } |
3646 | | |
3647 | 41 | return false; |
3648 | 59 | } |
3649 | | |
3650 | | void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, |
3651 | 5.68k | bool AddressOf) { |
3652 | 5.68k | if (isa<EnumConstantDecl>(ME->getMemberDecl())) |
3653 | 9 | return; |
3654 | | |
3655 | | // FieldME is the inner-most MemberExpr that is not an anonymous struct |
3656 | | // or union. |
3657 | 5.67k | MemberExpr *FieldME = ME; |
3658 | | |
3659 | 5.67k | bool AllPODFields = FieldME->getType().isPODType(S.Context); |
3660 | | |
3661 | 5.67k | Expr *Base = ME; |
3662 | 11.5k | while (MemberExpr *SubME = |
3663 | 5.86k | dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { |
3664 | | |
3665 | 5.86k | if (isa<VarDecl>(SubME->getMemberDecl())) |
3666 | 8 | return; |
3667 | | |
3668 | 5.86k | if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) |
3669 | 5.74k | if (!FD->isAnonymousStructOrUnion()) |
3670 | 5.72k | FieldME = SubME; |
3671 | | |
3672 | 5.86k | if (!FieldME->getType().isPODType(S.Context)) |
3673 | 322 | AllPODFields = false; |
3674 | | |
3675 | 5.86k | Base = SubME->getBase(); |
3676 | 5.86k | } |
3677 | | |
3678 | 5.66k | if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { |
3679 | 5.10k | Visit(Base); |
3680 | 5.10k | return; |
3681 | 5.10k | } |
3682 | | |
3683 | 562 | if (AddressOf && AllPODFields3 ) |
3684 | 2 | return; |
3685 | | |
3686 | 560 | ValueDecl* FoundVD = FieldME->getMemberDecl(); |
3687 | | |
3688 | 560 | if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { |
3689 | 16 | while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { |
3690 | 0 | BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); |
3691 | 0 | } |
3692 | | |
3693 | 16 | if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { |
3694 | 13 | QualType T = BaseCast->getType(); |
3695 | 13 | if (T->isPointerType() && |
3696 | 13 | BaseClasses.count(T->getPointeeType())) { |
3697 | 4 | S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) |
3698 | 4 | << T->getPointeeType() << FoundVD; |
3699 | 4 | } |
3700 | 13 | } |
3701 | 16 | } |
3702 | | |
3703 | 560 | if (!Decls.count(FoundVD)) |
3704 | 217 | return; |
3705 | | |
3706 | 343 | const bool IsReference = FoundVD->getType()->isReferenceType(); |
3707 | | |
3708 | 343 | if (InitList && !AddressOf70 && FoundVD == InitListFieldDecl70 ) { |
3709 | | // Special checking for initializer lists. |
3710 | 65 | if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { |
3711 | 24 | return; |
3712 | 24 | } |
3713 | 278 | } else { |
3714 | | // Prevent double warnings on use of unbounded references. |
3715 | 278 | if (CheckReferenceOnly && !IsReference85 ) |
3716 | 81 | return; |
3717 | 278 | } |
3718 | | |
3719 | 238 | unsigned diag = IsReference |
3720 | 238 | ? diag::warn_reference_field_is_uninit5 |
3721 | 238 | : diag::warn_field_is_uninit233 ; |
3722 | 238 | S.Diag(FieldME->getExprLoc(), diag) << FoundVD; |
3723 | 238 | if (Constructor) |
3724 | 45 | S.Diag(Constructor->getLocation(), |
3725 | 45 | diag::note_uninit_in_this_constructor) |
3726 | 45 | << (Constructor->isDefaultConstructor() && Constructor->isImplicit()44 ); |
3727 | | |
3728 | 238 | } |
3729 | | |
3730 | 15.7k | void HandleValue(Expr *E, bool AddressOf) { |
3731 | 15.7k | E = E->IgnoreParens(); |
3732 | | |
3733 | 15.7k | if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { |
3734 | 5.49k | HandleMemberExpr(ME, false /*CheckReferenceOnly*/, |
3735 | 5.49k | AddressOf /*AddressOf*/); |
3736 | 5.49k | return; |
3737 | 5.49k | } |
3738 | | |
3739 | 10.2k | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { |
3740 | 16 | Visit(CO->getCond()); |
3741 | 16 | HandleValue(CO->getTrueExpr(), AddressOf); |
3742 | 16 | HandleValue(CO->getFalseExpr(), AddressOf); |
3743 | 16 | return; |
3744 | 16 | } |
3745 | | |
3746 | 10.2k | if (BinaryConditionalOperator *BCO = |
3747 | 10.2k | dyn_cast<BinaryConditionalOperator>(E)) { |
3748 | 8 | Visit(BCO->getCond()); |
3749 | 8 | HandleValue(BCO->getFalseExpr(), AddressOf); |
3750 | 8 | return; |
3751 | 8 | } |
3752 | | |
3753 | 10.2k | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { |
3754 | 8 | HandleValue(OVE->getSourceExpr(), AddressOf); |
3755 | 8 | return; |
3756 | 8 | } |
3757 | | |
3758 | 10.2k | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { |
3759 | 37 | switch (BO->getOpcode()) { |
3760 | 18 | default: |
3761 | 18 | break; |
3762 | 18 | case(BO_PtrMemD): |
3763 | 4 | case(BO_PtrMemI): |
3764 | 4 | HandleValue(BO->getLHS(), AddressOf); |
3765 | 4 | Visit(BO->getRHS()); |
3766 | 4 | return; |
3767 | 15 | case(BO_Comma): |
3768 | 15 | Visit(BO->getLHS()); |
3769 | 15 | HandleValue(BO->getRHS(), AddressOf); |
3770 | 15 | return; |
3771 | 37 | } |
3772 | 37 | } |
3773 | | |
3774 | 10.2k | Visit(E); |
3775 | 10.2k | } |
3776 | | |
3777 | 348 | void CheckInitListExpr(InitListExpr *ILE) { |
3778 | 348 | InitFieldIndex.push_back(0); |
3779 | 1.49k | for (auto Child : ILE->children()) { |
3780 | 1.49k | if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { |
3781 | 91 | CheckInitListExpr(SubList); |
3782 | 1.40k | } else { |
3783 | 1.40k | Visit(Child); |
3784 | 1.40k | } |
3785 | 1.49k | ++InitFieldIndex.back(); |
3786 | 1.49k | } |
3787 | 348 | InitFieldIndex.pop_back(); |
3788 | 348 | } |
3789 | | |
3790 | | void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, |
3791 | 34.1k | FieldDecl *Field, const Type *BaseClass) { |
3792 | | // Remove Decls that may have been initialized in the previous |
3793 | | // initializer. |
3794 | 34.1k | for (ValueDecl* VD : DeclsToRemove) |
3795 | 9 | Decls.erase(VD); |
3796 | 34.1k | DeclsToRemove.clear(); |
3797 | | |
3798 | 34.1k | Constructor = FieldConstructor; |
3799 | 34.1k | InitListExpr *ILE = dyn_cast<InitListExpr>(E); |
3800 | | |
3801 | 34.1k | if (ILE && Field284 ) { |
3802 | 257 | InitList = true; |
3803 | 257 | InitListFieldDecl = Field; |
3804 | 257 | InitFieldIndex.clear(); |
3805 | 257 | CheckInitListExpr(ILE); |
3806 | 33.8k | } else { |
3807 | 33.8k | InitList = false; |
3808 | 33.8k | Visit(E); |
3809 | 33.8k | } |
3810 | | |
3811 | 34.1k | if (Field) |
3812 | 25.6k | Decls.erase(Field); |
3813 | 34.1k | if (BaseClass) |
3814 | 8.33k | BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); |
3815 | 34.1k | } |
3816 | | |
3817 | 186 | void VisitMemberExpr(MemberExpr *ME) { |
3818 | | // All uses of unbounded reference fields will warn. |
3819 | 186 | HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); |
3820 | 186 | } |
3821 | | |
3822 | 18.4k | void VisitImplicitCastExpr(ImplicitCastExpr *E) { |
3823 | 18.4k | if (E->getCastKind() == CK_LValueToRValue) { |
3824 | 15.0k | HandleValue(E->getSubExpr(), false /*AddressOf*/); |
3825 | 15.0k | return; |
3826 | 15.0k | } |
3827 | | |
3828 | 3.40k | Inherited::VisitImplicitCastExpr(E); |
3829 | 3.40k | } |
3830 | | |
3831 | 12.0k | void VisitCXXConstructExpr(CXXConstructExpr *E) { |
3832 | 12.0k | if (E->getConstructor()->isCopyConstructor()) { |
3833 | 341 | Expr *ArgExpr = E->getArg(0); |
3834 | 341 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) |
3835 | 3 | if (ILE->getNumInits() == 1) |
3836 | 3 | ArgExpr = ILE->getInit(0); |
3837 | 341 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) |
3838 | 279 | if (ICE->getCastKind() == CK_NoOp) |
3839 | 256 | ArgExpr = ICE->getSubExpr(); |
3840 | 341 | HandleValue(ArgExpr, false /*AddressOf*/); |
3841 | 341 | return; |
3842 | 341 | } |
3843 | 11.7k | Inherited::VisitCXXConstructExpr(E); |
3844 | 11.7k | } |
3845 | | |
3846 | 97 | void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { |
3847 | 97 | Expr *Callee = E->getCallee(); |
3848 | 97 | if (isa<MemberExpr>(Callee)) { |
3849 | 97 | HandleValue(Callee, false /*AddressOf*/); |
3850 | 97 | for (auto Arg : E->arguments()) |
3851 | 3 | Visit(Arg); |
3852 | 97 | return; |
3853 | 97 | } |
3854 | | |
3855 | 0 | Inherited::VisitCXXMemberCallExpr(E); |
3856 | 0 | } |
3857 | | |
3858 | 262 | void VisitCallExpr(CallExpr *E) { |
3859 | | // Treat std::move as a use. |
3860 | 262 | if (E->isCallToStdMove()) { |
3861 | 36 | HandleValue(E->getArg(0), /*AddressOf=*/false); |
3862 | 36 | return; |
3863 | 36 | } |
3864 | | |
3865 | 226 | Inherited::VisitCallExpr(E); |
3866 | 226 | } |
3867 | | |
3868 | 53 | void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { |
3869 | 53 | Expr *Callee = E->getCallee(); |
3870 | | |
3871 | 53 | if (isa<UnresolvedLookupExpr>(Callee)) |
3872 | 0 | return Inherited::VisitCXXOperatorCallExpr(E); |
3873 | | |
3874 | 53 | Visit(Callee); |
3875 | 53 | for (auto Arg : E->arguments()) |
3876 | 89 | HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); |
3877 | 53 | } |
3878 | | |
3879 | 1.88k | void VisitBinaryOperator(BinaryOperator *E) { |
3880 | | // If a field assignment is detected, remove the field from the |
3881 | | // uninitiailized field set. |
3882 | 1.88k | if (E->getOpcode() == BO_Assign) |
3883 | 18 | if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) |
3884 | 17 | if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) |
3885 | 17 | if (!FD->getType()->isReferenceType()) |
3886 | 16 | DeclsToRemove.push_back(FD); |
3887 | | |
3888 | 1.88k | if (E->isCompoundAssignmentOp()) { |
3889 | 3 | HandleValue(E->getLHS(), false /*AddressOf*/); |
3890 | 3 | Visit(E->getRHS()); |
3891 | 3 | return; |
3892 | 3 | } |
3893 | | |
3894 | 1.87k | Inherited::VisitBinaryOperator(E); |
3895 | 1.87k | } |
3896 | | |
3897 | 191 | void VisitUnaryOperator(UnaryOperator *E) { |
3898 | 191 | if (E->isIncrementDecrementOp()) { |
3899 | 38 | HandleValue(E->getSubExpr(), false /*AddressOf*/); |
3900 | 38 | return; |
3901 | 38 | } |
3902 | 153 | if (E->getOpcode() == UO_AddrOf) { |
3903 | 118 | if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { |
3904 | 56 | HandleValue(ME->getBase(), true /*AddressOf*/); |
3905 | 56 | return; |
3906 | 56 | } |
3907 | 118 | } |
3908 | | |
3909 | 97 | Inherited::VisitUnaryOperator(E); |
3910 | 97 | } |
3911 | | }; |
3912 | | |
3913 | | // Diagnose value-uses of fields to initialize themselves, e.g. |
3914 | | // foo(foo) |
3915 | | // where foo is not also a parameter to the constructor. |
3916 | | // Also diagnose across field uninitialized use such as |
3917 | | // x(y), y(x) |
3918 | | // TODO: implement -Wuninitialized and fold this into that framework. |
3919 | | static void DiagnoseUninitializedFields( |
3920 | 285k | Sema &SemaRef, const CXXConstructorDecl *Constructor) { |
3921 | | |
3922 | 285k | if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, |
3923 | 285k | Constructor->getLocation())) { |
3924 | 229k | return; |
3925 | 229k | } |
3926 | | |
3927 | 55.2k | if (Constructor->isInvalidDecl()) |
3928 | 59 | return; |
3929 | | |
3930 | 55.2k | const CXXRecordDecl *RD = Constructor->getParent(); |
3931 | | |
3932 | 55.2k | if (RD->isDependentContext()) |
3933 | 5.23k | return; |
3934 | | |
3935 | | // Holds fields that are uninitialized. |
3936 | 49.9k | llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; |
3937 | | |
3938 | | // At the beginning, all fields are uninitialized. |
3939 | 323k | for (auto *I : RD->decls()) { |
3940 | 323k | if (auto *FD = dyn_cast<FieldDecl>(I)) { |
3941 | 43.8k | UninitializedFields.insert(FD); |
3942 | 279k | } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { |
3943 | 681 | UninitializedFields.insert(IFD->getAnonField()); |
3944 | 681 | } |
3945 | 323k | } |
3946 | | |
3947 | 49.9k | llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; |
3948 | 49.9k | for (auto I : RD->bases()) |
3949 | 7.92k | UninitializedBaseClasses.insert(I.getType().getCanonicalType()); |
3950 | | |
3951 | 49.9k | if (UninitializedFields.empty() && UninitializedBaseClasses.empty()19.2k ) |
3952 | 14.3k | return; |
3953 | | |
3954 | 35.6k | UninitializedFieldVisitor UninitializedChecker(SemaRef, |
3955 | 35.6k | UninitializedFields, |
3956 | 35.6k | UninitializedBaseClasses); |
3957 | | |
3958 | 35.6k | for (const auto *FieldInit : Constructor->inits()) { |
3959 | 34.1k | if (UninitializedFields.empty() && UninitializedBaseClasses.empty()5.75k ) |
3960 | 10 | break; |
3961 | | |
3962 | 34.1k | Expr *InitExpr = FieldInit->getInit(); |
3963 | 34.1k | if (!InitExpr) |
3964 | 0 | continue; |
3965 | | |
3966 | 34.1k | if (CXXDefaultInitExpr *Default = |
3967 | 34.1k | dyn_cast<CXXDefaultInitExpr>(InitExpr)) { |
3968 | 1.33k | InitExpr = Default->getExpr(); |
3969 | 1.33k | if (!InitExpr) |
3970 | 0 | continue; |
3971 | | // In class initializers will point to the constructor. |
3972 | 1.33k | UninitializedChecker.CheckInitializer(InitExpr, Constructor, |
3973 | 1.33k | FieldInit->getAnyMember(), |
3974 | 1.33k | FieldInit->getBaseClass()); |
3975 | 32.8k | } else { |
3976 | 32.8k | UninitializedChecker.CheckInitializer(InitExpr, nullptr, |
3977 | 32.8k | FieldInit->getAnyMember(), |
3978 | 32.8k | FieldInit->getBaseClass()); |
3979 | 32.8k | } |
3980 | 34.1k | } |
3981 | 35.6k | } |
3982 | | } // namespace |
3983 | | |
3984 | | /// Enter a new C++ default initializer scope. After calling this, the |
3985 | | /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if |
3986 | | /// parsing or instantiating the initializer failed. |
3987 | 5.81k | void Sema::ActOnStartCXXInClassMemberInitializer() { |
3988 | | // Create a synthetic function scope to represent the call to the constructor |
3989 | | // that notionally surrounds a use of this initializer. |
3990 | 5.81k | PushFunctionScope(); |
3991 | 5.81k | } |
3992 | | |
3993 | 611 | void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { |
3994 | 611 | if (!D.isFunctionDeclarator()) |
3995 | 8 | return; |
3996 | 603 | auto &FTI = D.getFunctionTypeInfo(); |
3997 | 603 | if (!FTI.Params) |
3998 | 317 | return; |
3999 | 286 | for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, |
4000 | 398 | FTI.NumParams)) { |
4001 | 398 | auto *ParamDecl = cast<NamedDecl>(Param.Param); |
4002 | 398 | if (ParamDecl->getDeclName()) |
4003 | 340 | PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); |
4004 | 398 | } |
4005 | 286 | } |
4006 | | |
4007 | 611 | ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { |
4008 | 611 | return ActOnRequiresClause(ConstraintExpr); |
4009 | 611 | } |
4010 | | |
4011 | 2.07k | ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { |
4012 | 2.07k | if (ConstraintExpr.isInvalid()) |
4013 | 20 | return ExprError(); |
4014 | | |
4015 | 2.05k | ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr); |
4016 | 2.05k | if (ConstraintExpr.isInvalid()) |
4017 | 0 | return ExprError(); |
4018 | | |
4019 | 2.05k | if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(), |
4020 | 2.05k | UPPC_RequiresClause)) |
4021 | 2 | return ExprError(); |
4022 | | |
4023 | 2.04k | return ConstraintExpr; |
4024 | 2.05k | } |
4025 | | |
4026 | | /// This is invoked after parsing an in-class initializer for a |
4027 | | /// non-static C++ class member, and after instantiating an in-class initializer |
4028 | | /// in a class template. Such actions are deferred until the class is complete. |
4029 | | void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, |
4030 | | SourceLocation InitLoc, |
4031 | 5.81k | Expr *InitExpr) { |
4032 | | // Pop the notional constructor scope we created earlier. |
4033 | 5.81k | PopFunctionScopeInfo(nullptr, D); |
4034 | | |
4035 | 5.81k | FieldDecl *FD = dyn_cast<FieldDecl>(D); |
4036 | 5.81k | assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && |
4037 | 5.81k | "must set init style when field is created"); |
4038 | | |
4039 | 5.81k | if (!InitExpr) { |
4040 | 29 | D->setInvalidDecl(); |
4041 | 29 | if (FD) |
4042 | 28 | FD->removeInClassInitializer(); |
4043 | 29 | return; |
4044 | 29 | } |
4045 | | |
4046 | 5.78k | if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { |
4047 | 1 | FD->setInvalidDecl(); |
4048 | 1 | FD->removeInClassInitializer(); |
4049 | 1 | return; |
4050 | 1 | } |
4051 | | |
4052 | 5.78k | ExprResult Init = InitExpr; |
4053 | 5.78k | if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()4.24k ) { |
4054 | 4.15k | InitializedEntity Entity = |
4055 | 4.15k | InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); |
4056 | 4.15k | InitializationKind Kind = |
4057 | 4.15k | FD->getInClassInitStyle() == ICIS_ListInit |
4058 | 4.15k | ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), |
4059 | 151 | InitExpr->getBeginLoc(), |
4060 | 151 | InitExpr->getEndLoc()) |
4061 | 4.15k | : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc)4.00k ; |
4062 | 4.15k | InitializationSequence Seq(*this, Entity, Kind, InitExpr); |
4063 | 4.15k | Init = Seq.Perform(*this, Entity, Kind, InitExpr); |
4064 | 4.15k | if (Init.isInvalid()) { |
4065 | 34 | FD->setInvalidDecl(); |
4066 | 34 | return; |
4067 | 34 | } |
4068 | 4.15k | } |
4069 | | |
4070 | | // C++11 [class.base.init]p7: |
4071 | | // The initialization of each base and member constitutes a |
4072 | | // full-expression. |
4073 | 5.74k | Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); |
4074 | 5.74k | if (Init.isInvalid()) { |
4075 | 0 | FD->setInvalidDecl(); |
4076 | 0 | return; |
4077 | 0 | } |
4078 | | |
4079 | 5.74k | InitExpr = Init.get(); |
4080 | | |
4081 | 5.74k | FD->setInClassInitializer(InitExpr); |
4082 | 5.74k | } |
4083 | | |
4084 | | /// Find the direct and/or virtual base specifiers that |
4085 | | /// correspond to the given base type, for use in base initialization |
4086 | | /// within a constructor. |
4087 | | static bool FindBaseInitializer(Sema &SemaRef, |
4088 | | CXXRecordDecl *ClassDecl, |
4089 | | QualType BaseType, |
4090 | | const CXXBaseSpecifier *&DirectBaseSpec, |
4091 | 19.3k | const CXXBaseSpecifier *&VirtualBaseSpec) { |
4092 | | // First, check for a direct base class. |
4093 | 19.3k | DirectBaseSpec = nullptr; |
4094 | 23.2k | for (const auto &Base : ClassDecl->bases()) { |
4095 | 23.2k | if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { |
4096 | | // We found a direct base of this type. That's what we're |
4097 | | // initializing. |
4098 | 19.2k | DirectBaseSpec = &Base; |
4099 | 19.2k | break; |
4100 | 19.2k | } |
4101 | 23.2k | } |
4102 | | |
4103 | | // Check for a virtual base class. |
4104 | | // FIXME: We might be able to short-circuit this if we know in advance that |
4105 | | // there are no virtual bases. |
4106 | 19.3k | VirtualBaseSpec = nullptr; |
4107 | 19.3k | if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()19.2k ) { |
4108 | | // We haven't found a base yet; search the class hierarchy for a |
4109 | | // virtual base class. |
4110 | 19.2k | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, |
4111 | 19.2k | /*DetectVirtual=*/false); |
4112 | 19.2k | if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), |
4113 | 19.2k | SemaRef.Context.getTypeDeclType(ClassDecl), |
4114 | 19.2k | BaseType, Paths)) { |
4115 | 19.2k | for (CXXBasePaths::paths_iterator Path = Paths.begin(); |
4116 | 38.4k | Path != Paths.end(); ++Path19.1k ) { |
4117 | 19.2k | if (Path->back().Base->isVirtual()) { |
4118 | 53 | VirtualBaseSpec = Path->back().Base; |
4119 | 53 | break; |
4120 | 53 | } |
4121 | 19.2k | } |
4122 | 19.2k | } |
4123 | 19.2k | } |
4124 | | |
4125 | 19.3k | return DirectBaseSpec || VirtualBaseSpec85 ; |
4126 | 19.3k | } |
4127 | | |
4128 | | /// Handle a C++ member initializer using braced-init-list syntax. |
4129 | | MemInitResult |
4130 | | Sema::ActOnMemInitializer(Decl *ConstructorD, |
4131 | | Scope *S, |
4132 | | CXXScopeSpec &SS, |
4133 | | IdentifierInfo *MemberOrBase, |
4134 | | ParsedType TemplateTypeTy, |
4135 | | const DeclSpec &DS, |
4136 | | SourceLocation IdLoc, |
4137 | | Expr *InitList, |
4138 | 665 | SourceLocation EllipsisLoc) { |
4139 | 665 | return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, |
4140 | 665 | DS, IdLoc, InitList, |
4141 | 665 | EllipsisLoc); |
4142 | 665 | } |
4143 | | |
4144 | | /// Handle a C++ member initializer using parentheses syntax. |
4145 | | MemInitResult |
4146 | | Sema::ActOnMemInitializer(Decl *ConstructorD, |
4147 | | Scope *S, |
4148 | | CXXScopeSpec &SS, |
4149 | | IdentifierInfo *MemberOrBase, |
4150 | | ParsedType TemplateTypeTy, |
4151 | | const DeclSpec &DS, |
4152 | | SourceLocation IdLoc, |
4153 | | SourceLocation LParenLoc, |
4154 | | ArrayRef<Expr *> Args, |
4155 | | SourceLocation RParenLoc, |
4156 | 279k | SourceLocation EllipsisLoc) { |
4157 | 279k | Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); |
4158 | 279k | return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, |
4159 | 279k | DS, IdLoc, List, EllipsisLoc); |
4160 | 279k | } |
4161 | | |
4162 | | namespace { |
4163 | | |
4164 | | // Callback to only accept typo corrections that can be a valid C++ member |
4165 | | // initializer: either a non-static field member or a base class. |
4166 | | class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { |
4167 | | public: |
4168 | | explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) |
4169 | 83 | : ClassDecl(ClassDecl) {} |
4170 | | |
4171 | 12 | bool ValidateCandidate(const TypoCorrection &candidate) override { |
4172 | 12 | if (NamedDecl *ND = candidate.getCorrectionDecl()) { |
4173 | 8 | if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) |
4174 | 2 | return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); |
4175 | 6 | return isa<TypeDecl>(ND); |
4176 | 8 | } |
4177 | 4 | return false; |
4178 | 12 | } |
4179 | | |
4180 | 29 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
4181 | 29 | return std::make_unique<MemInitializerValidatorCCC>(*this); |
4182 | 29 | } |
4183 | | |
4184 | | private: |
4185 | | CXXRecordDecl *ClassDecl; |
4186 | | }; |
4187 | | |
4188 | | } |
4189 | | |
4190 | | ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, |
4191 | | CXXScopeSpec &SS, |
4192 | | ParsedType TemplateTypeTy, |
4193 | 279k | IdentifierInfo *MemberOrBase) { |
4194 | 279k | if (SS.getScopeRep() || TemplateTypeTy278k ) |
4195 | 7.01k | return nullptr; |
4196 | 272k | for (auto *D : ClassDecl->lookup(MemberOrBase)) |
4197 | 259k | if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)10.0k ) |
4198 | 249k | return cast<ValueDecl>(D); |
4199 | 23.1k | return nullptr; |
4200 | 272k | } |
4201 | | |
4202 | | /// Handle a C++ member initializer. |
4203 | | MemInitResult |
4204 | | Sema::BuildMemInitializer(Decl *ConstructorD, |
4205 | | Scope *S, |
4206 | | CXXScopeSpec &SS, |
4207 | | IdentifierInfo *MemberOrBase, |
4208 | | ParsedType TemplateTypeTy, |
4209 | | const DeclSpec &DS, |
4210 | | SourceLocation IdLoc, |
4211 | | Expr *Init, |
4212 | 279k | SourceLocation EllipsisLoc) { |
4213 | 279k | ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr, |
4214 | 279k | /*RecoverUncorrectedTypos=*/true); |
4215 | 279k | if (!Res.isUsable()) |
4216 | 4 | return true; |
4217 | 279k | Init = Res.get(); |
4218 | | |
4219 | 279k | if (!ConstructorD) |
4220 | 0 | return true; |
4221 | | |
4222 | 279k | AdjustDeclIfTemplate(ConstructorD); |
4223 | | |
4224 | 279k | CXXConstructorDecl *Constructor |
4225 | 279k | = dyn_cast<CXXConstructorDecl>(ConstructorD); |
4226 | 279k | if (!Constructor) { |
4227 | | // The user wrote a constructor initializer on a function that is |
4228 | | // not a C++ constructor. Ignore the error for now, because we may |
4229 | | // have more member initializers coming; we'll diagnose it just |
4230 | | // once in ActOnMemInitializers. |
4231 | 5 | return true; |
4232 | 5 | } |
4233 | | |
4234 | 279k | CXXRecordDecl *ClassDecl = Constructor->getParent(); |
4235 | | |
4236 | | // C++ [class.base.init]p2: |
4237 | | // Names in a mem-initializer-id are looked up in the scope of the |
4238 | | // constructor's class and, if not found in that scope, are looked |
4239 | | // up in the scope containing the constructor's definition. |
4240 | | // [Note: if the constructor's class contains a member with the |
4241 | | // same name as a direct or virtual base class of the class, a |
4242 | | // mem-initializer-id naming the member or base class and composed |
4243 | | // of a single identifier refers to the class member. A |
4244 | | // mem-initializer-id for the hidden base class may be specified |
4245 | | // using a qualified name. ] |
4246 | | |
4247 | | // Look for a member, first. |
4248 | 279k | if (ValueDecl *Member = tryLookupCtorInitMemberDecl( |
4249 | 279k | ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { |
4250 | 249k | if (EllipsisLoc.isValid()) |
4251 | 2 | Diag(EllipsisLoc, diag::err_pack_expansion_member_init) |
4252 | 2 | << MemberOrBase |
4253 | 2 | << SourceRange(IdLoc, Init->getSourceRange().getEnd()); |
4254 | | |
4255 | 249k | return BuildMemberInitializer(Member, Init, IdLoc); |
4256 | 249k | } |
4257 | | // It didn't name a member, so see if it names a class. |
4258 | 30.2k | QualType BaseType; |
4259 | 30.2k | TypeSourceInfo *TInfo = nullptr; |
4260 | | |
4261 | 30.2k | if (TemplateTypeTy) { |
4262 | 5.34k | BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); |
4263 | 5.34k | if (BaseType.isNull()) |
4264 | 0 | return true; |
4265 | 24.8k | } else if (DS.getTypeSpecType() == TST_decltype) { |
4266 | 4 | BaseType = BuildDecltypeType(DS.getRepAsExpr()); |
4267 | 24.8k | } else if (DS.getTypeSpecType() == TST_decltype_auto) { |
4268 | 6 | Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); |
4269 | 6 | return true; |
4270 | 24.8k | } else { |
4271 | 24.8k | LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); |
4272 | 24.8k | LookupParsedName(R, S, &SS); |
4273 | | |
4274 | 24.8k | TypeDecl *TyD = R.getAsSingle<TypeDecl>(); |
4275 | 24.8k | if (!TyD) { |
4276 | 83 | if (R.isAmbiguous()) return true0 ; |
4277 | | |
4278 | | // We don't want access-control diagnostics here. |
4279 | 83 | R.suppressDiagnostics(); |
4280 | | |
4281 | 83 | if (SS.isSet() && isDependentScopeSpecifier(SS)30 ) { |
4282 | 24 | bool NotUnknownSpecialization = false; |
4283 | 24 | DeclContext *DC = computeDeclContext(SS, false); |
4284 | 24 | if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) |
4285 | 0 | NotUnknownSpecialization = !Record->hasAnyDependentBases(); |
4286 | | |
4287 | 24 | if (!NotUnknownSpecialization) { |
4288 | | // When the scope specifier can refer to a member of an unknown |
4289 | | // specialization, we take it as a type name. |
4290 | 24 | BaseType = CheckTypenameType(ETK_None, SourceLocation(), |
4291 | 24 | SS.getWithLocInContext(Context), |
4292 | 24 | *MemberOrBase, IdLoc); |
4293 | 24 | if (BaseType.isNull()) |
4294 | 0 | return true; |
4295 | | |
4296 | 24 | TInfo = Context.CreateTypeSourceInfo(BaseType); |
4297 | 24 | DependentNameTypeLoc TL = |
4298 | 24 | TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); |
4299 | 24 | if (!TL.isNull()) { |
4300 | 24 | TL.setNameLoc(IdLoc); |
4301 | 24 | TL.setElaboratedKeywordLoc(SourceLocation()); |
4302 | 24 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); |
4303 | 24 | } |
4304 | | |
4305 | 24 | R.clear(); |
4306 | 24 | R.setLookupName(MemberOrBase); |
4307 | 24 | } |
4308 | 24 | } |
4309 | | |
4310 | 83 | if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus2016 ) { |
4311 | 8 | auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>(); |
4312 | 8 | if (UnqualifiedBase) { |
4313 | 8 | Diag(IdLoc, diag::ext_unqualified_base_class) |
4314 | 8 | << SourceRange(IdLoc, Init->getSourceRange().getEnd()); |
4315 | 8 | BaseType = UnqualifiedBase->getInjectedClassNameSpecialization(); |
4316 | 8 | } |
4317 | 8 | } |
4318 | | |
4319 | | // If no results were found, try to correct typos. |
4320 | 83 | TypoCorrection Corr; |
4321 | 83 | MemInitializerValidatorCCC CCC(ClassDecl); |
4322 | 83 | if (R.empty() && BaseType.isNull()60 && |
4323 | 83 | (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, |
4324 | 36 | CCC, CTK_ErrorRecovery, ClassDecl))) { |
4325 | 6 | if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { |
4326 | | // We have found a non-static data member with a similar |
4327 | | // name to what was typed; complain and initialize that |
4328 | | // member. |
4329 | 2 | diagnoseTypo(Corr, |
4330 | 2 | PDiag(diag::err_mem_init_not_member_or_class_suggest) |
4331 | 2 | << MemberOrBase << true); |
4332 | 2 | return BuildMemberInitializer(Member, Init, IdLoc); |
4333 | 4 | } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { |
4334 | 4 | const CXXBaseSpecifier *DirectBaseSpec; |
4335 | 4 | const CXXBaseSpecifier *VirtualBaseSpec; |
4336 | 4 | if (FindBaseInitializer(*this, ClassDecl, |
4337 | 4 | Context.getTypeDeclType(Type), |
4338 | 4 | DirectBaseSpec, VirtualBaseSpec)) { |
4339 | | // We have found a direct or virtual base class with a |
4340 | | // similar name to what was typed; complain and initialize |
4341 | | // that base class. |
4342 | 4 | diagnoseTypo(Corr, |
4343 | 4 | PDiag(diag::err_mem_init_not_member_or_class_suggest) |
4344 | 4 | << MemberOrBase << false, |
4345 | 4 | PDiag() /*Suppress note, we provide our own.*/); |
4346 | | |
4347 | 4 | const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec |
4348 | 4 | : VirtualBaseSpec0 ; |
4349 | 4 | Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) |
4350 | 4 | << BaseSpec->getType() << BaseSpec->getSourceRange(); |
4351 | | |
4352 | 4 | TyD = Type; |
4353 | 4 | } |
4354 | 4 | } |
4355 | 6 | } |
4356 | | |
4357 | 81 | if (!TyD && BaseType.isNull()77 ) { |
4358 | 45 | Diag(IdLoc, diag::err_mem_init_not_member_or_class) |
4359 | 45 | << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); |
4360 | 45 | return true; |
4361 | 45 | } |
4362 | 81 | } |
4363 | | |
4364 | 24.8k | if (BaseType.isNull()) { |
4365 | 24.7k | BaseType = Context.getTypeDeclType(TyD); |
4366 | 24.7k | MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); |
4367 | 24.7k | if (SS.isSet()) { |
4368 | 1.64k | BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), |
4369 | 1.64k | BaseType); |
4370 | 1.64k | TInfo = Context.CreateTypeSourceInfo(BaseType); |
4371 | 1.64k | ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); |
4372 | 1.64k | TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); |
4373 | 1.64k | TL.setElaboratedKeywordLoc(SourceLocation()); |
4374 | 1.64k | TL.setQualifierLoc(SS.getWithLocInContext(Context)); |
4375 | 1.64k | } |
4376 | 24.7k | } |
4377 | 24.8k | } |
4378 | | |
4379 | 30.1k | if (!TInfo) |
4380 | 23.1k | TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); |
4381 | | |
4382 | 30.1k | return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); |
4383 | 30.2k | } |
4384 | | |
4385 | | MemInitResult |
4386 | | Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, |
4387 | 276k | SourceLocation IdLoc) { |
4388 | 276k | FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); |
4389 | 276k | IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); |
4390 | 276k | assert((DirectMember || IndirectMember) && |
4391 | 276k | "Member must be a FieldDecl or IndirectFieldDecl"); |
4392 | | |
4393 | 276k | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) |
4394 | 1 | return true; |
4395 | | |
4396 | 276k | if (Member->isInvalidDecl()) |
4397 | 4 | return true; |
4398 | | |
4399 | 276k | MultiExprArg Args; |
4400 | 276k | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { |
4401 | 275k | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); |
4402 | 275k | } else if (InitListExpr *1.82k InitList1.82k = dyn_cast<InitListExpr>(Init)) { |
4403 | 760 | Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); |
4404 | 1.06k | } else { |
4405 | | // Template instantiation doesn't reconstruct ParenListExprs for us. |
4406 | 1.06k | Args = Init; |
4407 | 1.06k | } |
4408 | | |
4409 | 276k | SourceRange InitRange = Init->getSourceRange(); |
4410 | | |
4411 | 276k | if (Member->getType()->isDependentType() || Init->isTypeDependent()79.4k ) { |
4412 | | // Can't check initialization for a member of dependent type or when |
4413 | | // any of the arguments are type-dependent expressions. |
4414 | 208k | DiscardCleanupsInEvaluationContext(); |
4415 | 208k | } else { |
4416 | 68.6k | bool InitList = false; |
4417 | 68.6k | if (isa<InitListExpr>(Init)) { |
4418 | 444 | InitList = true; |
4419 | 444 | Args = Init; |
4420 | 444 | } |
4421 | | |
4422 | | // Initialize the member. |
4423 | 68.6k | InitializedEntity MemberEntity = |
4424 | 68.6k | DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)68.3k |
4425 | 68.6k | : InitializedEntity::InitializeMember(IndirectMember, |
4426 | 277 | nullptr); |
4427 | 68.6k | InitializationKind Kind = |
4428 | 68.6k | InitList ? InitializationKind::CreateDirectList( |
4429 | 444 | IdLoc, Init->getBeginLoc(), Init->getEndLoc()) |
4430 | 68.6k | : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), |
4431 | 68.1k | InitRange.getEnd()); |
4432 | | |
4433 | 68.6k | InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); |
4434 | 68.6k | ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, |
4435 | 68.6k | nullptr); |
4436 | 68.6k | if (!MemberInit.isInvalid()) { |
4437 | | // C++11 [class.base.init]p7: |
4438 | | // The initialization of each base and member constitutes a |
4439 | | // full-expression. |
4440 | 68.6k | MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), |
4441 | 68.6k | /*DiscardedValue*/ false); |
4442 | 68.6k | } |
4443 | | |
4444 | 68.6k | if (MemberInit.isInvalid()) { |
4445 | | // Args were sensible expressions but we couldn't initialize the member |
4446 | | // from them. Preserve them in a RecoveryExpr instead. |
4447 | 41 | Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, |
4448 | 41 | Member->getType()) |
4449 | 41 | .get(); |
4450 | 41 | if (!Init) |
4451 | 1 | return true; |
4452 | 68.6k | } else { |
4453 | 68.6k | Init = MemberInit.get(); |
4454 | 68.6k | } |
4455 | 68.6k | } |
4456 | | |
4457 | 276k | if (DirectMember) { |
4458 | 276k | return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, |
4459 | 276k | InitRange.getBegin(), Init, |
4460 | 276k | InitRange.getEnd()); |
4461 | 276k | } else { |
4462 | 313 | return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, |
4463 | 313 | InitRange.getBegin(), Init, |
4464 | 313 | InitRange.getEnd()); |
4465 | 313 | } |
4466 | 276k | } |
4467 | | |
4468 | | MemInitResult |
4469 | | Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, |
4470 | 545 | CXXRecordDecl *ClassDecl) { |
4471 | 545 | SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); |
4472 | 545 | if (!LangOpts.CPlusPlus11) |
4473 | 1 | return Diag(NameLoc, diag::err_delegating_ctor) |
4474 | 1 | << TInfo->getTypeLoc().getLocalSourceRange(); |
4475 | 544 | Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); |
4476 | | |
4477 | 544 | bool InitList = true; |
4478 | 544 | MultiExprArg Args = Init; |
4479 | 544 | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { |
4480 | 544 | InitList = false; |
4481 | 544 | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); |
4482 | 544 | } |
4483 | | |
4484 | 544 | SourceRange InitRange = Init->getSourceRange(); |
4485 | | // Initialize the object. |
4486 | 544 | InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( |
4487 | 544 | QualType(ClassDecl->getTypeForDecl(), 0)); |
4488 | 544 | InitializationKind Kind = |
4489 | 544 | InitList ? InitializationKind::CreateDirectList( |
4490 | 0 | NameLoc, Init->getBeginLoc(), Init->getEndLoc()) |
4491 | 544 | : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), |
4492 | 544 | InitRange.getEnd()); |
4493 | 544 | InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); |
4494 | 544 | ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, |
4495 | 544 | Args, nullptr); |
4496 | 544 | if (!DelegationInit.isInvalid()) { |
4497 | 541 | assert((DelegationInit.get()->containsErrors() || |
4498 | 541 | cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) && |
4499 | 541 | "Delegating constructor with no target?"); |
4500 | | |
4501 | | // C++11 [class.base.init]p7: |
4502 | | // The initialization of each base and member constitutes a |
4503 | | // full-expression. |
4504 | 0 | DelegationInit = ActOnFinishFullExpr( |
4505 | 541 | DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); |
4506 | 541 | } |
4507 | | |
4508 | 544 | if (DelegationInit.isInvalid()) { |
4509 | 3 | DelegationInit = |
4510 | 3 | CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, |
4511 | 3 | QualType(ClassDecl->getTypeForDecl(), 0)); |
4512 | 3 | if (DelegationInit.isInvalid()) |
4513 | 1 | return true; |
4514 | 541 | } else { |
4515 | | // If we are in a dependent context, template instantiation will |
4516 | | // perform this type-checking again. Just save the arguments that we |
4517 | | // received in a ParenListExpr. |
4518 | | // FIXME: This isn't quite ideal, since our ASTs don't capture all |
4519 | | // of the information that we have about the base |
4520 | | // initializer. However, deconstructing the ASTs is a dicey process, |
4521 | | // and this approach is far more likely to get the corner cases right. |
4522 | 541 | if (CurContext->isDependentContext()) |
4523 | 2 | DelegationInit = Init; |
4524 | 541 | } |
4525 | | |
4526 | 543 | return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), |
4527 | 543 | DelegationInit.getAs<Expr>(), |
4528 | 543 | InitRange.getEnd()); |
4529 | 544 | } |
4530 | | |
4531 | | MemInitResult |
4532 | | Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, |
4533 | | Expr *Init, CXXRecordDecl *ClassDecl, |
4534 | 39.1k | SourceLocation EllipsisLoc) { |
4535 | 39.1k | SourceLocation BaseLoc |
4536 | 39.1k | = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); |
4537 | | |
4538 | 39.1k | if (!BaseType->isDependentType() && !BaseType->isRecordType()19.8k ) |
4539 | 6 | return Diag(BaseLoc, diag::err_base_init_does_not_name_class) |
4540 | 6 | << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); |
4541 | | |
4542 | | // C++ [class.base.init]p2: |
4543 | | // [...] Unless the mem-initializer-id names a nonstatic data |
4544 | | // member of the constructor's class or a direct or virtual base |
4545 | | // of that class, the mem-initializer is ill-formed. A |
4546 | | // mem-initializer-list can initialize a base class using any |
4547 | | // name that denotes that base class type. |
4548 | | |
4549 | | // We can store the initializers in "as-written" form and delay analysis until |
4550 | | // instantiation if the constructor is dependent. But not for dependent |
4551 | | // (broken) code in a non-template! SetCtorInitializers does not expect this. |
4552 | 39.1k | bool Dependent = CurContext->isDependentContext() && |
4553 | 39.1k | (20.4k BaseType->isDependentType()20.4k || Init->isTypeDependent()1.21k ); |
4554 | | |
4555 | 39.1k | SourceRange InitRange = Init->getSourceRange(); |
4556 | 39.1k | if (EllipsisLoc.isValid()) { |
4557 | | // This is a pack expansion. |
4558 | 2.75k | if (!BaseType->containsUnexpandedParameterPack()) { |
4559 | 0 | Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) |
4560 | 0 | << SourceRange(BaseLoc, InitRange.getEnd()); |
4561 | |
|
4562 | 0 | EllipsisLoc = SourceLocation(); |
4563 | 0 | } |
4564 | 36.3k | } else { |
4565 | | // Check for any unexpanded parameter packs. |
4566 | 36.3k | if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) |
4567 | 1 | return true; |
4568 | | |
4569 | 36.3k | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) |
4570 | 0 | return true; |
4571 | 36.3k | } |
4572 | | |
4573 | | // Check for direct and virtual base classes. |
4574 | 39.1k | const CXXBaseSpecifier *DirectBaseSpec = nullptr; |
4575 | 39.1k | const CXXBaseSpecifier *VirtualBaseSpec = nullptr; |
4576 | 39.1k | if (!Dependent) { |
4577 | 19.8k | if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), |
4578 | 19.8k | BaseType)) |
4579 | 543 | return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); |
4580 | | |
4581 | 19.3k | FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, |
4582 | 19.3k | VirtualBaseSpec); |
4583 | | |
4584 | | // C++ [base.class.init]p2: |
4585 | | // Unless the mem-initializer-id names a nonstatic data member of the |
4586 | | // constructor's class or a direct or virtual base of that class, the |
4587 | | // mem-initializer is ill-formed. |
4588 | 19.3k | if (!DirectBaseSpec && !VirtualBaseSpec85 ) { |
4589 | | // If the class has any dependent bases, then it's possible that |
4590 | | // one of those types will resolve to the same type as |
4591 | | // BaseType. Therefore, just treat this as a dependent base |
4592 | | // class initialization. FIXME: Should we try to check the |
4593 | | // initialization anyway? It seems odd. |
4594 | 35 | if (ClassDecl->hasAnyDependentBases()) |
4595 | 20 | Dependent = true; |
4596 | 15 | else |
4597 | 15 | return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) |
4598 | 15 | << BaseType << Context.getTypeDeclType(ClassDecl) |
4599 | 15 | << BaseTInfo->getTypeLoc().getLocalSourceRange(); |
4600 | 35 | } |
4601 | 19.3k | } |
4602 | | |
4603 | 38.5k | if (Dependent) { |
4604 | 19.2k | DiscardCleanupsInEvaluationContext(); |
4605 | | |
4606 | 19.2k | return new (Context) CXXCtorInitializer(Context, BaseTInfo, |
4607 | 19.2k | /*IsVirtual=*/false, |
4608 | 19.2k | InitRange.getBegin(), Init, |
4609 | 19.2k | InitRange.getEnd(), EllipsisLoc); |
4610 | 19.2k | } |
4611 | | |
4612 | | // C++ [base.class.init]p2: |
4613 | | // If a mem-initializer-id is ambiguous because it designates both |
4614 | | // a direct non-virtual base class and an inherited virtual base |
4615 | | // class, the mem-initializer is ill-formed. |
4616 | 19.2k | if (DirectBaseSpec && VirtualBaseSpec19.2k ) |
4617 | 3 | return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) |
4618 | 3 | << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); |
4619 | | |
4620 | 19.2k | const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; |
4621 | 19.2k | if (!BaseSpec) |
4622 | 50 | BaseSpec = VirtualBaseSpec; |
4623 | | |
4624 | | // Initialize the base. |
4625 | 19.2k | bool InitList = true; |
4626 | 19.2k | MultiExprArg Args = Init; |
4627 | 19.2k | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { |
4628 | 19.2k | InitList = false; |
4629 | 19.2k | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); |
4630 | 19.2k | } |
4631 | | |
4632 | 19.2k | InitializedEntity BaseEntity = |
4633 | 19.2k | InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); |
4634 | 19.2k | InitializationKind Kind = |
4635 | 19.2k | InitList ? InitializationKind::CreateDirectList(BaseLoc)38 |
4636 | 19.2k | : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), |
4637 | 19.2k | InitRange.getEnd()); |
4638 | 19.2k | InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); |
4639 | 19.2k | ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); |
4640 | 19.2k | if (!BaseInit.isInvalid()) { |
4641 | | // C++11 [class.base.init]p7: |
4642 | | // The initialization of each base and member constitutes a |
4643 | | // full-expression. |
4644 | 19.2k | BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), |
4645 | 19.2k | /*DiscardedValue*/ false); |
4646 | 19.2k | } |
4647 | | |
4648 | 19.2k | if (BaseInit.isInvalid()) { |
4649 | 21 | BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), |
4650 | 21 | Args, BaseType); |
4651 | 21 | if (BaseInit.isInvalid()) |
4652 | 1 | return true; |
4653 | 19.2k | } else { |
4654 | | // If we are in a dependent context, template instantiation will |
4655 | | // perform this type-checking again. Just save the arguments that we |
4656 | | // received in a ParenListExpr. |
4657 | | // FIXME: This isn't quite ideal, since our ASTs don't capture all |
4658 | | // of the information that we have about the base |
4659 | | // initializer. However, deconstructing the ASTs is a dicey process, |
4660 | | // and this approach is far more likely to get the corner cases right. |
4661 | 19.2k | if (CurContext->isDependentContext()) |
4662 | 1.18k | BaseInit = Init; |
4663 | 19.2k | } |
4664 | | |
4665 | 19.2k | return new (Context) CXXCtorInitializer(Context, BaseTInfo, |
4666 | 19.2k | BaseSpec->isVirtual(), |
4667 | 19.2k | InitRange.getBegin(), |
4668 | 19.2k | BaseInit.getAs<Expr>(), |
4669 | 19.2k | InitRange.getEnd(), EllipsisLoc); |
4670 | 19.2k | } |
4671 | | |
4672 | | // Create a static_cast\<T&&>(expr). |
4673 | 30.2k | static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { |
4674 | 30.2k | if (T.isNull()) T = E->getType(); |
4675 | 30.2k | QualType TargetType = SemaRef.BuildReferenceType( |
4676 | 30.2k | T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); |
4677 | 30.2k | SourceLocation ExprLoc = E->getBeginLoc(); |
4678 | 30.2k | TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( |
4679 | 30.2k | TargetType, ExprLoc); |
4680 | | |
4681 | 30.2k | return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, |
4682 | 30.2k | SourceRange(ExprLoc, ExprLoc), |
4683 | 30.2k | E->getSourceRange()).get(); |
4684 | 30.2k | } |
4685 | | |
4686 | | /// ImplicitInitializerKind - How an implicit base or member initializer should |
4687 | | /// initialize its base or member. |
4688 | | enum ImplicitInitializerKind { |
4689 | | IIK_Default, |
4690 | | IIK_Copy, |
4691 | | IIK_Move, |
4692 | | IIK_Inherit |
4693 | | }; |
4694 | | |
4695 | | static bool |
4696 | | BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, |
4697 | | ImplicitInitializerKind ImplicitInitKind, |
4698 | | CXXBaseSpecifier *BaseSpec, |
4699 | | bool IsInheritedVirtualBase, |
4700 | 22.4k | CXXCtorInitializer *&CXXBaseInit) { |
4701 | 22.4k | InitializedEntity InitEntity |
4702 | 22.4k | = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, |
4703 | 22.4k | IsInheritedVirtualBase); |
4704 | | |
4705 | 22.4k | ExprResult BaseInit; |
4706 | | |
4707 | 22.4k | switch (ImplicitInitKind) { |
4708 | 40 | case IIK_Inherit: |
4709 | 12.5k | case IIK_Default: { |
4710 | 12.5k | InitializationKind InitKind |
4711 | 12.5k | = InitializationKind::CreateDefault(Constructor->getLocation()); |
4712 | 12.5k | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); |
4713 | 12.5k | BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); |
4714 | 12.5k | break; |
4715 | 40 | } |
4716 | | |
4717 | 3.67k | case IIK_Move: |
4718 | 9.93k | case IIK_Copy: { |
4719 | 9.93k | bool Moving = ImplicitInitKind == IIK_Move; |
4720 | 9.93k | ParmVarDecl *Param = Constructor->getParamDecl(0); |
4721 | 9.93k | QualType ParamType = Param->getType().getNonReferenceType(); |
4722 | | |
4723 | 9.93k | Expr *CopyCtorArg = |
4724 | 9.93k | DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), |
4725 | 9.93k | SourceLocation(), Param, false, |
4726 | 9.93k | Constructor->getLocation(), ParamType, |
4727 | 9.93k | VK_LValue, nullptr); |
4728 | | |
4729 | 9.93k | SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); |
4730 | | |
4731 | | // Cast to the base class to avoid ambiguities. |
4732 | 9.93k | QualType ArgTy = |
4733 | 9.93k | SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), |
4734 | 9.93k | ParamType.getQualifiers()); |
4735 | | |
4736 | 9.93k | if (Moving) { |
4737 | 3.67k | CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); |
4738 | 3.67k | } |
4739 | | |
4740 | 9.93k | CXXCastPath BasePath; |
4741 | 9.93k | BasePath.push_back(BaseSpec); |
4742 | 9.93k | CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, |
4743 | 9.93k | CK_UncheckedDerivedToBase, |
4744 | 9.93k | Moving ? VK_XValue3.67k : VK_LValue6.25k , |
4745 | 9.93k | &BasePath).get(); |
4746 | | |
4747 | 9.93k | InitializationKind InitKind |
4748 | 9.93k | = InitializationKind::CreateDirect(Constructor->getLocation(), |
4749 | 9.93k | SourceLocation(), SourceLocation()); |
4750 | 9.93k | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); |
4751 | 9.93k | BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); |
4752 | 9.93k | break; |
4753 | 3.67k | } |
4754 | 22.4k | } |
4755 | | |
4756 | 22.4k | BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); |
4757 | 22.4k | if (BaseInit.isInvalid()) |
4758 | 21 | return true; |
4759 | | |
4760 | 22.4k | CXXBaseInit = |
4761 | 22.4k | new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, |
4762 | 22.4k | SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), |
4763 | 22.4k | SourceLocation()), |
4764 | 22.4k | BaseSpec->isVirtual(), |
4765 | 22.4k | SourceLocation(), |
4766 | 22.4k | BaseInit.getAs<Expr>(), |
4767 | 22.4k | SourceLocation(), |
4768 | 22.4k | SourceLocation()); |
4769 | | |
4770 | 22.4k | return false; |
4771 | 22.4k | } |
4772 | | |
4773 | 34.7k | static bool RefersToRValueRef(Expr *MemRef) { |
4774 | 34.7k | ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); |
4775 | 34.7k | return Referenced->getType()->isRValueReferenceType(); |
4776 | 34.7k | } |
4777 | | |
4778 | | static bool |
4779 | | BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, |
4780 | | ImplicitInitializerKind ImplicitInitKind, |
4781 | | FieldDecl *Field, IndirectFieldDecl *Indirect, |
4782 | 64.0k | CXXCtorInitializer *&CXXMemberInit) { |
4783 | 64.0k | if (Field->isInvalidDecl()) |
4784 | 0 | return true; |
4785 | | |
4786 | 64.0k | SourceLocation Loc = Constructor->getLocation(); |
4787 | | |
4788 | 64.0k | if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move53.0k ) { |
4789 | 34.7k | bool Moving = ImplicitInitKind == IIK_Move; |
4790 | 34.7k | ParmVarDecl *Param = Constructor->getParamDecl(0); |
4791 | 34.7k | QualType ParamType = Param->getType().getNonReferenceType(); |
4792 | | |
4793 | | // Suppress copying zero-width bitfields. |
4794 | 34.7k | if (Field->isZeroLengthBitField(SemaRef.Context)) |
4795 | 0 | return false; |
4796 | | |
4797 | 34.7k | Expr *MemberExprBase = |
4798 | 34.7k | DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), |
4799 | 34.7k | SourceLocation(), Param, false, |
4800 | 34.7k | Loc, ParamType, VK_LValue, nullptr); |
4801 | | |
4802 | 34.7k | SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); |
4803 | | |
4804 | 34.7k | if (Moving) { |
4805 | 23.7k | MemberExprBase = CastForMoving(SemaRef, MemberExprBase); |
4806 | 23.7k | } |
4807 | | |
4808 | | // Build a reference to this field within the parameter. |
4809 | 34.7k | CXXScopeSpec SS; |
4810 | 34.7k | LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, |
4811 | 34.7k | Sema::LookupMemberName); |
4812 | 34.7k | MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)0 |
4813 | 34.7k | : cast<ValueDecl>(Field), AS_public); |
4814 | 34.7k | MemberLookup.resolveKind(); |
4815 | 34.7k | ExprResult CtorArg |
4816 | 34.7k | = SemaRef.BuildMemberReferenceExpr(MemberExprBase, |
4817 | 34.7k | ParamType, Loc, |
4818 | 34.7k | /*IsArrow=*/false, |
4819 | 34.7k | SS, |
4820 | 34.7k | /*TemplateKWLoc=*/SourceLocation(), |
4821 | 34.7k | /*FirstQualifierInScope=*/nullptr, |
4822 | 34.7k | MemberLookup, |
4823 | 34.7k | /*TemplateArgs=*/nullptr, |
4824 | 34.7k | /*S*/nullptr); |
4825 | 34.7k | if (CtorArg.isInvalid()) |
4826 | 0 | return true; |
4827 | | |
4828 | | // C++11 [class.copy]p15: |
4829 | | // - if a member m has rvalue reference type T&&, it is direct-initialized |
4830 | | // with static_cast<T&&>(x.m); |
4831 | 34.7k | if (RefersToRValueRef(CtorArg.get())) { |
4832 | 85 | CtorArg = CastForMoving(SemaRef, CtorArg.get()); |
4833 | 85 | } |
4834 | | |
4835 | 34.7k | InitializedEntity Entity = |
4836 | 34.7k | Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, |
4837 | 0 | /*Implicit*/ true) |
4838 | 34.7k | : InitializedEntity::InitializeMember(Field, nullptr, |
4839 | 34.7k | /*Implicit*/ true); |
4840 | | |
4841 | | // Direct-initialize to use the copy constructor. |
4842 | 34.7k | InitializationKind InitKind = |
4843 | 34.7k | InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); |
4844 | | |
4845 | 34.7k | Expr *CtorArgE = CtorArg.getAs<Expr>(); |
4846 | 34.7k | InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); |
4847 | 34.7k | ExprResult MemberInit = |
4848 | 34.7k | InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); |
4849 | 34.7k | MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); |
4850 | 34.7k | if (MemberInit.isInvalid()) |
4851 | 0 | return true; |
4852 | | |
4853 | 34.7k | if (Indirect) |
4854 | 0 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( |
4855 | 0 | SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); |
4856 | 34.7k | else |
4857 | 34.7k | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( |
4858 | 34.7k | SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); |
4859 | 34.7k | return false; |
4860 | 34.7k | } |
4861 | | |
4862 | 29.2k | assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && |
4863 | 29.2k | "Unhandled implicit init kind!"); |
4864 | | |
4865 | 0 | QualType FieldBaseElementType = |
4866 | 29.2k | SemaRef.Context.getBaseElementType(Field->getType()); |
4867 | | |
4868 | 29.2k | if (FieldBaseElementType->isRecordType()) { |
4869 | 4.21k | InitializedEntity InitEntity = |
4870 | 4.21k | Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, |
4871 | 8 | /*Implicit*/ true) |
4872 | 4.21k | : InitializedEntity::InitializeMember(Field, nullptr, |
4873 | 4.21k | /*Implicit*/ true); |
4874 | 4.21k | InitializationKind InitKind = |
4875 | 4.21k | InitializationKind::CreateDefault(Loc); |
4876 | | |
4877 | 4.21k | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); |
4878 | 4.21k | ExprResult MemberInit = |
4879 | 4.21k | InitSeq.Perform(SemaRef, InitEntity, InitKind, None); |
4880 | | |
4881 | 4.21k | MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); |
4882 | 4.21k | if (MemberInit.isInvalid()) |
4883 | 18 | return true; |
4884 | | |
4885 | 4.20k | if (Indirect) |
4886 | 8 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, |
4887 | 8 | Indirect, Loc, |
4888 | 8 | Loc, |
4889 | 8 | MemberInit.get(), |
4890 | 8 | Loc); |
4891 | 4.19k | else |
4892 | 4.19k | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, |
4893 | 4.19k | Field, Loc, Loc, |
4894 | 4.19k | MemberInit.get(), |
4895 | 4.19k | Loc); |
4896 | 4.20k | return false; |
4897 | 4.21k | } |
4898 | | |
4899 | 25.0k | if (!Field->getParent()->isUnion()) { |
4900 | 25.0k | if (FieldBaseElementType->isReferenceType()) { |
4901 | 9 | SemaRef.Diag(Constructor->getLocation(), |
4902 | 9 | diag::err_uninitialized_member_in_ctor) |
4903 | 9 | << (int)Constructor->isImplicit() |
4904 | 9 | << SemaRef.Context.getTagDeclType(Constructor->getParent()) |
4905 | 9 | << 0 << Field->getDeclName(); |
4906 | 9 | SemaRef.Diag(Field->getLocation(), diag::note_declared_at); |
4907 | 9 | return true; |
4908 | 9 | } |
4909 | | |
4910 | 25.0k | if (FieldBaseElementType.isConstQualified()) { |
4911 | 3 | SemaRef.Diag(Constructor->getLocation(), |
4912 | 3 | diag::err_uninitialized_member_in_ctor) |
4913 | 3 | << (int)Constructor->isImplicit() |
4914 | 3 | << SemaRef.Context.getTagDeclType(Constructor->getParent()) |
4915 | 3 | << 1 << Field->getDeclName(); |
4916 | 3 | SemaRef.Diag(Field->getLocation(), diag::note_declared_at); |
4917 | 3 | return true; |
4918 | 3 | } |
4919 | 25.0k | } |
4920 | | |
4921 | 25.0k | if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { |
4922 | | // ARC and Weak: |
4923 | | // Default-initialize Objective-C pointers to NULL. |
4924 | 40 | CXXMemberInit |
4925 | 40 | = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, |
4926 | 40 | Loc, Loc, |
4927 | 40 | new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), |
4928 | 40 | Loc); |
4929 | 40 | return false; |
4930 | 40 | } |
4931 | | |
4932 | | // Nothing to initialize. |
4933 | 25.0k | CXXMemberInit = nullptr; |
4934 | 25.0k | return false; |
4935 | 25.0k | } |
4936 | | |
4937 | | namespace { |
4938 | | struct BaseAndFieldInfo { |
4939 | | Sema &S; |
4940 | | CXXConstructorDecl *Ctor; |
4941 | | bool AnyErrorsInInits; |
4942 | | ImplicitInitializerKind IIK; |
4943 | | llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; |
4944 | | SmallVector<CXXCtorInitializer*, 8> AllToInit; |
4945 | | llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; |
4946 | | |
4947 | | BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) |
4948 | 150k | : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { |
4949 | 150k | bool Generated = Ctor->isImplicit() || Ctor->isDefaulted()84.2k ; |
4950 | 150k | if (Ctor->getInheritedConstructor()) |
4951 | 315 | IIK = IIK_Inherit; |
4952 | 149k | else if (Generated && Ctor->isCopyConstructor()76.3k ) |
4953 | 15.8k | IIK = IIK_Copy; |
4954 | 134k | else if (Generated && Ctor->isMoveConstructor()60.5k ) |
4955 | 28.2k | IIK = IIK_Move; |
4956 | 105k | else |
4957 | 105k | IIK = IIK_Default; |
4958 | 150k | } |
4959 | | |
4960 | 2.05M | bool isImplicitCopyOrMove() const { |
4961 | 2.05M | switch (IIK) { |
4962 | 149k | case IIK_Copy: |
4963 | 497k | case IIK_Move: |
4964 | 497k | return true; |
4965 | | |
4966 | 1.55M | case IIK_Default: |
4967 | 1.55M | case IIK_Inherit: |
4968 | 1.55M | return false; |
4969 | 2.05M | } |
4970 | | |
4971 | 0 | llvm_unreachable("Invalid ImplicitInitializerKind!"); |
4972 | 0 | } |
4973 | | |
4974 | 97.0k | bool addFieldInitializer(CXXCtorInitializer *Init) { |
4975 | 97.0k | AllToInit.push_back(Init); |
4976 | | |
4977 | | // Check whether this initializer makes the field "used". |
4978 | 97.0k | if (Init->getInit()->HasSideEffects(S.Context)) |
4979 | 13.6k | S.UnusedPrivateFields.remove(Init->getAnyMember()); |
4980 | | |
4981 | 97.0k | return false; |
4982 | 97.0k | } |
4983 | | |
4984 | 80.2k | bool isInactiveUnionMember(FieldDecl *Field) { |
4985 | 80.2k | RecordDecl *Record = Field->getParent(); |
4986 | 80.2k | if (!Record->isUnion()) |
4987 | 68.3k | return false; |
4988 | | |
4989 | 11.8k | if (FieldDecl *Active = |
4990 | 11.8k | ActiveUnionMember.lookup(Record->getCanonicalDecl())) |
4991 | 290 | return Active != Field->getCanonicalDecl(); |
4992 | | |
4993 | | // In an implicit copy or move constructor, ignore any in-class initializer. |
4994 | 11.5k | if (isImplicitCopyOrMove()) |
4995 | 1.58k | return true; |
4996 | | |
4997 | | // If there's no explicit initialization, the field is active only if it |
4998 | | // has an in-class initializer... |
4999 | 9.98k | if (Field->hasInClassInitializer()) |
5000 | 85 | return false; |
5001 | | // ... or it's an anonymous struct or union whose class has an in-class |
5002 | | // initializer. |
5003 | 9.90k | if (!Field->isAnonymousStructOrUnion()) |
5004 | 9.84k | return true; |
5005 | 55 | CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); |
5006 | 55 | return !FieldRD->hasInClassInitializer(); |
5007 | 9.90k | } |
5008 | | |
5009 | | /// Determine whether the given field is, or is within, a union member |
5010 | | /// that is inactive (because there was an initializer given for a different |
5011 | | /// member of the union, or because the union was not initialized at all). |
5012 | | bool isWithinInactiveUnionMember(FieldDecl *Field, |
5013 | 78.4k | IndirectFieldDecl *Indirect) { |
5014 | 78.4k | if (!Indirect) |
5015 | 76.8k | return isInactiveUnionMember(Field); |
5016 | | |
5017 | 3.40k | for (auto *C : Indirect->chain())1.66k { |
5018 | 3.40k | FieldDecl *Field = dyn_cast<FieldDecl>(C); |
5019 | 3.40k | if (Field && isInactiveUnionMember(Field)) |
5020 | 1.53k | return true; |
5021 | 3.40k | } |
5022 | 130 | return false; |
5023 | 1.66k | } |
5024 | | }; |
5025 | | } |
5026 | | |
5027 | | /// Determine whether the given type is an incomplete or zero-lenfgth |
5028 | | /// array type. |
5029 | 181k | static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { |
5030 | 181k | if (T->isIncompleteArrayType()) |
5031 | 37 | return true; |
5032 | | |
5033 | 192k | while (const ConstantArrayType *181k ArrayT = Context.getAsConstantArrayType(T)) { |
5034 | 11.4k | if (!ArrayT->getSize()) |
5035 | 68 | return true; |
5036 | | |
5037 | 11.3k | T = ArrayT->getElementType(); |
5038 | 11.3k | } |
5039 | | |
5040 | 181k | return false; |
5041 | 181k | } |
5042 | | |
5043 | | static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, |
5044 | | FieldDecl *Field, |
5045 | 134k | IndirectFieldDecl *Indirect = nullptr) { |
5046 | 134k | if (Field->isInvalidDecl()) |
5047 | 100 | return false; |
5048 | | |
5049 | | // Overwhelmingly common case: we have a direct initializer for this field. |
5050 | 133k | if (CXXCtorInitializer *Init = |
5051 | 133k | Info.AllBaseFields.lookup(Field->getCanonicalDecl())) |
5052 | 55.4k | return Info.addFieldInitializer(Init); |
5053 | | |
5054 | | // C++11 [class.base.init]p8: |
5055 | | // if the entity is a non-static data member that has a |
5056 | | // brace-or-equal-initializer and either |
5057 | | // -- the constructor's class is a union and no other variant member of that |
5058 | | // union is designated by a mem-initializer-id or |
5059 | | // -- the constructor's class is not a union, and, if the entity is a member |
5060 | | // of an anonymous union, no other member of that union is designated by |
5061 | | // a mem-initializer-id, |
5062 | | // the entity is initialized as specified in [dcl.init]. |
5063 | | // |
5064 | | // We also apply the same rules to handle anonymous structs within anonymous |
5065 | | // unions. |
5066 | 78.4k | if (Info.isWithinInactiveUnionMember(Field, Indirect)) |
5067 | 11.7k | return false; |
5068 | | |
5069 | 66.7k | if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()2.79k ) { |
5070 | 2.62k | ExprResult DIE = |
5071 | 2.62k | SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); |
5072 | 2.62k | if (DIE.isInvalid()) |
5073 | 2 | return true; |
5074 | | |
5075 | 2.62k | auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); |
5076 | 2.62k | SemaRef.checkInitializerLifetime(Entity, DIE.get()); |
5077 | | |
5078 | 2.62k | CXXCtorInitializer *Init; |
5079 | 2.62k | if (Indirect) |
5080 | 71 | Init = new (SemaRef.Context) |
5081 | 71 | CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), |
5082 | 71 | SourceLocation(), DIE.get(), SourceLocation()); |
5083 | 2.55k | else |
5084 | 2.55k | Init = new (SemaRef.Context) |
5085 | 2.55k | CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), |
5086 | 2.55k | SourceLocation(), DIE.get(), SourceLocation()); |
5087 | 2.62k | return Info.addFieldInitializer(Init); |
5088 | 2.62k | } |
5089 | | |
5090 | | // Don't initialize incomplete or zero-length arrays. |
5091 | 64.1k | if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) |
5092 | 71 | return false; |
5093 | | |
5094 | | // Don't try to build an implicit initializer if there were semantic |
5095 | | // errors in any of the initializers (and therefore we might be |
5096 | | // missing some that the user actually wrote). |
5097 | 64.0k | if (Info.AnyErrorsInInits) |
5098 | 20 | return false; |
5099 | | |
5100 | 64.0k | CXXCtorInitializer *Init = nullptr; |
5101 | 64.0k | if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, |
5102 | 64.0k | Indirect, Init)) |
5103 | 30 | return true; |
5104 | | |
5105 | 63.9k | if (!Init) |
5106 | 25.0k | return false; |
5107 | | |
5108 | 38.9k | return Info.addFieldInitializer(Init); |
5109 | 63.9k | } |
5110 | | |
5111 | | bool |
5112 | | Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, |
5113 | 543 | CXXCtorInitializer *Initializer) { |