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/DeclCXX.h" |
21 | #include "clang/AST/DeclTemplate.h" |
22 | #include "clang/AST/EvaluatedExprVisitor.h" |
23 | #include "clang/AST/Expr.h" |
24 | #include "clang/AST/ExprCXX.h" |
25 | #include "clang/AST/RecordLayout.h" |
26 | #include "clang/AST/RecursiveASTVisitor.h" |
27 | #include "clang/AST/StmtVisitor.h" |
28 | #include "clang/AST/TypeLoc.h" |
29 | #include "clang/AST/TypeOrdering.h" |
30 | #include "clang/Basic/AttributeCommonInfo.h" |
31 | #include "clang/Basic/PartialDiagnostic.h" |
32 | #include "clang/Basic/Specifiers.h" |
33 | #include "clang/Basic/TargetInfo.h" |
34 | #include "clang/Lex/LiteralSupport.h" |
35 | #include "clang/Lex/Preprocessor.h" |
36 | #include "clang/Sema/CXXFieldCollector.h" |
37 | #include "clang/Sema/DeclSpec.h" |
38 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
39 | #include "clang/Sema/Initialization.h" |
40 | #include "clang/Sema/Lookup.h" |
41 | #include "clang/Sema/Ownership.h" |
42 | #include "clang/Sema/ParsedTemplate.h" |
43 | #include "clang/Sema/Scope.h" |
44 | #include "clang/Sema/ScopeInfo.h" |
45 | #include "clang/Sema/SemaCUDA.h" |
46 | #include "clang/Sema/SemaInternal.h" |
47 | #include "clang/Sema/SemaOpenMP.h" |
48 | #include "clang/Sema/Template.h" |
49 | #include "llvm/ADT/ArrayRef.h" |
50 | #include "llvm/ADT/STLExtras.h" |
51 | #include "llvm/ADT/STLForwardCompat.h" |
52 | #include "llvm/ADT/ScopeExit.h" |
53 | #include "llvm/ADT/SmallString.h" |
54 | #include "llvm/ADT/StringExtras.h" |
55 | #include "llvm/Support/ConvertUTF.h" |
56 | #include "llvm/Support/SaveAndRestore.h" |
57 | #include <map> |
58 | #include <optional> |
59 | #include <set> |
60 | |
61 | using namespace clang; |
62 | |
63 | //===----------------------------------------------------------------------===// |
64 | // CheckDefaultArgumentVisitor |
65 | //===----------------------------------------------------------------------===// |
66 | |
67 | namespace { |
68 | /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses |
69 | /// the default argument of a parameter to determine whether it |
70 | /// contains any ill-formed subexpressions. For example, this will |
71 | /// diagnose the use of local variables or parameters within the |
72 | /// default argument expression. |
73 | class CheckDefaultArgumentVisitor |
74 | : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> { |
75 | Sema &S; |
76 | const Expr *DefaultArg; |
77 | |
78 | public: |
79 | CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg) |
80 | : S(S), DefaultArg(DefaultArg) {} |
81 | |
82 | bool VisitExpr(const Expr *Node); |
83 | bool VisitDeclRefExpr(const DeclRefExpr *DRE); |
84 | bool VisitCXXThisExpr(const CXXThisExpr *ThisE); |
85 | bool VisitLambdaExpr(const LambdaExpr *Lambda); |
86 | bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE); |
87 | }; |
88 | |
89 | /// VisitExpr - Visit all of the children of this expression. |
90 | bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) { |
91 | bool IsInvalid = false; |
92 | for (const Stmt *SubStmt : Node->children()) |
93 | if (SubStmt) |
94 | IsInvalid |= Visit(SubStmt); |
95 | return IsInvalid; |
96 | } |
97 | |
98 | /// VisitDeclRefExpr - Visit a reference to a declaration, to |
99 | /// determine whether this declaration can be used in the default |
100 | /// argument expression. |
101 | bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) { |
102 | const ValueDecl *Decl = dyn_cast<ValueDecl>(Val: DRE->getDecl()); |
103 | |
104 | if (!isa<VarDecl, BindingDecl>(Val: Decl)) |
105 | return false; |
106 | |
107 | if (const auto *Param = dyn_cast<ParmVarDecl>(Val: Decl)) { |
108 | // C++ [dcl.fct.default]p9: |
109 | // [...] parameters of a function shall not be used in default |
110 | // argument expressions, even if they are not evaluated. [...] |
111 | // |
112 | // C++17 [dcl.fct.default]p9 (by CWG 2082): |
113 | // [...] A parameter shall not appear as a potentially-evaluated |
114 | // expression in a default argument. [...] |
115 | // |
116 | if (DRE->isNonOdrUse() != NOUR_Unevaluated) |
117 | return S.Diag(DRE->getBeginLoc(), |
118 | diag::err_param_default_argument_references_param) |
119 | << Param->getDeclName() << DefaultArg->getSourceRange(); |
120 | } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) { |
121 | // C++ [dcl.fct.default]p7: |
122 | // Local variables shall not be used in default argument |
123 | // expressions. |
124 | // |
125 | // C++17 [dcl.fct.default]p7 (by CWG 2082): |
126 | // A local variable shall not appear as a potentially-evaluated |
127 | // expression in a default argument. |
128 | // |
129 | // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346): |
130 | // Note: A local variable cannot be odr-used (6.3) in a default |
131 | // argument. |
132 | // |
133 | if (VD->isLocalVarDecl() && !DRE->isNonOdrUse()) |
134 | return S.Diag(DRE->getBeginLoc(), |
135 | diag::err_param_default_argument_references_local) |
136 | << Decl << DefaultArg->getSourceRange(); |
137 | } |
138 | return false; |
139 | } |
140 | |
141 | /// VisitCXXThisExpr - Visit a C++ "this" expression. |
142 | bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) { |
143 | // C++ [dcl.fct.default]p8: |
144 | // The keyword this shall not be used in a default argument of a |
145 | // member function. |
146 | return S.Diag(ThisE->getBeginLoc(), |
147 | diag::err_param_default_argument_references_this) |
148 | << ThisE->getSourceRange(); |
149 | } |
150 | |
151 | bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr( |
152 | const PseudoObjectExpr *POE) { |
153 | bool Invalid = false; |
154 | for (const Expr *E : POE->semantics()) { |
155 | // Look through bindings. |
156 | if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) { |
157 | E = OVE->getSourceExpr(); |
158 | assert(E && "pseudo-object binding without source expression?" ); |
159 | } |
160 | |
161 | Invalid |= Visit(E); |
162 | } |
163 | return Invalid; |
164 | } |
165 | |
166 | bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) { |
167 | // [expr.prim.lambda.capture]p9 |
168 | // a lambda-expression appearing in a default argument cannot implicitly or |
169 | // explicitly capture any local entity. Such a lambda-expression can still |
170 | // have an init-capture if any full-expression in its initializer satisfies |
171 | // the constraints of an expression appearing in a default argument. |
172 | bool Invalid = false; |
173 | for (const LambdaCapture &LC : Lambda->captures()) { |
174 | if (!Lambda->isInitCapture(&LC)) |
175 | return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg); |
176 | // Init captures are always VarDecl. |
177 | auto *D = cast<VarDecl>(Val: LC.getCapturedVar()); |
178 | Invalid |= Visit(D->getInit()); |
179 | } |
180 | return Invalid; |
181 | } |
182 | } // namespace |
183 | |
184 | void |
185 | Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, |
186 | const CXXMethodDecl *Method) { |
187 | // If we have an MSAny spec already, don't bother. |
188 | if (!Method || ComputedEST == EST_MSAny) |
189 | return; |
190 | |
191 | const FunctionProtoType *Proto |
192 | = Method->getType()->getAs<FunctionProtoType>(); |
193 | Proto = Self->ResolveExceptionSpec(Loc: CallLoc, FPT: Proto); |
194 | if (!Proto) |
195 | return; |
196 | |
197 | ExceptionSpecificationType EST = Proto->getExceptionSpecType(); |
198 | |
199 | // If we have a throw-all spec at this point, ignore the function. |
200 | if (ComputedEST == EST_None) |
201 | return; |
202 | |
203 | if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) |
204 | EST = EST_BasicNoexcept; |
205 | |
206 | switch (EST) { |
207 | case EST_Unparsed: |
208 | case EST_Uninstantiated: |
209 | case EST_Unevaluated: |
210 | llvm_unreachable("should not see unresolved exception specs here" ); |
211 | |
212 | // If this function can throw any exceptions, make a note of that. |
213 | case EST_MSAny: |
214 | case EST_None: |
215 | // FIXME: Whichever we see last of MSAny and None determines our result. |
216 | // We should make a consistent, order-independent choice here. |
217 | ClearExceptions(); |
218 | ComputedEST = EST; |
219 | return; |
220 | case EST_NoexceptFalse: |
221 | ClearExceptions(); |
222 | ComputedEST = EST_None; |
223 | return; |
224 | // FIXME: If the call to this decl is using any of its default arguments, we |
225 | // need to search them for potentially-throwing calls. |
226 | // If this function has a basic noexcept, it doesn't affect the outcome. |
227 | case EST_BasicNoexcept: |
228 | case EST_NoexceptTrue: |
229 | case EST_NoThrow: |
230 | return; |
231 | // If we're still at noexcept(true) and there's a throw() callee, |
232 | // change to that specification. |
233 | case EST_DynamicNone: |
234 | if (ComputedEST == EST_BasicNoexcept) |
235 | ComputedEST = EST_DynamicNone; |
236 | return; |
237 | case EST_DependentNoexcept: |
238 | llvm_unreachable( |
239 | "should not generate implicit declarations for dependent cases" ); |
240 | case EST_Dynamic: |
241 | break; |
242 | } |
243 | assert(EST == EST_Dynamic && "EST case not considered earlier." ); |
244 | assert(ComputedEST != EST_None && |
245 | "Shouldn't collect exceptions when throw-all is guaranteed." ); |
246 | ComputedEST = EST_Dynamic; |
247 | // Record the exceptions in this function's exception specification. |
248 | for (const auto &E : Proto->exceptions()) |
249 | if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) |
250 | Exceptions.push_back(E); |
251 | } |
252 | |
253 | void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) { |
254 | if (!S || ComputedEST == EST_MSAny) |
255 | return; |
256 | |
257 | // FIXME: |
258 | // |
259 | // C++0x [except.spec]p14: |
260 | // [An] implicit exception-specification specifies the type-id T if and |
261 | // only if T is allowed by the exception-specification of a function directly |
262 | // invoked by f's implicit definition; f shall allow all exceptions if any |
263 | // function it directly invokes allows all exceptions, and f shall allow no |
264 | // exceptions if every function it directly invokes allows no exceptions. |
265 | // |
266 | // Note in particular that if an implicit exception-specification is generated |
267 | // for a function containing a throw-expression, that specification can still |
268 | // be noexcept(true). |
269 | // |
270 | // Note also that 'directly invoked' is not defined in the standard, and there |
271 | // is no indication that we should only consider potentially-evaluated calls. |
272 | // |
273 | // Ultimately we should implement the intent of the standard: the exception |
274 | // specification should be the set of exceptions which can be thrown by the |
275 | // implicit definition. For now, we assume that any non-nothrow expression can |
276 | // throw any exception. |
277 | |
278 | if (Self->canThrow(E: S)) |
279 | ComputedEST = EST_None; |
280 | } |
281 | |
282 | ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, |
283 | SourceLocation EqualLoc) { |
284 | if (RequireCompleteType(Param->getLocation(), Param->getType(), |
285 | diag::err_typecheck_decl_incomplete_type)) |
286 | return true; |
287 | |
288 | // C++ [dcl.fct.default]p5 |
289 | // A default argument expression is implicitly converted (clause |
290 | // 4) to the parameter type. The default argument expression has |
291 | // the same semantic constraints as the initializer expression in |
292 | // a declaration of a variable of the parameter type, using the |
293 | // copy-initialization semantics (8.5). |
294 | InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, |
295 | Parm: Param); |
296 | InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Param->getLocation(), |
297 | EqualLoc); |
298 | InitializationSequence InitSeq(*this, Entity, Kind, Arg); |
299 | ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Arg); |
300 | if (Result.isInvalid()) |
301 | return true; |
302 | Arg = Result.getAs<Expr>(); |
303 | |
304 | CheckCompletedExpr(E: Arg, CheckLoc: EqualLoc); |
305 | Arg = MaybeCreateExprWithCleanups(SubExpr: Arg); |
306 | |
307 | return Arg; |
308 | } |
309 | |
310 | void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, |
311 | SourceLocation EqualLoc) { |
312 | // Add the default argument to the parameter |
313 | Param->setDefaultArg(Arg); |
314 | |
315 | // We have already instantiated this parameter; provide each of the |
316 | // instantiations with the uninstantiated default argument. |
317 | UnparsedDefaultArgInstantiationsMap::iterator InstPos |
318 | = UnparsedDefaultArgInstantiations.find(Val: Param); |
319 | if (InstPos != UnparsedDefaultArgInstantiations.end()) { |
320 | for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) |
321 | InstPos->second[I]->setUninstantiatedDefaultArg(Arg); |
322 | |
323 | // We're done tracking this parameter's instantiations. |
324 | UnparsedDefaultArgInstantiations.erase(I: InstPos); |
325 | } |
326 | } |
327 | |
328 | /// ActOnParamDefaultArgument - Check whether the default argument |
329 | /// provided for a function parameter is well-formed. If so, attach it |
330 | /// to the parameter declaration. |
331 | void |
332 | Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, |
333 | Expr *DefaultArg) { |
334 | if (!param || !DefaultArg) |
335 | return; |
336 | |
337 | ParmVarDecl *Param = cast<ParmVarDecl>(Val: param); |
338 | UnparsedDefaultArgLocs.erase(Val: Param); |
339 | |
340 | // Default arguments are only permitted in C++ |
341 | if (!getLangOpts().CPlusPlus) { |
342 | Diag(EqualLoc, diag::err_param_default_argument) |
343 | << DefaultArg->getSourceRange(); |
344 | return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg); |
345 | } |
346 | |
347 | // Check for unexpanded parameter packs. |
348 | if (DiagnoseUnexpandedParameterPack(E: DefaultArg, UPPC: UPPC_DefaultArgument)) |
349 | return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg); |
350 | |
351 | // C++11 [dcl.fct.default]p3 |
352 | // A default argument expression [...] shall not be specified for a |
353 | // parameter pack. |
354 | if (Param->isParameterPack()) { |
355 | Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) |
356 | << DefaultArg->getSourceRange(); |
357 | // Recover by discarding the default argument. |
358 | Param->setDefaultArg(nullptr); |
359 | return; |
360 | } |
361 | |
362 | ExprResult Result = ConvertParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc); |
363 | if (Result.isInvalid()) |
364 | return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg); |
365 | |
366 | DefaultArg = Result.getAs<Expr>(); |
367 | |
368 | // Check that the default argument is well-formed |
369 | CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg); |
370 | if (DefaultArgChecker.Visit(DefaultArg)) |
371 | return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg); |
372 | |
373 | SetParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc); |
374 | } |
375 | |
376 | /// ActOnParamUnparsedDefaultArgument - We've seen a default |
377 | /// argument for a function parameter, but we can't parse it yet |
378 | /// because we're inside a class definition. Note that this default |
379 | /// argument will be parsed later. |
380 | void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, |
381 | SourceLocation EqualLoc, |
382 | SourceLocation ArgLoc) { |
383 | if (!param) |
384 | return; |
385 | |
386 | ParmVarDecl *Param = cast<ParmVarDecl>(Val: param); |
387 | Param->setUnparsedDefaultArg(); |
388 | UnparsedDefaultArgLocs[Param] = ArgLoc; |
389 | } |
390 | |
391 | /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of |
392 | /// the default argument for the parameter param failed. |
393 | void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc, |
394 | Expr *DefaultArg) { |
395 | if (!param) |
396 | return; |
397 | |
398 | ParmVarDecl *Param = cast<ParmVarDecl>(Val: param); |
399 | Param->setInvalidDecl(); |
400 | UnparsedDefaultArgLocs.erase(Val: Param); |
401 | ExprResult RE; |
402 | if (DefaultArg) { |
403 | RE = CreateRecoveryExpr(Begin: EqualLoc, End: DefaultArg->getEndLoc(), SubExprs: {DefaultArg}, |
404 | T: Param->getType().getNonReferenceType()); |
405 | } else { |
406 | RE = CreateRecoveryExpr(Begin: EqualLoc, End: EqualLoc, SubExprs: {}, |
407 | T: Param->getType().getNonReferenceType()); |
408 | } |
409 | Param->setDefaultArg(RE.get()); |
410 | } |
411 | |
412 | /// CheckExtraCXXDefaultArguments - Check for any extra default |
413 | /// arguments in the declarator, which is not a function declaration |
414 | /// or definition and therefore is not permitted to have default |
415 | /// arguments. This routine should be invoked for every declarator |
416 | /// that is not a function declaration or definition. |
417 | void Sema::(Declarator &D) { |
418 | // C++ [dcl.fct.default]p3 |
419 | // A default argument expression shall be specified only in the |
420 | // parameter-declaration-clause of a function declaration or in a |
421 | // template-parameter (14.1). It shall not be specified for a |
422 | // parameter pack. If it is specified in a |
423 | // parameter-declaration-clause, it shall not occur within a |
424 | // declarator or abstract-declarator of a parameter-declaration. |
425 | bool MightBeFunction = D.isFunctionDeclarationContext(); |
426 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { |
427 | DeclaratorChunk &chunk = D.getTypeObject(i); |
428 | if (chunk.Kind == DeclaratorChunk::Function) { |
429 | if (MightBeFunction) { |
430 | // This is a function declaration. It can have default arguments, but |
431 | // keep looking in case its return type is a function type with default |
432 | // arguments. |
433 | MightBeFunction = false; |
434 | continue; |
435 | } |
436 | for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; |
437 | ++argIdx) { |
438 | ParmVarDecl *Param = cast<ParmVarDecl>(Val: chunk.Fun.Params[argIdx].Param); |
439 | if (Param->hasUnparsedDefaultArg()) { |
440 | std::unique_ptr<CachedTokens> Toks = |
441 | std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); |
442 | SourceRange SR; |
443 | if (Toks->size() > 1) |
444 | SR = SourceRange((*Toks)[1].getLocation(), |
445 | Toks->back().getLocation()); |
446 | else |
447 | SR = UnparsedDefaultArgLocs[Param]; |
448 | Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) |
449 | << SR; |
450 | } else if (Param->getDefaultArg()) { |
451 | Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) |
452 | << Param->getDefaultArg()->getSourceRange(); |
453 | Param->setDefaultArg(nullptr); |
454 | } |
455 | } |
456 | } else if (chunk.Kind != DeclaratorChunk::Paren) { |
457 | MightBeFunction = false; |
458 | } |
459 | } |
460 | } |
461 | |
462 | static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { |
463 | return llvm::any_of(Range: FD->parameters(), P: [](ParmVarDecl *P) { |
464 | return P->hasDefaultArg() && !P->hasInheritedDefaultArg(); |
465 | }); |
466 | } |
467 | |
468 | /// MergeCXXFunctionDecl - Merge two declarations of the same C++ |
469 | /// function, once we already know that they have the same |
470 | /// type. Subroutine of MergeFunctionDecl. Returns true if there was an |
471 | /// error, false otherwise. |
472 | bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, |
473 | Scope *S) { |
474 | bool Invalid = false; |
475 | |
476 | // The declaration context corresponding to the scope is the semantic |
477 | // parent, unless this is a local function declaration, in which case |
478 | // it is that surrounding function. |
479 | DeclContext *ScopeDC = New->isLocalExternDecl() |
480 | ? New->getLexicalDeclContext() |
481 | : New->getDeclContext(); |
482 | |
483 | // Find the previous declaration for the purpose of default arguments. |
484 | FunctionDecl *PrevForDefaultArgs = Old; |
485 | for (/**/; PrevForDefaultArgs; |
486 | // Don't bother looking back past the latest decl if this is a local |
487 | // extern declaration; nothing else could work. |
488 | PrevForDefaultArgs = New->isLocalExternDecl() |
489 | ? nullptr |
490 | : PrevForDefaultArgs->getPreviousDecl()) { |
491 | // Ignore hidden declarations. |
492 | if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) |
493 | continue; |
494 | |
495 | if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && |
496 | !New->isCXXClassMember()) { |
497 | // Ignore default arguments of old decl if they are not in |
498 | // the same scope and this is not an out-of-line definition of |
499 | // a member function. |
500 | continue; |
501 | } |
502 | |
503 | if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { |
504 | // If only one of these is a local function declaration, then they are |
505 | // declared in different scopes, even though isDeclInScope may think |
506 | // they're in the same scope. (If both are local, the scope check is |
507 | // sufficient, and if neither is local, then they are in the same scope.) |
508 | continue; |
509 | } |
510 | |
511 | // We found the right previous declaration. |
512 | break; |
513 | } |
514 | |
515 | // C++ [dcl.fct.default]p4: |
516 | // For non-template functions, default arguments can be added in |
517 | // later declarations of a function in the same |
518 | // scope. Declarations in different scopes have completely |
519 | // distinct sets of default arguments. That is, declarations in |
520 | // inner scopes do not acquire default arguments from |
521 | // declarations in outer scopes, and vice versa. In a given |
522 | // function declaration, all parameters subsequent to a |
523 | // parameter with a default argument shall have default |
524 | // arguments supplied in this or previous declarations. A |
525 | // default argument shall not be redefined by a later |
526 | // declaration (not even to the same value). |
527 | // |
528 | // C++ [dcl.fct.default]p6: |
529 | // Except for member functions of class templates, the default arguments |
530 | // in a member function definition that appears outside of the class |
531 | // definition are added to the set of default arguments provided by the |
532 | // member function declaration in the class definition. |
533 | for (unsigned p = 0, NumParams = PrevForDefaultArgs |
534 | ? PrevForDefaultArgs->getNumParams() |
535 | : 0; |
536 | p < NumParams; ++p) { |
537 | ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(i: p); |
538 | ParmVarDecl *NewParam = New->getParamDecl(i: p); |
539 | |
540 | bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; |
541 | bool NewParamHasDfl = NewParam->hasDefaultArg(); |
542 | |
543 | if (OldParamHasDfl && NewParamHasDfl) { |
544 | unsigned DiagDefaultParamID = |
545 | diag::err_param_default_argument_redefinition; |
546 | |
547 | // MSVC accepts that default parameters be redefined for member functions |
548 | // of template class. The new default parameter's value is ignored. |
549 | Invalid = true; |
550 | if (getLangOpts().MicrosoftExt) { |
551 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: New); |
552 | if (MD && MD->getParent()->getDescribedClassTemplate()) { |
553 | // Merge the old default argument into the new parameter. |
554 | NewParam->setHasInheritedDefaultArg(); |
555 | if (OldParam->hasUninstantiatedDefaultArg()) |
556 | NewParam->setUninstantiatedDefaultArg( |
557 | OldParam->getUninstantiatedDefaultArg()); |
558 | else |
559 | NewParam->setDefaultArg(OldParam->getInit()); |
560 | DiagDefaultParamID = diag::ext_param_default_argument_redefinition; |
561 | Invalid = false; |
562 | } |
563 | } |
564 | |
565 | // FIXME: If we knew where the '=' was, we could easily provide a fix-it |
566 | // hint here. Alternatively, we could walk the type-source information |
567 | // for NewParam to find the last source location in the type... but it |
568 | // isn't worth the effort right now. This is the kind of test case that |
569 | // is hard to get right: |
570 | // int f(int); |
571 | // void g(int (*fp)(int) = f); |
572 | // void g(int (*fp)(int) = &f); |
573 | Diag(NewParam->getLocation(), DiagDefaultParamID) |
574 | << NewParam->getDefaultArgRange(); |
575 | |
576 | // Look for the function declaration where the default argument was |
577 | // actually written, which may be a declaration prior to Old. |
578 | for (auto Older = PrevForDefaultArgs; |
579 | OldParam->hasInheritedDefaultArg(); /**/) { |
580 | Older = Older->getPreviousDecl(); |
581 | OldParam = Older->getParamDecl(i: p); |
582 | } |
583 | |
584 | Diag(OldParam->getLocation(), diag::note_previous_definition) |
585 | << OldParam->getDefaultArgRange(); |
586 | } else if (OldParamHasDfl) { |
587 | // Merge the old default argument into the new parameter unless the new |
588 | // function is a friend declaration in a template class. In the latter |
589 | // case the default arguments will be inherited when the friend |
590 | // declaration will be instantiated. |
591 | if (New->getFriendObjectKind() == Decl::FOK_None || |
592 | !New->getLexicalDeclContext()->isDependentContext()) { |
593 | // It's important to use getInit() here; getDefaultArg() |
594 | // strips off any top-level ExprWithCleanups. |
595 | NewParam->setHasInheritedDefaultArg(); |
596 | if (OldParam->hasUnparsedDefaultArg()) |
597 | NewParam->setUnparsedDefaultArg(); |
598 | else if (OldParam->hasUninstantiatedDefaultArg()) |
599 | NewParam->setUninstantiatedDefaultArg( |
600 | OldParam->getUninstantiatedDefaultArg()); |
601 | else |
602 | NewParam->setDefaultArg(OldParam->getInit()); |
603 | } |
604 | } else if (NewParamHasDfl) { |
605 | if (New->getDescribedFunctionTemplate()) { |
606 | // Paragraph 4, quoted above, only applies to non-template functions. |
607 | Diag(NewParam->getLocation(), |
608 | diag::err_param_default_argument_template_redecl) |
609 | << NewParam->getDefaultArgRange(); |
610 | Diag(PrevForDefaultArgs->getLocation(), |
611 | diag::note_template_prev_declaration) |
612 | << false; |
613 | } else if (New->getTemplateSpecializationKind() |
614 | != TSK_ImplicitInstantiation && |
615 | New->getTemplateSpecializationKind() != TSK_Undeclared) { |
616 | // C++ [temp.expr.spec]p21: |
617 | // Default function arguments shall not be specified in a declaration |
618 | // or a definition for one of the following explicit specializations: |
619 | // - the explicit specialization of a function template; |
620 | // - the explicit specialization of a member function template; |
621 | // - the explicit specialization of a member function of a class |
622 | // template where the class template specialization to which the |
623 | // member function specialization belongs is implicitly |
624 | // instantiated. |
625 | Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) |
626 | << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) |
627 | << New->getDeclName() |
628 | << NewParam->getDefaultArgRange(); |
629 | } else if (New->getDeclContext()->isDependentContext()) { |
630 | // C++ [dcl.fct.default]p6 (DR217): |
631 | // Default arguments for a member function of a class template shall |
632 | // be specified on the initial declaration of the member function |
633 | // within the class template. |
634 | // |
635 | // Reading the tea leaves a bit in DR217 and its reference to DR205 |
636 | // leads me to the conclusion that one cannot add default function |
637 | // arguments for an out-of-line definition of a member function of a |
638 | // dependent type. |
639 | int WhichKind = 2; |
640 | if (CXXRecordDecl *Record |
641 | = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { |
642 | if (Record->getDescribedClassTemplate()) |
643 | WhichKind = 0; |
644 | else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Record)) |
645 | WhichKind = 1; |
646 | else |
647 | WhichKind = 2; |
648 | } |
649 | |
650 | Diag(NewParam->getLocation(), |
651 | diag::err_param_default_argument_member_template_redecl) |
652 | << WhichKind |
653 | << NewParam->getDefaultArgRange(); |
654 | } |
655 | } |
656 | } |
657 | |
658 | // DR1344: If a default argument is added outside a class definition and that |
659 | // default argument makes the function a special member function, the program |
660 | // is ill-formed. This can only happen for constructors. |
661 | if (isa<CXXConstructorDecl>(Val: New) && |
662 | New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { |
663 | CXXSpecialMemberKind NewSM = getSpecialMember(MD: cast<CXXMethodDecl>(Val: New)), |
664 | OldSM = getSpecialMember(MD: cast<CXXMethodDecl>(Val: Old)); |
665 | if (NewSM != OldSM) { |
666 | ParmVarDecl *NewParam = New->getParamDecl(i: New->getMinRequiredArguments()); |
667 | assert(NewParam->hasDefaultArg()); |
668 | Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) |
669 | << NewParam->getDefaultArgRange() << llvm::to_underlying(NewSM); |
670 | Diag(Old->getLocation(), diag::note_previous_declaration); |
671 | } |
672 | } |
673 | |
674 | const FunctionDecl *Def; |
675 | // C++11 [dcl.constexpr]p1: If any declaration of a function or function |
676 | // template has a constexpr specifier then all its declarations shall |
677 | // contain the constexpr specifier. |
678 | if (New->getConstexprKind() != Old->getConstexprKind()) { |
679 | Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) |
680 | << New << static_cast<int>(New->getConstexprKind()) |
681 | << static_cast<int>(Old->getConstexprKind()); |
682 | Diag(Old->getLocation(), diag::note_previous_declaration); |
683 | Invalid = true; |
684 | } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && |
685 | Old->isDefined(Definition&: Def) && |
686 | // If a friend function is inlined but does not have 'inline' |
687 | // specifier, it is a definition. Do not report attribute conflict |
688 | // in this case, redefinition will be diagnosed later. |
689 | (New->isInlineSpecified() || |
690 | New->getFriendObjectKind() == Decl::FOK_None)) { |
691 | // C++11 [dcl.fcn.spec]p4: |
692 | // If the definition of a function appears in a translation unit before its |
693 | // first declaration as inline, the program is ill-formed. |
694 | Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; |
695 | Diag(Def->getLocation(), diag::note_previous_definition); |
696 | Invalid = true; |
697 | } |
698 | |
699 | // C++17 [temp.deduct.guide]p3: |
700 | // Two deduction guide declarations in the same translation unit |
701 | // for the same class template shall not have equivalent |
702 | // parameter-declaration-clauses. |
703 | if (isa<CXXDeductionGuideDecl>(Val: New) && |
704 | !New->isFunctionTemplateSpecialization() && isVisible(Old)) { |
705 | Diag(New->getLocation(), diag::err_deduction_guide_redeclared); |
706 | Diag(Old->getLocation(), diag::note_previous_declaration); |
707 | } |
708 | |
709 | // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default |
710 | // argument expression, that declaration shall be a definition and shall be |
711 | // the only declaration of the function or function template in the |
712 | // translation unit. |
713 | if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && |
714 | functionDeclHasDefaultArgument(FD: Old)) { |
715 | Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); |
716 | Diag(Old->getLocation(), diag::note_previous_declaration); |
717 | Invalid = true; |
718 | } |
719 | |
720 | // C++11 [temp.friend]p4 (DR329): |
721 | // When a function is defined in a friend function declaration in a class |
722 | // template, the function is instantiated when the function is odr-used. |
723 | // The same restrictions on multiple declarations and definitions that |
724 | // apply to non-template function declarations and definitions also apply |
725 | // to these implicit definitions. |
726 | const FunctionDecl *OldDefinition = nullptr; |
727 | if (New->isThisDeclarationInstantiatedFromAFriendDefinition() && |
728 | Old->isDefined(Definition&: OldDefinition, CheckForPendingFriendDefinition: true)) |
729 | CheckForFunctionRedefinition(FD: New, EffectiveDefinition: OldDefinition); |
730 | |
731 | return Invalid; |
732 | } |
733 | |
734 | void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) { |
735 | Diag(Loc, getLangOpts().CPlusPlus26 |
736 | ? diag::warn_cxx23_placeholder_var_definition |
737 | : diag::ext_placeholder_var_definition); |
738 | } |
739 | |
740 | NamedDecl * |
741 | Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, |
742 | MultiTemplateParamsArg TemplateParamLists) { |
743 | assert(D.isDecompositionDeclarator()); |
744 | const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); |
745 | |
746 | // The syntax only allows a decomposition declarator as a simple-declaration, |
747 | // a for-range-declaration, or a condition in Clang, but we parse it in more |
748 | // cases than that. |
749 | if (!D.mayHaveDecompositionDeclarator()) { |
750 | Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) |
751 | << Decomp.getSourceRange(); |
752 | return nullptr; |
753 | } |
754 | |
755 | if (!TemplateParamLists.empty()) { |
756 | // FIXME: There's no rule against this, but there are also no rules that |
757 | // would actually make it usable, so we reject it for now. |
758 | Diag(TemplateParamLists.front()->getTemplateLoc(), |
759 | diag::err_decomp_decl_template); |
760 | return nullptr; |
761 | } |
762 | |
763 | Diag(Decomp.getLSquareLoc(), |
764 | !getLangOpts().CPlusPlus17 |
765 | ? diag::ext_decomp_decl |
766 | : D.getContext() == DeclaratorContext::Condition |
767 | ? diag::ext_decomp_decl_cond |
768 | : diag::warn_cxx14_compat_decomp_decl) |
769 | << Decomp.getSourceRange(); |
770 | |
771 | // The semantic context is always just the current context. |
772 | DeclContext *const DC = CurContext; |
773 | |
774 | // C++17 [dcl.dcl]/8: |
775 | // The decl-specifier-seq shall contain only the type-specifier auto |
776 | // and cv-qualifiers. |
777 | // C++20 [dcl.dcl]/8: |
778 | // If decl-specifier-seq contains any decl-specifier other than static, |
779 | // thread_local, auto, or cv-qualifiers, the program is ill-formed. |
780 | // C++23 [dcl.pre]/6: |
781 | // Each decl-specifier in the decl-specifier-seq shall be static, |
782 | // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier. |
783 | auto &DS = D.getDeclSpec(); |
784 | { |
785 | // Note: While constrained-auto needs to be checked, we do so separately so |
786 | // we can emit a better diagnostic. |
787 | SmallVector<StringRef, 8> BadSpecifiers; |
788 | SmallVector<SourceLocation, 8> BadSpecifierLocs; |
789 | SmallVector<StringRef, 8> CPlusPlus20Specifiers; |
790 | SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; |
791 | if (auto SCS = DS.getStorageClassSpec()) { |
792 | if (SCS == DeclSpec::SCS_static) { |
793 | CPlusPlus20Specifiers.push_back(Elt: DeclSpec::getSpecifierName(S: SCS)); |
794 | CPlusPlus20SpecifierLocs.push_back(Elt: DS.getStorageClassSpecLoc()); |
795 | } else { |
796 | BadSpecifiers.push_back(Elt: DeclSpec::getSpecifierName(S: SCS)); |
797 | BadSpecifierLocs.push_back(Elt: DS.getStorageClassSpecLoc()); |
798 | } |
799 | } |
800 | if (auto TSCS = DS.getThreadStorageClassSpec()) { |
801 | CPlusPlus20Specifiers.push_back(Elt: DeclSpec::getSpecifierName(S: TSCS)); |
802 | CPlusPlus20SpecifierLocs.push_back(Elt: DS.getThreadStorageClassSpecLoc()); |
803 | } |
804 | if (DS.hasConstexprSpecifier()) { |
805 | BadSpecifiers.push_back( |
806 | Elt: DeclSpec::getSpecifierName(C: DS.getConstexprSpecifier())); |
807 | BadSpecifierLocs.push_back(Elt: DS.getConstexprSpecLoc()); |
808 | } |
809 | if (DS.isInlineSpecified()) { |
810 | BadSpecifiers.push_back(Elt: "inline" ); |
811 | BadSpecifierLocs.push_back(Elt: DS.getInlineSpecLoc()); |
812 | } |
813 | |
814 | if (!BadSpecifiers.empty()) { |
815 | auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); |
816 | Err << (int)BadSpecifiers.size() |
817 | << llvm::join(Begin: BadSpecifiers.begin(), End: BadSpecifiers.end(), Separator: " " ); |
818 | // Don't add FixItHints to remove the specifiers; we do still respect |
819 | // them when building the underlying variable. |
820 | for (auto Loc : BadSpecifierLocs) |
821 | Err << SourceRange(Loc, Loc); |
822 | } else if (!CPlusPlus20Specifiers.empty()) { |
823 | auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), |
824 | getLangOpts().CPlusPlus20 |
825 | ? diag::warn_cxx17_compat_decomp_decl_spec |
826 | : diag::ext_decomp_decl_spec); |
827 | Warn << (int)CPlusPlus20Specifiers.size() |
828 | << llvm::join(Begin: CPlusPlus20Specifiers.begin(), |
829 | End: CPlusPlus20Specifiers.end(), Separator: " " ); |
830 | for (auto Loc : CPlusPlus20SpecifierLocs) |
831 | Warn << SourceRange(Loc, Loc); |
832 | } |
833 | // We can't recover from it being declared as a typedef. |
834 | if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) |
835 | return nullptr; |
836 | } |
837 | |
838 | // C++2a [dcl.struct.bind]p1: |
839 | // A cv that includes volatile is deprecated |
840 | if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && |
841 | getLangOpts().CPlusPlus20) |
842 | Diag(DS.getVolatileSpecLoc(), |
843 | diag::warn_deprecated_volatile_structured_binding); |
844 | |
845 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D); |
846 | QualType R = TInfo->getType(); |
847 | |
848 | if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo, |
849 | UPPC: UPPC_DeclarationType)) |
850 | D.setInvalidType(); |
851 | |
852 | // The syntax only allows a single ref-qualifier prior to the decomposition |
853 | // declarator. No other declarator chunks are permitted. Also check the type |
854 | // specifier here. |
855 | if (DS.getTypeSpecType() != DeclSpec::TST_auto || |
856 | D.hasGroupingParens() || D.getNumTypeObjects() > 1 || |
857 | (D.getNumTypeObjects() == 1 && |
858 | D.getTypeObject(i: 0).Kind != DeclaratorChunk::Reference)) { |
859 | Diag(Decomp.getLSquareLoc(), |
860 | (D.hasGroupingParens() || |
861 | (D.getNumTypeObjects() && |
862 | D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) |
863 | ? diag::err_decomp_decl_parens |
864 | : diag::err_decomp_decl_type) |
865 | << R; |
866 | |
867 | // In most cases, there's no actual problem with an explicitly-specified |
868 | // type, but a function type won't work here, and ActOnVariableDeclarator |
869 | // shouldn't be called for such a type. |
870 | if (R->isFunctionType()) |
871 | D.setInvalidType(); |
872 | } |
873 | |
874 | // Constrained auto is prohibited by [decl.pre]p6, so check that here. |
875 | if (DS.isConstrainedAuto()) { |
876 | TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId(); |
877 | assert(TemplRep->Kind == TNK_Concept_template && |
878 | "No other template kind should be possible for a constrained auto" ); |
879 | |
880 | SourceRange TemplRange{TemplRep->TemplateNameLoc, |
881 | TemplRep->RAngleLoc.isValid() |
882 | ? TemplRep->RAngleLoc |
883 | : TemplRep->TemplateNameLoc}; |
884 | Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint) |
885 | << TemplRange << FixItHint::CreateRemoval(TemplRange); |
886 | } |
887 | |
888 | // Build the BindingDecls. |
889 | SmallVector<BindingDecl*, 8> Bindings; |
890 | |
891 | // Build the BindingDecls. |
892 | for (auto &B : D.getDecompositionDeclarator().bindings()) { |
893 | // Check for name conflicts. |
894 | DeclarationNameInfo NameInfo(B.Name, B.NameLoc); |
895 | IdentifierInfo *VarName = B.Name; |
896 | assert(VarName && "Cannot have an unnamed binding declaration" ); |
897 | |
898 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, |
899 | RedeclarationKind::ForVisibleRedeclaration); |
900 | LookupName(R&: Previous, S, |
901 | /*CreateBuiltins*/AllowBuiltinCreation: DC->getRedeclContext()->isTranslationUnit()); |
902 | |
903 | // It's not permitted to shadow a template parameter name. |
904 | if (Previous.isSingleResult() && |
905 | Previous.getFoundDecl()->isTemplateParameter()) { |
906 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), |
907 | Previous.getFoundDecl()); |
908 | Previous.clear(); |
909 | } |
910 | |
911 | auto *BD = BindingDecl::Create(C&: Context, DC, IdLoc: B.NameLoc, Id: VarName); |
912 | |
913 | // Find the shadowed declaration before filtering for scope. |
914 | NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() |
915 | ? getShadowedDeclaration(D: BD, R: Previous) |
916 | : nullptr; |
917 | |
918 | bool ConsiderLinkage = DC->isFunctionOrMethod() && |
919 | DS.getStorageClassSpec() == DeclSpec::SCS_extern; |
920 | FilterLookupForScope(R&: Previous, Ctx: DC, S, ConsiderLinkage, |
921 | /*AllowInlineNamespace*/false); |
922 | |
923 | bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static && |
924 | DC->isFunctionOrMethod() && VarName->isPlaceholder(); |
925 | if (!Previous.empty()) { |
926 | if (IsPlaceholder) { |
927 | bool sameDC = (Previous.end() - 1) |
928 | ->getDeclContext() |
929 | ->getRedeclContext() |
930 | ->Equals(DC->getRedeclContext()); |
931 | if (sameDC && |
932 | isDeclInScope(D: *(Previous.end() - 1), Ctx: CurContext, S, AllowInlineNamespace: false)) { |
933 | Previous.clear(); |
934 | DiagPlaceholderVariableDefinition(Loc: B.NameLoc); |
935 | } |
936 | } else { |
937 | auto *Old = Previous.getRepresentativeDecl(); |
938 | Diag(B.NameLoc, diag::err_redefinition) << B.Name; |
939 | Diag(Old->getLocation(), diag::note_previous_definition); |
940 | } |
941 | } else if (ShadowedDecl && !D.isRedeclaration()) { |
942 | CheckShadow(BD, ShadowedDecl, Previous); |
943 | } |
944 | PushOnScopeChains(BD, S, true); |
945 | Bindings.push_back(Elt: BD); |
946 | ParsingInitForAutoVars.insert(BD); |
947 | } |
948 | |
949 | // There are no prior lookup results for the variable itself, because it |
950 | // is unnamed. |
951 | DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, |
952 | Decomp.getLSquareLoc()); |
953 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, |
954 | RedeclarationKind::ForVisibleRedeclaration); |
955 | |
956 | // Build the variable that holds the non-decomposed object. |
957 | bool AddToScope = true; |
958 | NamedDecl *New = |
959 | ActOnVariableDeclarator(S, D, DC, TInfo, Previous, |
960 | TemplateParamLists: MultiTemplateParamsArg(), AddToScope, Bindings); |
961 | if (AddToScope) { |
962 | S->AddDecl(New); |
963 | CurContext->addHiddenDecl(New); |
964 | } |
965 | |
966 | if (OpenMP().isInOpenMPDeclareTargetContext()) |
967 | OpenMP().checkDeclIsAllowedInOpenMPTarget(nullptr, New); |
968 | |
969 | return New; |
970 | } |
971 | |
972 | static bool checkSimpleDecomposition( |
973 | Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, |
974 | QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, |
975 | llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { |
976 | if ((int64_t)Bindings.size() != NumElems) { |
977 | S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) |
978 | << DecompType << (unsigned)Bindings.size() |
979 | << (unsigned)NumElems.getLimitedValue(UINT_MAX) |
980 | << toString(NumElems, 10) << (NumElems < Bindings.size()); |
981 | return true; |
982 | } |
983 | |
984 | unsigned I = 0; |
985 | for (auto *B : Bindings) { |
986 | SourceLocation Loc = B->getLocation(); |
987 | ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc); |
988 | if (E.isInvalid()) |
989 | return true; |
990 | E = GetInit(Loc, E.get(), I++); |
991 | if (E.isInvalid()) |
992 | return true; |
993 | B->setBinding(DeclaredType: ElemType, Binding: E.get()); |
994 | } |
995 | |
996 | return false; |
997 | } |
998 | |
999 | static bool checkArrayLikeDecomposition(Sema &S, |
1000 | ArrayRef<BindingDecl *> Bindings, |
1001 | ValueDecl *Src, QualType DecompType, |
1002 | const llvm::APSInt &NumElems, |
1003 | QualType ElemType) { |
1004 | return checkSimpleDecomposition( |
1005 | S, Bindings, Src, DecompType, NumElems, ElemType, |
1006 | GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { |
1007 | ExprResult E = S.ActOnIntegerConstant(Loc, Val: I); |
1008 | if (E.isInvalid()) |
1009 | return ExprError(); |
1010 | return S.CreateBuiltinArraySubscriptExpr(Base, LLoc: Loc, Idx: E.get(), RLoc: Loc); |
1011 | }); |
1012 | } |
1013 | |
1014 | static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, |
1015 | ValueDecl *Src, QualType DecompType, |
1016 | const ConstantArrayType *CAT) { |
1017 | return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, |
1018 | llvm::APSInt(CAT->getSize()), |
1019 | CAT->getElementType()); |
1020 | } |
1021 | |
1022 | static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, |
1023 | ValueDecl *Src, QualType DecompType, |
1024 | const VectorType *VT) { |
1025 | return checkArrayLikeDecomposition( |
1026 | S, Bindings, Src, DecompType, NumElems: llvm::APSInt::get(X: VT->getNumElements()), |
1027 | ElemType: S.Context.getQualifiedType(T: VT->getElementType(), |
1028 | Qs: DecompType.getQualifiers())); |
1029 | } |
1030 | |
1031 | static bool checkComplexDecomposition(Sema &S, |
1032 | ArrayRef<BindingDecl *> Bindings, |
1033 | ValueDecl *Src, QualType DecompType, |
1034 | const ComplexType *CT) { |
1035 | return checkSimpleDecomposition( |
1036 | S, Bindings, Src, DecompType, NumElems: llvm::APSInt::get(X: 2), |
1037 | ElemType: S.Context.getQualifiedType(T: CT->getElementType(), |
1038 | Qs: DecompType.getQualifiers()), |
1039 | GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { |
1040 | return S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: I ? UO_Imag : UO_Real, InputExpr: Base); |
1041 | }); |
1042 | } |
1043 | |
1044 | static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, |
1045 | TemplateArgumentListInfo &Args, |
1046 | const TemplateParameterList *Params) { |
1047 | SmallString<128> SS; |
1048 | llvm::raw_svector_ostream OS(SS); |
1049 | bool First = true; |
1050 | unsigned I = 0; |
1051 | for (auto &Arg : Args.arguments()) { |
1052 | if (!First) |
1053 | OS << ", " ; |
1054 | Arg.getArgument().print(Policy: PrintingPolicy, Out&: OS, |
1055 | IncludeType: TemplateParameterList::shouldIncludeTypeForArgument( |
1056 | Policy: PrintingPolicy, TPL: Params, Idx: I)); |
1057 | First = false; |
1058 | I++; |
1059 | } |
1060 | return std::string(OS.str()); |
1061 | } |
1062 | |
1063 | static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, |
1064 | SourceLocation Loc, StringRef Trait, |
1065 | TemplateArgumentListInfo &Args, |
1066 | unsigned DiagID) { |
1067 | auto DiagnoseMissing = [&] { |
1068 | if (DiagID) |
1069 | S.Diag(Loc, DiagID) << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), |
1070 | Args, /*Params*/ nullptr); |
1071 | return true; |
1072 | }; |
1073 | |
1074 | // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. |
1075 | NamespaceDecl *Std = S.getStdNamespace(); |
1076 | if (!Std) |
1077 | return DiagnoseMissing(); |
1078 | |
1079 | // Look up the trait itself, within namespace std. We can diagnose various |
1080 | // problems with this lookup even if we've been asked to not diagnose a |
1081 | // missing specialization, because this can only fail if the user has been |
1082 | // declaring their own names in namespace std or we don't support the |
1083 | // standard library implementation in use. |
1084 | LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: Trait), |
1085 | Loc, Sema::LookupOrdinaryName); |
1086 | if (!S.LookupQualifiedName(Result, Std)) |
1087 | return DiagnoseMissing(); |
1088 | if (Result.isAmbiguous()) |
1089 | return true; |
1090 | |
1091 | ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); |
1092 | if (!TraitTD) { |
1093 | Result.suppressDiagnostics(); |
1094 | NamedDecl *Found = *Result.begin(); |
1095 | S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; |
1096 | S.Diag(Found->getLocation(), diag::note_declared_at); |
1097 | return true; |
1098 | } |
1099 | |
1100 | // Build the template-id. |
1101 | QualType TraitTy = S.CheckTemplateIdType(Template: TemplateName(TraitTD), TemplateLoc: Loc, TemplateArgs&: Args); |
1102 | if (TraitTy.isNull()) |
1103 | return true; |
1104 | if (!S.isCompleteType(Loc, T: TraitTy)) { |
1105 | if (DiagID) |
1106 | S.RequireCompleteType( |
1107 | Loc, TraitTy, DiagID, |
1108 | printTemplateArgs(S.Context.getPrintingPolicy(), Args, |
1109 | TraitTD->getTemplateParameters())); |
1110 | return true; |
1111 | } |
1112 | |
1113 | CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); |
1114 | assert(RD && "specialization of class template is not a class?" ); |
1115 | |
1116 | // Look up the member of the trait type. |
1117 | S.LookupQualifiedName(TraitMemberLookup, RD); |
1118 | return TraitMemberLookup.isAmbiguous(); |
1119 | } |
1120 | |
1121 | static TemplateArgumentLoc |
1122 | getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, |
1123 | uint64_t I) { |
1124 | TemplateArgument Arg(S.Context, S.Context.MakeIntValue(Value: I, Type: T), T); |
1125 | return S.getTrivialTemplateArgumentLoc(Arg, NTTPType: T, Loc); |
1126 | } |
1127 | |
1128 | static TemplateArgumentLoc |
1129 | getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { |
1130 | return S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(T), NTTPType: QualType(), Loc); |
1131 | } |
1132 | |
1133 | namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } |
1134 | |
1135 | static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, |
1136 | llvm::APSInt &Size) { |
1137 | EnterExpressionEvaluationContext ( |
1138 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
1139 | |
1140 | DeclarationName Value = S.PP.getIdentifierInfo(Name: "value" ); |
1141 | LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); |
1142 | |
1143 | // Form template argument list for tuple_size<T>. |
1144 | TemplateArgumentListInfo Args(Loc, Loc); |
1145 | Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T)); |
1146 | |
1147 | // If there's no tuple_size specialization or the lookup of 'value' is empty, |
1148 | // it's not tuple-like. |
1149 | if (lookupStdTypeTraitMember(S, TraitMemberLookup&: R, Loc, Trait: "tuple_size" , Args, /*DiagID*/ 0) || |
1150 | R.empty()) |
1151 | return IsTupleLike::NotTupleLike; |
1152 | |
1153 | // If we get this far, we've committed to the tuple interpretation, but |
1154 | // we can still fail if there actually isn't a usable ::value. |
1155 | |
1156 | struct ICEDiagnoser : Sema::VerifyICEDiagnoser { |
1157 | LookupResult &R; |
1158 | TemplateArgumentListInfo &Args; |
1159 | ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) |
1160 | : R(R), Args(Args) {} |
1161 | Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, |
1162 | SourceLocation Loc) override { |
1163 | return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) |
1164 | << printTemplateArgs(S.Context.getPrintingPolicy(), Args, |
1165 | /*Params*/ nullptr); |
1166 | } |
1167 | } Diagnoser(R, Args); |
1168 | |
1169 | ExprResult E = |
1170 | S.BuildDeclarationNameExpr(SS: CXXScopeSpec(), R, /*NeedsADL*/false); |
1171 | if (E.isInvalid()) |
1172 | return IsTupleLike::Error; |
1173 | |
1174 | E = S.VerifyIntegerConstantExpression(E: E.get(), Result: &Size, Diagnoser); |
1175 | if (E.isInvalid()) |
1176 | return IsTupleLike::Error; |
1177 | |
1178 | return IsTupleLike::TupleLike; |
1179 | } |
1180 | |
1181 | /// \return std::tuple_element<I, T>::type. |
1182 | static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, |
1183 | unsigned I, QualType T) { |
1184 | // Form template argument list for tuple_element<I, T>. |
1185 | TemplateArgumentListInfo Args(Loc, Loc); |
1186 | Args.addArgument( |
1187 | Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I)); |
1188 | Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T)); |
1189 | |
1190 | DeclarationName TypeDN = S.PP.getIdentifierInfo(Name: "type" ); |
1191 | LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); |
1192 | if (lookupStdTypeTraitMember( |
1193 | S, R, Loc, "tuple_element" , Args, |
1194 | diag::err_decomp_decl_std_tuple_element_not_specialized)) |
1195 | return QualType(); |
1196 | |
1197 | auto *TD = R.getAsSingle<TypeDecl>(); |
1198 | if (!TD) { |
1199 | R.suppressDiagnostics(); |
1200 | S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) |
1201 | << printTemplateArgs(S.Context.getPrintingPolicy(), Args, |
1202 | /*Params*/ nullptr); |
1203 | if (!R.empty()) |
1204 | S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); |
1205 | return QualType(); |
1206 | } |
1207 | |
1208 | return S.Context.getTypeDeclType(Decl: TD); |
1209 | } |
1210 | |
1211 | namespace { |
1212 | struct InitializingBinding { |
1213 | Sema &S; |
1214 | InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { |
1215 | Sema::CodeSynthesisContext Ctx; |
1216 | Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; |
1217 | Ctx.PointOfInstantiation = BD->getLocation(); |
1218 | Ctx.Entity = BD; |
1219 | S.pushCodeSynthesisContext(Ctx); |
1220 | } |
1221 | ~InitializingBinding() { |
1222 | S.popCodeSynthesisContext(); |
1223 | } |
1224 | }; |
1225 | } |
1226 | |
1227 | static bool checkTupleLikeDecomposition(Sema &S, |
1228 | ArrayRef<BindingDecl *> Bindings, |
1229 | VarDecl *Src, QualType DecompType, |
1230 | const llvm::APSInt &TupleSize) { |
1231 | if ((int64_t)Bindings.size() != TupleSize) { |
1232 | S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) |
1233 | << DecompType << (unsigned)Bindings.size() |
1234 | << (unsigned)TupleSize.getLimitedValue(UINT_MAX) |
1235 | << toString(TupleSize, 10) << (TupleSize < Bindings.size()); |
1236 | return true; |
1237 | } |
1238 | |
1239 | if (Bindings.empty()) |
1240 | return false; |
1241 | |
1242 | DeclarationName GetDN = S.PP.getIdentifierInfo(Name: "get" ); |
1243 | |
1244 | // [dcl.decomp]p3: |
1245 | // The unqualified-id get is looked up in the scope of E by class member |
1246 | // access lookup ... |
1247 | LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); |
1248 | bool UseMemberGet = false; |
1249 | if (S.isCompleteType(Loc: Src->getLocation(), T: DecompType)) { |
1250 | if (auto *RD = DecompType->getAsCXXRecordDecl()) |
1251 | S.LookupQualifiedName(MemberGet, RD); |
1252 | if (MemberGet.isAmbiguous()) |
1253 | return true; |
1254 | // ... and if that finds at least one declaration that is a function |
1255 | // template whose first template parameter is a non-type parameter ... |
1256 | for (NamedDecl *D : MemberGet) { |
1257 | if (FunctionTemplateDecl *FTD = |
1258 | dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { |
1259 | TemplateParameterList *TPL = FTD->getTemplateParameters(); |
1260 | if (TPL->size() != 0 && |
1261 | isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { |
1262 | // ... the initializer is e.get<i>(). |
1263 | UseMemberGet = true; |
1264 | break; |
1265 | } |
1266 | } |
1267 | } |
1268 | } |
1269 | |
1270 | unsigned I = 0; |
1271 | for (auto *B : Bindings) { |
1272 | InitializingBinding InitContext(S, B); |
1273 | SourceLocation Loc = B->getLocation(); |
1274 | |
1275 | ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); |
1276 | if (E.isInvalid()) |
1277 | return true; |
1278 | |
1279 | // e is an lvalue if the type of the entity is an lvalue reference and |
1280 | // an xvalue otherwise |
1281 | if (!Src->getType()->isLValueReferenceType()) |
1282 | E = ImplicitCastExpr::Create(Context: S.Context, T: E.get()->getType(), Kind: CK_NoOp, |
1283 | Operand: E.get(), BasePath: nullptr, Cat: VK_XValue, |
1284 | FPO: FPOptionsOverride()); |
1285 | |
1286 | TemplateArgumentListInfo Args(Loc, Loc); |
1287 | Args.addArgument( |
1288 | Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I)); |
1289 | |
1290 | if (UseMemberGet) { |
1291 | // if [lookup of member get] finds at least one declaration, the |
1292 | // initializer is e.get<i-1>(). |
1293 | E = S.BuildMemberReferenceExpr(Base: E.get(), BaseType: DecompType, OpLoc: Loc, IsArrow: false, |
1294 | SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr, |
1295 | R&: MemberGet, TemplateArgs: &Args, S: nullptr); |
1296 | if (E.isInvalid()) |
1297 | return true; |
1298 | |
1299 | E = S.BuildCallExpr(S: nullptr, Fn: E.get(), LParenLoc: Loc, ArgExprs: std::nullopt, RParenLoc: Loc); |
1300 | } else { |
1301 | // Otherwise, the initializer is get<i-1>(e), where get is looked up |
1302 | // in the associated namespaces. |
1303 | Expr *Get = UnresolvedLookupExpr::Create( |
1304 | Context: S.Context, NamingClass: nullptr, QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(), |
1305 | NameInfo: DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, Args: &Args, |
1306 | Begin: UnresolvedSetIterator(), End: UnresolvedSetIterator(), |
1307 | /*KnownDependent=*/false); |
1308 | |
1309 | Expr *Arg = E.get(); |
1310 | E = S.BuildCallExpr(S: nullptr, Fn: Get, LParenLoc: Loc, ArgExprs: Arg, RParenLoc: Loc); |
1311 | } |
1312 | if (E.isInvalid()) |
1313 | return true; |
1314 | Expr *Init = E.get(); |
1315 | |
1316 | // Given the type T designated by std::tuple_element<i - 1, E>::type, |
1317 | QualType T = getTupleLikeElementType(S, Loc, I, T: DecompType); |
1318 | if (T.isNull()) |
1319 | return true; |
1320 | |
1321 | // each vi is a variable of type "reference to T" initialized with the |
1322 | // initializer, where the reference is an lvalue reference if the |
1323 | // initializer is an lvalue and an rvalue reference otherwise |
1324 | QualType RefType = |
1325 | S.BuildReferenceType(T, LValueRef: E.get()->isLValue(), Loc, Entity: B->getDeclName()); |
1326 | if (RefType.isNull()) |
1327 | return true; |
1328 | auto *RefVD = VarDecl::Create( |
1329 | C&: S.Context, DC: Src->getDeclContext(), StartLoc: Loc, IdLoc: Loc, |
1330 | Id: B->getDeclName().getAsIdentifierInfo(), T: RefType, |
1331 | TInfo: S.Context.getTrivialTypeSourceInfo(T, Loc), S: Src->getStorageClass()); |
1332 | RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); |
1333 | RefVD->setTSCSpec(Src->getTSCSpec()); |
1334 | RefVD->setImplicit(); |
1335 | if (Src->isInlineSpecified()) |
1336 | RefVD->setInlineSpecified(); |
1337 | RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); |
1338 | |
1339 | InitializedEntity Entity = InitializedEntity::InitializeBinding(Binding: RefVD); |
1340 | InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Loc); |
1341 | InitializationSequence Seq(S, Entity, Kind, Init); |
1342 | E = Seq.Perform(S, Entity, Kind, Args: Init); |
1343 | if (E.isInvalid()) |
1344 | return true; |
1345 | E = S.ActOnFinishFullExpr(Expr: E.get(), CC: Loc, /*DiscardedValue*/ false); |
1346 | if (E.isInvalid()) |
1347 | return true; |
1348 | RefVD->setInit(E.get()); |
1349 | S.CheckCompleteVariableDeclaration(VD: RefVD); |
1350 | |
1351 | E = S.BuildDeclarationNameExpr(CXXScopeSpec(), |
1352 | DeclarationNameInfo(B->getDeclName(), Loc), |
1353 | RefVD); |
1354 | if (E.isInvalid()) |
1355 | return true; |
1356 | |
1357 | B->setBinding(DeclaredType: T, Binding: E.get()); |
1358 | I++; |
1359 | } |
1360 | |
1361 | return false; |
1362 | } |
1363 | |
1364 | /// Find the base class to decompose in a built-in decomposition of a class type. |
1365 | /// This base class search is, unfortunately, not quite like any other that we |
1366 | /// perform anywhere else in C++. |
1367 | static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, |
1368 | const CXXRecordDecl *RD, |
1369 | CXXCastPath &BasePath) { |
1370 | auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, |
1371 | CXXBasePath &Path) { |
1372 | return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); |
1373 | }; |
1374 | |
1375 | const CXXRecordDecl *ClassWithFields = nullptr; |
1376 | AccessSpecifier AS = AS_public; |
1377 | if (RD->hasDirectFields()) |
1378 | // [dcl.decomp]p4: |
1379 | // Otherwise, all of E's non-static data members shall be public direct |
1380 | // members of E ... |
1381 | ClassWithFields = RD; |
1382 | else { |
1383 | // ... or of ... |
1384 | CXXBasePaths Paths; |
1385 | Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); |
1386 | if (!RD->lookupInBases(BaseMatches: BaseHasFields, Paths)) { |
1387 | // If no classes have fields, just decompose RD itself. (This will work |
1388 | // if and only if zero bindings were provided.) |
1389 | return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); |
1390 | } |
1391 | |
1392 | CXXBasePath *BestPath = nullptr; |
1393 | for (auto &P : Paths) { |
1394 | if (!BestPath) |
1395 | BestPath = &P; |
1396 | else if (!S.Context.hasSameType(T1: P.back().Base->getType(), |
1397 | T2: BestPath->back().Base->getType())) { |
1398 | // ... the same ... |
1399 | S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) |
1400 | << false << RD << BestPath->back().Base->getType() |
1401 | << P.back().Base->getType(); |
1402 | return DeclAccessPair(); |
1403 | } else if (P.Access < BestPath->Access) { |
1404 | BestPath = &P; |
1405 | } |
1406 | } |
1407 | |
1408 | // ... unambiguous ... |
1409 | QualType BaseType = BestPath->back().Base->getType(); |
1410 | if (Paths.isAmbiguous(BaseType: S.Context.getCanonicalType(T: BaseType))) { |
1411 | S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) |
1412 | << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); |
1413 | return DeclAccessPair(); |
1414 | } |
1415 | |
1416 | // ... [accessible, implied by other rules] base class of E. |
1417 | S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), |
1418 | *BestPath, diag::err_decomp_decl_inaccessible_base); |
1419 | AS = BestPath->Access; |
1420 | |
1421 | ClassWithFields = BaseType->getAsCXXRecordDecl(); |
1422 | S.BuildBasePathArray(Paths, BasePath); |
1423 | } |
1424 | |
1425 | // The above search did not check whether the selected class itself has base |
1426 | // classes with fields, so check that now. |
1427 | CXXBasePaths Paths; |
1428 | if (ClassWithFields->lookupInBases(BaseMatches: BaseHasFields, Paths)) { |
1429 | S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) |
1430 | << (ClassWithFields == RD) << RD << ClassWithFields |
1431 | << Paths.front().back().Base->getType(); |
1432 | return DeclAccessPair(); |
1433 | } |
1434 | |
1435 | return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); |
1436 | } |
1437 | |
1438 | static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, |
1439 | ValueDecl *Src, QualType DecompType, |
1440 | const CXXRecordDecl *OrigRD) { |
1441 | if (S.RequireCompleteType(Src->getLocation(), DecompType, |
1442 | diag::err_incomplete_type)) |
1443 | return true; |
1444 | |
1445 | CXXCastPath BasePath; |
1446 | DeclAccessPair BasePair = |
1447 | findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); |
1448 | const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl()); |
1449 | if (!RD) |
1450 | return true; |
1451 | QualType BaseType = S.Context.getQualifiedType(T: S.Context.getRecordType(RD), |
1452 | Qs: DecompType.getQualifiers()); |
1453 | |
1454 | auto DiagnoseBadNumberOfBindings = [&]() -> bool { |
1455 | unsigned NumFields = llvm::count_if( |
1456 | RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitField(); }); |
1457 | assert(Bindings.size() != NumFields); |
1458 | S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) |
1459 | << DecompType << (unsigned)Bindings.size() << NumFields << NumFields |
1460 | << (NumFields < Bindings.size()); |
1461 | return true; |
1462 | }; |
1463 | |
1464 | // all of E's non-static data members shall be [...] well-formed |
1465 | // when named as e.name in the context of the structured binding, |
1466 | // E shall not have an anonymous union member, ... |
1467 | unsigned I = 0; |
1468 | for (auto *FD : RD->fields()) { |
1469 | if (FD->isUnnamedBitField()) |
1470 | continue; |
1471 | |
1472 | // All the non-static data members are required to be nameable, so they |
1473 | // must all have names. |
1474 | if (!FD->getDeclName()) { |
1475 | if (RD->isLambda()) { |
1476 | S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda); |
1477 | S.Diag(RD->getLocation(), diag::note_lambda_decl); |
1478 | return true; |
1479 | } |
1480 | |
1481 | if (FD->isAnonymousStructOrUnion()) { |
1482 | S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) |
1483 | << DecompType << FD->getType()->isUnionType(); |
1484 | S.Diag(FD->getLocation(), diag::note_declared_at); |
1485 | return true; |
1486 | } |
1487 | |
1488 | // FIXME: Are there any other ways we could have an anonymous member? |
1489 | } |
1490 | |
1491 | // We have a real field to bind. |
1492 | if (I >= Bindings.size()) |
1493 | return DiagnoseBadNumberOfBindings(); |
1494 | auto *B = Bindings[I++]; |
1495 | SourceLocation Loc = B->getLocation(); |
1496 | |
1497 | // The field must be accessible in the context of the structured binding. |
1498 | // We already checked that the base class is accessible. |
1499 | // FIXME: Add 'const' to AccessedEntity's classes so we can remove the |
1500 | // const_cast here. |
1501 | S.CheckStructuredBindingMemberAccess( |
1502 | Loc, const_cast<CXXRecordDecl *>(OrigRD), |
1503 | DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( |
1504 | BasePair.getAccess(), FD->getAccess()))); |
1505 | |
1506 | // Initialize the binding to Src.FD. |
1507 | ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); |
1508 | if (E.isInvalid()) |
1509 | return true; |
1510 | E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, |
1511 | VK_LValue, &BasePath); |
1512 | if (E.isInvalid()) |
1513 | return true; |
1514 | E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, |
1515 | CXXScopeSpec(), FD, |
1516 | DeclAccessPair::make(FD, FD->getAccess()), |
1517 | DeclarationNameInfo(FD->getDeclName(), Loc)); |
1518 | if (E.isInvalid()) |
1519 | return true; |
1520 | |
1521 | // If the type of the member is T, the referenced type is cv T, where cv is |
1522 | // the cv-qualification of the decomposition expression. |
1523 | // |
1524 | // FIXME: We resolve a defect here: if the field is mutable, we do not add |
1525 | // 'const' to the type of the field. |
1526 | Qualifiers Q = DecompType.getQualifiers(); |
1527 | if (FD->isMutable()) |
1528 | Q.removeConst(); |
1529 | B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); |
1530 | } |
1531 | |
1532 | if (I != Bindings.size()) |
1533 | return DiagnoseBadNumberOfBindings(); |
1534 | |
1535 | return false; |
1536 | } |
1537 | |
1538 | void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { |
1539 | QualType DecompType = DD->getType(); |
1540 | |
1541 | // If the type of the decomposition is dependent, then so is the type of |
1542 | // each binding. |
1543 | if (DecompType->isDependentType()) { |
1544 | for (auto *B : DD->bindings()) |
1545 | B->setType(Context.DependentTy); |
1546 | return; |
1547 | } |
1548 | |
1549 | DecompType = DecompType.getNonReferenceType(); |
1550 | ArrayRef<BindingDecl*> Bindings = DD->bindings(); |
1551 | |
1552 | // C++1z [dcl.decomp]/2: |
1553 | // If E is an array type [...] |
1554 | // As an extension, we also support decomposition of built-in complex and |
1555 | // vector types. |
1556 | if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { |
1557 | if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) |
1558 | DD->setInvalidDecl(); |
1559 | return; |
1560 | } |
1561 | if (auto *VT = DecompType->getAs<VectorType>()) { |
1562 | if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) |
1563 | DD->setInvalidDecl(); |
1564 | return; |
1565 | } |
1566 | if (auto *CT = DecompType->getAs<ComplexType>()) { |
1567 | if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) |
1568 | DD->setInvalidDecl(); |
1569 | return; |
1570 | } |
1571 | |
1572 | // C++1z [dcl.decomp]/3: |
1573 | // if the expression std::tuple_size<E>::value is a well-formed integral |
1574 | // constant expression, [...] |
1575 | llvm::APSInt TupleSize(32); |
1576 | switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { |
1577 | case IsTupleLike::Error: |
1578 | DD->setInvalidDecl(); |
1579 | return; |
1580 | |
1581 | case IsTupleLike::TupleLike: |
1582 | if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) |
1583 | DD->setInvalidDecl(); |
1584 | return; |
1585 | |
1586 | case IsTupleLike::NotTupleLike: |
1587 | break; |
1588 | } |
1589 | |
1590 | // C++1z [dcl.dcl]/8: |
1591 | // [E shall be of array or non-union class type] |
1592 | CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); |
1593 | if (!RD || RD->isUnion()) { |
1594 | Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) |
1595 | << DD << !RD << DecompType; |
1596 | DD->setInvalidDecl(); |
1597 | return; |
1598 | } |
1599 | |
1600 | // C++1z [dcl.decomp]/4: |
1601 | // all of E's non-static data members shall be [...] direct members of |
1602 | // E or of the same unambiguous public base class of E, ... |
1603 | if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) |
1604 | DD->setInvalidDecl(); |
1605 | } |
1606 | |
1607 | /// Merge the exception specifications of two variable declarations. |
1608 | /// |
1609 | /// This is called when there's a redeclaration of a VarDecl. The function |
1610 | /// checks if the redeclaration might have an exception specification and |
1611 | /// validates compatibility and merges the specs if necessary. |
1612 | void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { |
1613 | // Shortcut if exceptions are disabled. |
1614 | if (!getLangOpts().CXXExceptions) |
1615 | return; |
1616 | |
1617 | assert(Context.hasSameType(New->getType(), Old->getType()) && |
1618 | "Should only be called if types are otherwise the same." ); |
1619 | |
1620 | QualType NewType = New->getType(); |
1621 | QualType OldType = Old->getType(); |
1622 | |
1623 | // We're only interested in pointers and references to functions, as well |
1624 | // as pointers to member functions. |
1625 | if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { |
1626 | NewType = R->getPointeeType(); |
1627 | OldType = OldType->castAs<ReferenceType>()->getPointeeType(); |
1628 | } else if (const PointerType *P = NewType->getAs<PointerType>()) { |
1629 | NewType = P->getPointeeType(); |
1630 | OldType = OldType->castAs<PointerType>()->getPointeeType(); |
1631 | } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { |
1632 | NewType = M->getPointeeType(); |
1633 | OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); |
1634 | } |
1635 | |
1636 | if (!NewType->isFunctionProtoType()) |
1637 | return; |
1638 | |
1639 | // There's lots of special cases for functions. For function pointers, system |
1640 | // libraries are hopefully not as broken so that we don't need these |
1641 | // workarounds. |
1642 | if (CheckEquivalentExceptionSpec( |
1643 | OldType->getAs<FunctionProtoType>(), Old->getLocation(), |
1644 | NewType->getAs<FunctionProtoType>(), New->getLocation())) { |
1645 | New->setInvalidDecl(); |
1646 | } |
1647 | } |
1648 | |
1649 | /// CheckCXXDefaultArguments - Verify that the default arguments for a |
1650 | /// function declaration are well-formed according to C++ |
1651 | /// [dcl.fct.default]. |
1652 | void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { |
1653 | unsigned NumParams = FD->getNumParams(); |
1654 | unsigned ParamIdx = 0; |
1655 | |
1656 | // This checking doesn't make sense for explicit specializations; their |
1657 | // default arguments are determined by the declaration we're specializing, |
1658 | // not by FD. |
1659 | if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) |
1660 | return; |
1661 | if (auto *FTD = FD->getDescribedFunctionTemplate()) |
1662 | if (FTD->isMemberSpecialization()) |
1663 | return; |
1664 | |
1665 | // Find first parameter with a default argument |
1666 | for (; ParamIdx < NumParams; ++ParamIdx) { |
1667 | ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx); |
1668 | if (Param->hasDefaultArg()) |
1669 | break; |
1670 | } |
1671 | |
1672 | // C++20 [dcl.fct.default]p4: |
1673 | // In a given function declaration, each parameter subsequent to a parameter |
1674 | // with a default argument shall have a default argument supplied in this or |
1675 | // a previous declaration, unless the parameter was expanded from a |
1676 | // parameter pack, or shall be a function parameter pack. |
1677 | for (; ParamIdx < NumParams; ++ParamIdx) { |
1678 | ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx); |
1679 | if (!Param->hasDefaultArg() && !Param->isParameterPack() && |
1680 | !(CurrentInstantiationScope && |
1681 | CurrentInstantiationScope->isLocalPackExpansion(Param))) { |
1682 | if (Param->isInvalidDecl()) |
1683 | /* We already complained about this parameter. */; |
1684 | else if (Param->getIdentifier()) |
1685 | Diag(Param->getLocation(), |
1686 | diag::err_param_default_argument_missing_name) |
1687 | << Param->getIdentifier(); |
1688 | else |
1689 | Diag(Param->getLocation(), |
1690 | diag::err_param_default_argument_missing); |
1691 | } |
1692 | } |
1693 | } |
1694 | |
1695 | /// Check that the given type is a literal type. Issue a diagnostic if not, |
1696 | /// if Kind is Diagnose. |
1697 | /// \return \c true if a problem has been found (and optionally diagnosed). |
1698 | template <typename... Ts> |
1699 | static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, |
1700 | SourceLocation Loc, QualType T, unsigned DiagID, |
1701 | Ts &&...DiagArgs) { |
1702 | if (T->isDependentType()) |
1703 | return false; |
1704 | |
1705 | switch (Kind) { |
1706 | case Sema::CheckConstexprKind::Diagnose: |
1707 | return SemaRef.RequireLiteralType(Loc, T, DiagID, |
1708 | std::forward<Ts>(DiagArgs)...); |
1709 | |
1710 | case Sema::CheckConstexprKind::CheckValid: |
1711 | return !T->isLiteralType(Ctx: SemaRef.Context); |
1712 | } |
1713 | |
1714 | llvm_unreachable("unknown CheckConstexprKind" ); |
1715 | } |
1716 | |
1717 | /// Determine whether a destructor cannot be constexpr due to |
1718 | static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, |
1719 | const CXXDestructorDecl *DD, |
1720 | Sema::CheckConstexprKind Kind) { |
1721 | assert(!SemaRef.getLangOpts().CPlusPlus23 && |
1722 | "this check is obsolete for C++23" ); |
1723 | auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { |
1724 | const CXXRecordDecl *RD = |
1725 | T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); |
1726 | if (!RD || RD->hasConstexprDestructor()) |
1727 | return true; |
1728 | |
1729 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
1730 | SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) |
1731 | << static_cast<int>(DD->getConstexprKind()) << !FD |
1732 | << (FD ? FD->getDeclName() : DeclarationName()) << T; |
1733 | SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) |
1734 | << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; |
1735 | } |
1736 | return false; |
1737 | }; |
1738 | |
1739 | const CXXRecordDecl *RD = DD->getParent(); |
1740 | for (const CXXBaseSpecifier &B : RD->bases()) |
1741 | if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) |
1742 | return false; |
1743 | for (const FieldDecl *FD : RD->fields()) |
1744 | if (!Check(FD->getLocation(), FD->getType(), FD)) |
1745 | return false; |
1746 | return true; |
1747 | } |
1748 | |
1749 | /// Check whether a function's parameter types are all literal types. If so, |
1750 | /// return true. If not, produce a suitable diagnostic and return false. |
1751 | static bool CheckConstexprParameterTypes(Sema &SemaRef, |
1752 | const FunctionDecl *FD, |
1753 | Sema::CheckConstexprKind Kind) { |
1754 | assert(!SemaRef.getLangOpts().CPlusPlus23 && |
1755 | "this check is obsolete for C++23" ); |
1756 | unsigned ArgIndex = 0; |
1757 | const auto *FT = FD->getType()->castAs<FunctionProtoType>(); |
1758 | for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), |
1759 | e = FT->param_type_end(); |
1760 | i != e; ++i, ++ArgIndex) { |
1761 | const ParmVarDecl *PD = FD->getParamDecl(i: ArgIndex); |
1762 | assert(PD && "null in a parameter list" ); |
1763 | SourceLocation ParamLoc = PD->getLocation(); |
1764 | if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, |
1765 | diag::err_constexpr_non_literal_param, ArgIndex + 1, |
1766 | PD->getSourceRange(), isa<CXXConstructorDecl>(FD), |
1767 | FD->isConsteval())) |
1768 | return false; |
1769 | } |
1770 | return true; |
1771 | } |
1772 | |
1773 | /// Check whether a function's return type is a literal type. If so, return |
1774 | /// true. If not, produce a suitable diagnostic and return false. |
1775 | static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, |
1776 | Sema::CheckConstexprKind Kind) { |
1777 | assert(!SemaRef.getLangOpts().CPlusPlus23 && |
1778 | "this check is obsolete for C++23" ); |
1779 | if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), |
1780 | diag::err_constexpr_non_literal_return, |
1781 | FD->isConsteval())) |
1782 | return false; |
1783 | return true; |
1784 | } |
1785 | |
1786 | /// Get diagnostic %select index for tag kind for |
1787 | /// record diagnostic message. |
1788 | /// WARNING: Indexes apply to particular diagnostics only! |
1789 | /// |
1790 | /// \returns diagnostic %select index. |
1791 | static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { |
1792 | switch (Tag) { |
1793 | case TagTypeKind::Struct: |
1794 | return 0; |
1795 | case TagTypeKind::Interface: |
1796 | return 1; |
1797 | case TagTypeKind::Class: |
1798 | return 2; |
1799 | default: llvm_unreachable("Invalid tag kind for record diagnostic!" ); |
1800 | } |
1801 | } |
1802 | |
1803 | static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, |
1804 | Stmt *Body, |
1805 | Sema::CheckConstexprKind Kind); |
1806 | |
1807 | // Check whether a function declaration satisfies the requirements of a |
1808 | // constexpr function definition or a constexpr constructor definition. If so, |
1809 | // return true. If not, produce appropriate diagnostics (unless asked not to by |
1810 | // Kind) and return false. |
1811 | // |
1812 | // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. |
1813 | bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, |
1814 | CheckConstexprKind Kind) { |
1815 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD); |
1816 | if (MD && MD->isInstance()) { |
1817 | // C++11 [dcl.constexpr]p4: |
1818 | // The definition of a constexpr constructor shall satisfy the following |
1819 | // constraints: |
1820 | // - the class shall not have any virtual base classes; |
1821 | // |
1822 | // FIXME: This only applies to constructors and destructors, not arbitrary |
1823 | // member functions. |
1824 | const CXXRecordDecl *RD = MD->getParent(); |
1825 | if (RD->getNumVBases()) { |
1826 | if (Kind == CheckConstexprKind::CheckValid) |
1827 | return false; |
1828 | |
1829 | Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) |
1830 | << isa<CXXConstructorDecl>(NewFD) |
1831 | << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); |
1832 | for (const auto &I : RD->vbases()) |
1833 | Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) |
1834 | << I.getSourceRange(); |
1835 | return false; |
1836 | } |
1837 | } |
1838 | |
1839 | if (!isa<CXXConstructorDecl>(Val: NewFD)) { |
1840 | // C++11 [dcl.constexpr]p3: |
1841 | // The definition of a constexpr function shall satisfy the following |
1842 | // constraints: |
1843 | // - it shall not be virtual; (removed in C++20) |
1844 | const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD); |
1845 | if (Method && Method->isVirtual()) { |
1846 | if (getLangOpts().CPlusPlus20) { |
1847 | if (Kind == CheckConstexprKind::Diagnose) |
1848 | Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); |
1849 | } else { |
1850 | if (Kind == CheckConstexprKind::CheckValid) |
1851 | return false; |
1852 | |
1853 | Method = Method->getCanonicalDecl(); |
1854 | Diag(Method->getLocation(), diag::err_constexpr_virtual); |
1855 | |
1856 | // If it's not obvious why this function is virtual, find an overridden |
1857 | // function which uses the 'virtual' keyword. |
1858 | const CXXMethodDecl *WrittenVirtual = Method; |
1859 | while (!WrittenVirtual->isVirtualAsWritten()) |
1860 | WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); |
1861 | if (WrittenVirtual != Method) |
1862 | Diag(WrittenVirtual->getLocation(), |
1863 | diag::note_overridden_virtual_function); |
1864 | return false; |
1865 | } |
1866 | } |
1867 | |
1868 | // - its return type shall be a literal type; (removed in C++23) |
1869 | if (!getLangOpts().CPlusPlus23 && |
1870 | !CheckConstexprReturnType(SemaRef&: *this, FD: NewFD, Kind)) |
1871 | return false; |
1872 | } |
1873 | |
1874 | if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: NewFD)) { |
1875 | // A destructor can be constexpr only if the defaulted destructor could be; |
1876 | // we don't need to check the members and bases if we already know they all |
1877 | // have constexpr destructors. (removed in C++23) |
1878 | if (!getLangOpts().CPlusPlus23 && |
1879 | !Dtor->getParent()->defaultedDestructorIsConstexpr()) { |
1880 | if (Kind == CheckConstexprKind::CheckValid) |
1881 | return false; |
1882 | if (!CheckConstexprDestructorSubobjects(SemaRef&: *this, DD: Dtor, Kind)) |
1883 | return false; |
1884 | } |
1885 | } |
1886 | |
1887 | // - each of its parameter types shall be a literal type; (removed in C++23) |
1888 | if (!getLangOpts().CPlusPlus23 && |
1889 | !CheckConstexprParameterTypes(SemaRef&: *this, FD: NewFD, Kind)) |
1890 | return false; |
1891 | |
1892 | Stmt *Body = NewFD->getBody(); |
1893 | assert(Body && |
1894 | "CheckConstexprFunctionDefinition called on function with no body" ); |
1895 | return CheckConstexprFunctionBody(SemaRef&: *this, Dcl: NewFD, Body, Kind); |
1896 | } |
1897 | |
1898 | /// Check the given declaration statement is legal within a constexpr function |
1899 | /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. |
1900 | /// |
1901 | /// \return true if the body is OK (maybe only as an extension), false if we |
1902 | /// have diagnosed a problem. |
1903 | static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, |
1904 | DeclStmt *DS, SourceLocation &Cxx1yLoc, |
1905 | Sema::CheckConstexprKind Kind) { |
1906 | // C++11 [dcl.constexpr]p3 and p4: |
1907 | // The definition of a constexpr function(p3) or constructor(p4) [...] shall |
1908 | // contain only |
1909 | for (const auto *DclIt : DS->decls()) { |
1910 | switch (DclIt->getKind()) { |
1911 | case Decl::StaticAssert: |
1912 | case Decl::Using: |
1913 | case Decl::UsingShadow: |
1914 | case Decl::UsingDirective: |
1915 | case Decl::UnresolvedUsingTypename: |
1916 | case Decl::UnresolvedUsingValue: |
1917 | case Decl::UsingEnum: |
1918 | // - static_assert-declarations |
1919 | // - using-declarations, |
1920 | // - using-directives, |
1921 | // - using-enum-declaration |
1922 | continue; |
1923 | |
1924 | case Decl::Typedef: |
1925 | case Decl::TypeAlias: { |
1926 | // - typedef declarations and alias-declarations that do not define |
1927 | // classes or enumerations, |
1928 | const auto *TN = cast<TypedefNameDecl>(Val: DclIt); |
1929 | if (TN->getUnderlyingType()->isVariablyModifiedType()) { |
1930 | // Don't allow variably-modified types in constexpr functions. |
1931 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
1932 | TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); |
1933 | SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) |
1934 | << TL.getSourceRange() << TL.getType() |
1935 | << isa<CXXConstructorDecl>(Dcl); |
1936 | } |
1937 | return false; |
1938 | } |
1939 | continue; |
1940 | } |
1941 | |
1942 | case Decl::Enum: |
1943 | case Decl::CXXRecord: |
1944 | // C++1y allows types to be defined, not just declared. |
1945 | if (cast<TagDecl>(Val: DclIt)->isThisDeclarationADefinition()) { |
1946 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
1947 | SemaRef.Diag(DS->getBeginLoc(), |
1948 | SemaRef.getLangOpts().CPlusPlus14 |
1949 | ? diag::warn_cxx11_compat_constexpr_type_definition |
1950 | : diag::ext_constexpr_type_definition) |
1951 | << isa<CXXConstructorDecl>(Dcl); |
1952 | } else if (!SemaRef.getLangOpts().CPlusPlus14) { |
1953 | return false; |
1954 | } |
1955 | } |
1956 | continue; |
1957 | |
1958 | case Decl::EnumConstant: |
1959 | case Decl::IndirectField: |
1960 | case Decl::ParmVar: |
1961 | // These can only appear with other declarations which are banned in |
1962 | // C++11 and permitted in C++1y, so ignore them. |
1963 | continue; |
1964 | |
1965 | case Decl::Var: |
1966 | case Decl::Decomposition: { |
1967 | // C++1y [dcl.constexpr]p3 allows anything except: |
1968 | // a definition of a variable of non-literal type or of static or |
1969 | // thread storage duration or [before C++2a] for which no |
1970 | // initialization is performed. |
1971 | const auto *VD = cast<VarDecl>(Val: DclIt); |
1972 | if (VD->isThisDeclarationADefinition()) { |
1973 | if (VD->isStaticLocal()) { |
1974 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
1975 | SemaRef.Diag(VD->getLocation(), |
1976 | SemaRef.getLangOpts().CPlusPlus23 |
1977 | ? diag::warn_cxx20_compat_constexpr_var |
1978 | : diag::ext_constexpr_static_var) |
1979 | << isa<CXXConstructorDecl>(Dcl) |
1980 | << (VD->getTLSKind() == VarDecl::TLS_Dynamic); |
1981 | } else if (!SemaRef.getLangOpts().CPlusPlus23) { |
1982 | return false; |
1983 | } |
1984 | } |
1985 | if (SemaRef.LangOpts.CPlusPlus23) { |
1986 | CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), |
1987 | diag::warn_cxx20_compat_constexpr_var, |
1988 | isa<CXXConstructorDecl>(Dcl), |
1989 | /*variable of non-literal type*/ 2); |
1990 | } else if (CheckLiteralType( |
1991 | SemaRef, Kind, VD->getLocation(), VD->getType(), |
1992 | diag::err_constexpr_local_var_non_literal_type, |
1993 | isa<CXXConstructorDecl>(Dcl))) { |
1994 | return false; |
1995 | } |
1996 | if (!VD->getType()->isDependentType() && |
1997 | !VD->hasInit() && !VD->isCXXForRangeDecl()) { |
1998 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
1999 | SemaRef.Diag( |
2000 | VD->getLocation(), |
2001 | SemaRef.getLangOpts().CPlusPlus20 |
2002 | ? diag::warn_cxx17_compat_constexpr_local_var_no_init |
2003 | : diag::ext_constexpr_local_var_no_init) |
2004 | << isa<CXXConstructorDecl>(Dcl); |
2005 | } else if (!SemaRef.getLangOpts().CPlusPlus20) { |
2006 | return false; |
2007 | } |
2008 | continue; |
2009 | } |
2010 | } |
2011 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
2012 | SemaRef.Diag(VD->getLocation(), |
2013 | SemaRef.getLangOpts().CPlusPlus14 |
2014 | ? diag::warn_cxx11_compat_constexpr_local_var |
2015 | : diag::ext_constexpr_local_var) |
2016 | << isa<CXXConstructorDecl>(Dcl); |
2017 | } else if (!SemaRef.getLangOpts().CPlusPlus14) { |
2018 | return false; |
2019 | } |
2020 | continue; |
2021 | } |
2022 | |
2023 | case Decl::NamespaceAlias: |
2024 | case Decl::Function: |
2025 | // These are disallowed in C++11 and permitted in C++1y. Allow them |
2026 | // everywhere as an extension. |
2027 | if (!Cxx1yLoc.isValid()) |
2028 | Cxx1yLoc = DS->getBeginLoc(); |
2029 | continue; |
2030 | |
2031 | default: |
2032 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
2033 | SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) |
2034 | << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); |
2035 | } |
2036 | return false; |
2037 | } |
2038 | } |
2039 | |
2040 | return true; |
2041 | } |
2042 | |
2043 | /// Check that the given field is initialized within a constexpr constructor. |
2044 | /// |
2045 | /// \param Dcl The constexpr constructor being checked. |
2046 | /// \param Field The field being checked. This may be a member of an anonymous |
2047 | /// struct or union nested within the class being checked. |
2048 | /// \param Inits All declarations, including anonymous struct/union members and |
2049 | /// indirect members, for which any initialization was provided. |
2050 | /// \param Diagnosed Whether we've emitted the error message yet. Used to attach |
2051 | /// multiple notes for different members to the same error. |
2052 | /// \param Kind Whether we're diagnosing a constructor as written or determining |
2053 | /// whether the formal requirements are satisfied. |
2054 | /// \return \c false if we're checking for validity and the constructor does |
2055 | /// not satisfy the requirements on a constexpr constructor. |
2056 | static bool CheckConstexprCtorInitializer(Sema &SemaRef, |
2057 | const FunctionDecl *Dcl, |
2058 | FieldDecl *Field, |
2059 | llvm::SmallSet<Decl*, 16> &Inits, |
2060 | bool &Diagnosed, |
2061 | Sema::CheckConstexprKind Kind) { |
2062 | // In C++20 onwards, there's nothing to check for validity. |
2063 | if (Kind == Sema::CheckConstexprKind::CheckValid && |
2064 | SemaRef.getLangOpts().CPlusPlus20) |
2065 | return true; |
2066 | |
2067 | if (Field->isInvalidDecl()) |
2068 | return true; |
2069 | |
2070 | if (Field->isUnnamedBitField()) |
2071 | return true; |
2072 | |
2073 | // Anonymous unions with no variant members and empty anonymous structs do not |
2074 | // need to be explicitly initialized. FIXME: Anonymous structs that contain no |
2075 | // indirect fields don't need initializing. |
2076 | if (Field->isAnonymousStructOrUnion() && |
2077 | (Field->getType()->isUnionType() |
2078 | ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() |
2079 | : Field->getType()->getAsCXXRecordDecl()->isEmpty())) |
2080 | return true; |
2081 | |
2082 | if (!Inits.count(Field)) { |
2083 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
2084 | if (!Diagnosed) { |
2085 | SemaRef.Diag(Dcl->getLocation(), |
2086 | SemaRef.getLangOpts().CPlusPlus20 |
2087 | ? diag::warn_cxx17_compat_constexpr_ctor_missing_init |
2088 | : diag::ext_constexpr_ctor_missing_init); |
2089 | Diagnosed = true; |
2090 | } |
2091 | SemaRef.Diag(Field->getLocation(), |
2092 | diag::note_constexpr_ctor_missing_init); |
2093 | } else if (!SemaRef.getLangOpts().CPlusPlus20) { |
2094 | return false; |
2095 | } |
2096 | } else if (Field->isAnonymousStructOrUnion()) { |
2097 | const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); |
2098 | for (auto *I : RD->fields()) |
2099 | // If an anonymous union contains an anonymous struct of which any member |
2100 | // is initialized, all members must be initialized. |
2101 | if (!RD->isUnion() || Inits.count(I)) |
2102 | if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, |
2103 | Kind)) |
2104 | return false; |
2105 | } |
2106 | return true; |
2107 | } |
2108 | |
2109 | /// Check the provided statement is allowed in a constexpr function |
2110 | /// definition. |
2111 | static bool |
2112 | CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, |
2113 | SmallVectorImpl<SourceLocation> &ReturnStmts, |
2114 | SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, |
2115 | SourceLocation &Cxx2bLoc, |
2116 | Sema::CheckConstexprKind Kind) { |
2117 | // - its function-body shall be [...] a compound-statement that contains only |
2118 | switch (S->getStmtClass()) { |
2119 | case Stmt::NullStmtClass: |
2120 | // - null statements, |
2121 | return true; |
2122 | |
2123 | case Stmt::DeclStmtClass: |
2124 | // - static_assert-declarations |
2125 | // - using-declarations, |
2126 | // - using-directives, |
2127 | // - typedef declarations and alias-declarations that do not define |
2128 | // classes or enumerations, |
2129 | if (!CheckConstexprDeclStmt(SemaRef, Dcl, DS: cast<DeclStmt>(Val: S), Cxx1yLoc, Kind)) |
2130 | return false; |
2131 | return true; |
2132 | |
2133 | case Stmt::ReturnStmtClass: |
2134 | // - and exactly one return statement; |
2135 | if (isa<CXXConstructorDecl>(Val: Dcl)) { |
2136 | // C++1y allows return statements in constexpr constructors. |
2137 | if (!Cxx1yLoc.isValid()) |
2138 | Cxx1yLoc = S->getBeginLoc(); |
2139 | return true; |
2140 | } |
2141 | |
2142 | ReturnStmts.push_back(Elt: S->getBeginLoc()); |
2143 | return true; |
2144 | |
2145 | case Stmt::AttributedStmtClass: |
2146 | // Attributes on a statement don't affect its formal kind and hence don't |
2147 | // affect its validity in a constexpr function. |
2148 | return CheckConstexprFunctionStmt( |
2149 | SemaRef, Dcl, S: cast<AttributedStmt>(Val: S)->getSubStmt(), ReturnStmts, |
2150 | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind); |
2151 | |
2152 | case Stmt::CompoundStmtClass: { |
2153 | // C++1y allows compound-statements. |
2154 | if (!Cxx1yLoc.isValid()) |
2155 | Cxx1yLoc = S->getBeginLoc(); |
2156 | |
2157 | CompoundStmt *CompStmt = cast<CompoundStmt>(Val: S); |
2158 | for (auto *BodyIt : CompStmt->body()) { |
2159 | if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: BodyIt, ReturnStmts, |
2160 | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2161 | return false; |
2162 | } |
2163 | return true; |
2164 | } |
2165 | |
2166 | case Stmt::IfStmtClass: { |
2167 | // C++1y allows if-statements. |
2168 | if (!Cxx1yLoc.isValid()) |
2169 | Cxx1yLoc = S->getBeginLoc(); |
2170 | |
2171 | IfStmt *If = cast<IfStmt>(Val: S); |
2172 | if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getThen(), ReturnStmts, |
2173 | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2174 | return false; |
2175 | if (If->getElse() && |
2176 | !CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getElse(), ReturnStmts, |
2177 | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2178 | return false; |
2179 | return true; |
2180 | } |
2181 | |
2182 | case Stmt::WhileStmtClass: |
2183 | case Stmt::DoStmtClass: |
2184 | case Stmt::ForStmtClass: |
2185 | case Stmt::CXXForRangeStmtClass: |
2186 | case Stmt::ContinueStmtClass: |
2187 | // C++1y allows all of these. We don't allow them as extensions in C++11, |
2188 | // because they don't make sense without variable mutation. |
2189 | if (!SemaRef.getLangOpts().CPlusPlus14) |
2190 | break; |
2191 | if (!Cxx1yLoc.isValid()) |
2192 | Cxx1yLoc = S->getBeginLoc(); |
2193 | for (Stmt *SubStmt : S->children()) { |
2194 | if (SubStmt && |
2195 | !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts, |
2196 | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2197 | return false; |
2198 | } |
2199 | return true; |
2200 | |
2201 | case Stmt::SwitchStmtClass: |
2202 | case Stmt::CaseStmtClass: |
2203 | case Stmt::DefaultStmtClass: |
2204 | case Stmt::BreakStmtClass: |
2205 | // C++1y allows switch-statements, and since they don't need variable |
2206 | // mutation, we can reasonably allow them in C++11 as an extension. |
2207 | if (!Cxx1yLoc.isValid()) |
2208 | Cxx1yLoc = S->getBeginLoc(); |
2209 | for (Stmt *SubStmt : S->children()) { |
2210 | if (SubStmt && |
2211 | !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts, |
2212 | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2213 | return false; |
2214 | } |
2215 | return true; |
2216 | |
2217 | case Stmt::LabelStmtClass: |
2218 | case Stmt::GotoStmtClass: |
2219 | if (Cxx2bLoc.isInvalid()) |
2220 | Cxx2bLoc = S->getBeginLoc(); |
2221 | for (Stmt *SubStmt : S->children()) { |
2222 | if (SubStmt && |
2223 | !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts, |
2224 | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2225 | return false; |
2226 | } |
2227 | return true; |
2228 | |
2229 | case Stmt::GCCAsmStmtClass: |
2230 | case Stmt::MSAsmStmtClass: |
2231 | // C++2a allows inline assembly statements. |
2232 | case Stmt::CXXTryStmtClass: |
2233 | if (Cxx2aLoc.isInvalid()) |
2234 | Cxx2aLoc = S->getBeginLoc(); |
2235 | for (Stmt *SubStmt : S->children()) { |
2236 | if (SubStmt && |
2237 | !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts, |
2238 | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2239 | return false; |
2240 | } |
2241 | return true; |
2242 | |
2243 | case Stmt::CXXCatchStmtClass: |
2244 | // Do not bother checking the language mode (already covered by the |
2245 | // try block check). |
2246 | if (!CheckConstexprFunctionStmt( |
2247 | SemaRef, Dcl, S: cast<CXXCatchStmt>(Val: S)->getHandlerBlock(), ReturnStmts, |
2248 | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2249 | return false; |
2250 | return true; |
2251 | |
2252 | default: |
2253 | if (!isa<Expr>(Val: S)) |
2254 | break; |
2255 | |
2256 | // C++1y allows expression-statements. |
2257 | if (!Cxx1yLoc.isValid()) |
2258 | Cxx1yLoc = S->getBeginLoc(); |
2259 | return true; |
2260 | } |
2261 | |
2262 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
2263 | SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) |
2264 | << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); |
2265 | } |
2266 | return false; |
2267 | } |
2268 | |
2269 | /// Check the body for the given constexpr function declaration only contains |
2270 | /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. |
2271 | /// |
2272 | /// \return true if the body is OK, false if we have found or diagnosed a |
2273 | /// problem. |
2274 | static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, |
2275 | Stmt *Body, |
2276 | Sema::CheckConstexprKind Kind) { |
2277 | SmallVector<SourceLocation, 4> ReturnStmts; |
2278 | |
2279 | if (isa<CXXTryStmt>(Val: Body)) { |
2280 | // C++11 [dcl.constexpr]p3: |
2281 | // The definition of a constexpr function shall satisfy the following |
2282 | // constraints: [...] |
2283 | // - its function-body shall be = delete, = default, or a |
2284 | // compound-statement |
2285 | // |
2286 | // C++11 [dcl.constexpr]p4: |
2287 | // In the definition of a constexpr constructor, [...] |
2288 | // - its function-body shall not be a function-try-block; |
2289 | // |
2290 | // This restriction is lifted in C++2a, as long as inner statements also |
2291 | // apply the general constexpr rules. |
2292 | switch (Kind) { |
2293 | case Sema::CheckConstexprKind::CheckValid: |
2294 | if (!SemaRef.getLangOpts().CPlusPlus20) |
2295 | return false; |
2296 | break; |
2297 | |
2298 | case Sema::CheckConstexprKind::Diagnose: |
2299 | SemaRef.Diag(Body->getBeginLoc(), |
2300 | !SemaRef.getLangOpts().CPlusPlus20 |
2301 | ? diag::ext_constexpr_function_try_block_cxx20 |
2302 | : diag::warn_cxx17_compat_constexpr_function_try_block) |
2303 | << isa<CXXConstructorDecl>(Dcl); |
2304 | break; |
2305 | } |
2306 | } |
2307 | |
2308 | // - its function-body shall be [...] a compound-statement that contains only |
2309 | // [... list of cases ...] |
2310 | // |
2311 | // Note that walking the children here is enough to properly check for |
2312 | // CompoundStmt and CXXTryStmt body. |
2313 | SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc; |
2314 | for (Stmt *SubStmt : Body->children()) { |
2315 | if (SubStmt && |
2316 | !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts, |
2317 | Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind)) |
2318 | return false; |
2319 | } |
2320 | |
2321 | if (Kind == Sema::CheckConstexprKind::CheckValid) { |
2322 | // If this is only valid as an extension, report that we don't satisfy the |
2323 | // constraints of the current language. |
2324 | if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) || |
2325 | (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || |
2326 | (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) |
2327 | return false; |
2328 | } else if (Cxx2bLoc.isValid()) { |
2329 | SemaRef.Diag(Cxx2bLoc, |
2330 | SemaRef.getLangOpts().CPlusPlus23 |
2331 | ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt |
2332 | : diag::ext_constexpr_body_invalid_stmt_cxx23) |
2333 | << isa<CXXConstructorDecl>(Dcl); |
2334 | } else if (Cxx2aLoc.isValid()) { |
2335 | SemaRef.Diag(Cxx2aLoc, |
2336 | SemaRef.getLangOpts().CPlusPlus20 |
2337 | ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt |
2338 | : diag::ext_constexpr_body_invalid_stmt_cxx20) |
2339 | << isa<CXXConstructorDecl>(Dcl); |
2340 | } else if (Cxx1yLoc.isValid()) { |
2341 | SemaRef.Diag(Cxx1yLoc, |
2342 | SemaRef.getLangOpts().CPlusPlus14 |
2343 | ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt |
2344 | : diag::ext_constexpr_body_invalid_stmt) |
2345 | << isa<CXXConstructorDecl>(Dcl); |
2346 | } |
2347 | |
2348 | if (const CXXConstructorDecl *Constructor |
2349 | = dyn_cast<CXXConstructorDecl>(Val: Dcl)) { |
2350 | const CXXRecordDecl *RD = Constructor->getParent(); |
2351 | // DR1359: |
2352 | // - every non-variant non-static data member and base class sub-object |
2353 | // shall be initialized; |
2354 | // DR1460: |
2355 | // - if the class is a union having variant members, exactly one of them |
2356 | // shall be initialized; |
2357 | if (RD->isUnion()) { |
2358 | if (Constructor->getNumCtorInitializers() == 0 && |
2359 | RD->hasVariantMembers()) { |
2360 | if (Kind == Sema::CheckConstexprKind::Diagnose) { |
2361 | SemaRef.Diag( |
2362 | Dcl->getLocation(), |
2363 | SemaRef.getLangOpts().CPlusPlus20 |
2364 | ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init |
2365 | : diag::ext_constexpr_union_ctor_no_init); |
2366 | } else if (!SemaRef.getLangOpts().CPlusPlus20) { |
2367 | return false; |
2368 | } |
2369 | } |
2370 | } else if (!Constructor->isDependentContext() && |
2371 | !Constructor->isDelegatingConstructor()) { |
2372 | assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases" ); |
2373 | |
2374 | // Skip detailed checking if we have enough initializers, and we would |
2375 | // allow at most one initializer per member. |
2376 | bool AnyAnonStructUnionMembers = false; |
2377 | unsigned Fields = 0; |
2378 | for (CXXRecordDecl::field_iterator I = RD->field_begin(), |
2379 | E = RD->field_end(); I != E; ++I, ++Fields) { |
2380 | if (I->isAnonymousStructOrUnion()) { |
2381 | AnyAnonStructUnionMembers = true; |
2382 | break; |
2383 | } |
2384 | } |
2385 | // DR1460: |
2386 | // - if the class is a union-like class, but is not a union, for each of |
2387 | // its anonymous union members having variant members, exactly one of |
2388 | // them shall be initialized; |
2389 | if (AnyAnonStructUnionMembers || |
2390 | Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { |
2391 | // Check initialization of non-static data members. Base classes are |
2392 | // always initialized so do not need to be checked. Dependent bases |
2393 | // might not have initializers in the member initializer list. |
2394 | llvm::SmallSet<Decl*, 16> Inits; |
2395 | for (const auto *I: Constructor->inits()) { |
2396 | if (FieldDecl *FD = I->getMember()) |
2397 | Inits.insert(FD); |
2398 | else if (IndirectFieldDecl *ID = I->getIndirectMember()) |
2399 | Inits.insert(I: ID->chain_begin(), E: ID->chain_end()); |
2400 | } |
2401 | |
2402 | bool Diagnosed = false; |
2403 | for (auto *I : RD->fields()) |
2404 | if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, |
2405 | Kind)) |
2406 | return false; |
2407 | } |
2408 | } |
2409 | } else { |
2410 | if (ReturnStmts.empty()) { |
2411 | // C++1y doesn't require constexpr functions to contain a 'return' |
2412 | // statement. We still do, unless the return type might be void, because |
2413 | // otherwise if there's no return statement, the function cannot |
2414 | // be used in a core constant expression. |
2415 | bool OK = SemaRef.getLangOpts().CPlusPlus14 && |
2416 | (Dcl->getReturnType()->isVoidType() || |
2417 | Dcl->getReturnType()->isDependentType()); |
2418 | switch (Kind) { |
2419 | case Sema::CheckConstexprKind::Diagnose: |
2420 | SemaRef.Diag(Dcl->getLocation(), |
2421 | OK ? diag::warn_cxx11_compat_constexpr_body_no_return |
2422 | : diag::err_constexpr_body_no_return) |
2423 | << Dcl->isConsteval(); |
2424 | if (!OK) |
2425 | return false; |
2426 | break; |
2427 | |
2428 | case Sema::CheckConstexprKind::CheckValid: |
2429 | // The formal requirements don't include this rule in C++14, even |
2430 | // though the "must be able to produce a constant expression" rules |
2431 | // still imply it in some cases. |
2432 | if (!SemaRef.getLangOpts().CPlusPlus14) |
2433 | return false; |
2434 | break; |
2435 | } |
2436 | } else if (ReturnStmts.size() > 1) { |
2437 | switch (Kind) { |
2438 | case Sema::CheckConstexprKind::Diagnose: |
2439 | SemaRef.Diag( |
2440 | ReturnStmts.back(), |
2441 | SemaRef.getLangOpts().CPlusPlus14 |
2442 | ? diag::warn_cxx11_compat_constexpr_body_multiple_return |
2443 | : diag::ext_constexpr_body_multiple_return); |
2444 | for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) |
2445 | SemaRef.Diag(ReturnStmts[I], |
2446 | diag::note_constexpr_body_previous_return); |
2447 | break; |
2448 | |
2449 | case Sema::CheckConstexprKind::CheckValid: |
2450 | if (!SemaRef.getLangOpts().CPlusPlus14) |
2451 | return false; |
2452 | break; |
2453 | } |
2454 | } |
2455 | } |
2456 | |
2457 | // C++11 [dcl.constexpr]p5: |
2458 | // if no function argument values exist such that the function invocation |
2459 | // substitution would produce a constant expression, the program is |
2460 | // ill-formed; no diagnostic required. |
2461 | // C++11 [dcl.constexpr]p3: |
2462 | // - every constructor call and implicit conversion used in initializing the |
2463 | // return value shall be one of those allowed in a constant expression. |
2464 | // C++11 [dcl.constexpr]p4: |
2465 | // - every constructor involved in initializing non-static data members and |
2466 | // base class sub-objects shall be a constexpr constructor. |
2467 | // |
2468 | // Note that this rule is distinct from the "requirements for a constexpr |
2469 | // function", so is not checked in CheckValid mode. |
2470 | SmallVector<PartialDiagnosticAt, 8> Diags; |
2471 | if (Kind == Sema::CheckConstexprKind::Diagnose && |
2472 | !Expr::isPotentialConstantExpr(FD: Dcl, Diags) && |
2473 | !SemaRef.getLangOpts().CPlusPlus23) { |
2474 | SemaRef.Diag(Dcl->getLocation(), |
2475 | diag::ext_constexpr_function_never_constant_expr) |
2476 | << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval() |
2477 | << Dcl->getNameInfo().getSourceRange(); |
2478 | for (size_t I = 0, N = Diags.size(); I != N; ++I) |
2479 | SemaRef.Diag(Diags[I].first, Diags[I].second); |
2480 | // Don't return false here: we allow this for compatibility in |
2481 | // system headers. |
2482 | } |
2483 | |
2484 | return true; |
2485 | } |
2486 | |
2487 | bool Sema::CheckImmediateEscalatingFunctionDefinition( |
2488 | FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) { |
2489 | if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating()) |
2490 | return true; |
2491 | FD->setBodyContainsImmediateEscalatingExpressions( |
2492 | FSI->FoundImmediateEscalatingExpression); |
2493 | if (FSI->FoundImmediateEscalatingExpression) { |
2494 | auto it = UndefinedButUsed.find(FD->getCanonicalDecl()); |
2495 | if (it != UndefinedButUsed.end()) { |
2496 | Diag(it->second, diag::err_immediate_function_used_before_definition) |
2497 | << it->first; |
2498 | Diag(FD->getLocation(), diag::note_defined_here) << FD; |
2499 | if (FD->isImmediateFunction() && !FD->isConsteval()) |
2500 | DiagnoseImmediateEscalatingReason(FD); |
2501 | return false; |
2502 | } |
2503 | } |
2504 | return true; |
2505 | } |
2506 | |
2507 | void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) { |
2508 | assert(FD->isImmediateEscalating() && !FD->isConsteval() && |
2509 | "expected an immediate function" ); |
2510 | assert(FD->hasBody() && "expected the function to have a body" ); |
2511 | struct ImmediateEscalatingExpressionsVisitor |
2512 | : public RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor> { |
2513 | |
2514 | using Base = RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor>; |
2515 | Sema &SemaRef; |
2516 | |
2517 | const FunctionDecl *ImmediateFn; |
2518 | bool ImmediateFnIsConstructor; |
2519 | CXXConstructorDecl *CurrentConstructor = nullptr; |
2520 | CXXCtorInitializer *CurrentInit = nullptr; |
2521 | |
2522 | ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD) |
2523 | : SemaRef(SemaRef), ImmediateFn(FD), |
2524 | ImmediateFnIsConstructor(isa<CXXConstructorDecl>(Val: FD)) {} |
2525 | |
2526 | bool shouldVisitImplicitCode() const { return true; } |
2527 | bool shouldVisitLambdaBody() const { return false; } |
2528 | |
2529 | void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) { |
2530 | SourceLocation Loc = E->getBeginLoc(); |
2531 | SourceRange Range = E->getSourceRange(); |
2532 | if (CurrentConstructor && CurrentInit) { |
2533 | Loc = CurrentConstructor->getLocation(); |
2534 | Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange() |
2535 | : SourceRange(); |
2536 | } |
2537 | |
2538 | FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr; |
2539 | |
2540 | SemaRef.Diag(Loc, diag::note_immediate_function_reason) |
2541 | << ImmediateFn << Fn << Fn->isConsteval() << IsCall |
2542 | << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor |
2543 | << (InitializedField != nullptr) |
2544 | << (CurrentInit && !CurrentInit->isWritten()) |
2545 | << InitializedField << Range; |
2546 | } |
2547 | bool TraverseCallExpr(CallExpr *E) { |
2548 | if (const auto *DR = |
2549 | dyn_cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit()); |
2550 | DR && DR->isImmediateEscalating()) { |
2551 | Diag(E, E->getDirectCallee(), /*IsCall=*/true); |
2552 | return false; |
2553 | } |
2554 | |
2555 | for (Expr *A : E->arguments()) |
2556 | if (!getDerived().TraverseStmt(A)) |
2557 | return false; |
2558 | |
2559 | return true; |
2560 | } |
2561 | |
2562 | bool VisitDeclRefExpr(DeclRefExpr *E) { |
2563 | if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(Val: E->getDecl()); |
2564 | ReferencedFn && E->isImmediateEscalating()) { |
2565 | Diag(E, ReferencedFn, /*IsCall=*/false); |
2566 | return false; |
2567 | } |
2568 | |
2569 | return true; |
2570 | } |
2571 | |
2572 | bool VisitCXXConstructExpr(CXXConstructExpr *E) { |
2573 | CXXConstructorDecl *D = E->getConstructor(); |
2574 | if (E->isImmediateEscalating()) { |
2575 | Diag(E, D, /*IsCall=*/true); |
2576 | return false; |
2577 | } |
2578 | return true; |
2579 | } |
2580 | |
2581 | bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { |
2582 | llvm::SaveAndRestore RAII(CurrentInit, Init); |
2583 | return Base::TraverseConstructorInitializer(Init); |
2584 | } |
2585 | |
2586 | bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) { |
2587 | llvm::SaveAndRestore RAII(CurrentConstructor, Ctr); |
2588 | return Base::TraverseCXXConstructorDecl(Ctr); |
2589 | } |
2590 | |
2591 | bool TraverseType(QualType T) { return true; } |
2592 | bool VisitBlockExpr(BlockExpr *T) { return true; } |
2593 | |
2594 | } Visitor(*this, FD); |
2595 | Visitor.TraverseDecl(FD); |
2596 | } |
2597 | |
2598 | /// Get the class that is directly named by the current context. This is the |
2599 | /// class for which an unqualified-id in this scope could name a constructor |
2600 | /// or destructor. |
2601 | /// |
2602 | /// If the scope specifier denotes a class, this will be that class. |
2603 | /// If the scope specifier is empty, this will be the class whose |
2604 | /// member-specification we are currently within. Otherwise, there |
2605 | /// is no such class. |
2606 | CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { |
2607 | assert(getLangOpts().CPlusPlus && "No class names in C!" ); |
2608 | |
2609 | if (SS && SS->isInvalid()) |
2610 | return nullptr; |
2611 | |
2612 | if (SS && SS->isNotEmpty()) { |
2613 | DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true); |
2614 | return dyn_cast_or_null<CXXRecordDecl>(Val: DC); |
2615 | } |
2616 | |
2617 | return dyn_cast_or_null<CXXRecordDecl>(Val: CurContext); |
2618 | } |
2619 | |
2620 | /// isCurrentClassName - Determine whether the identifier II is the |
2621 | /// name of the class type currently being defined. In the case of |
2622 | /// nested classes, this will only return true if II is the name of |
2623 | /// the innermost class. |
2624 | bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, |
2625 | const CXXScopeSpec *SS) { |
2626 | CXXRecordDecl *CurDecl = getCurrentClass(S, SS); |
2627 | return CurDecl && &II == CurDecl->getIdentifier(); |
2628 | } |
2629 | |
2630 | /// Determine whether the identifier II is a typo for the name of |
2631 | /// the class type currently being defined. If so, update it to the identifier |
2632 | /// that should have been used. |
2633 | bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { |
2634 | assert(getLangOpts().CPlusPlus && "No class names in C!" ); |
2635 | |
2636 | if (!getLangOpts().SpellChecking) |
2637 | return false; |
2638 | |
2639 | CXXRecordDecl *CurDecl; |
2640 | if (SS && SS->isSet() && !SS->isInvalid()) { |
2641 | DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true); |
2642 | CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: DC); |
2643 | } else |
2644 | CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: CurContext); |
2645 | |
2646 | if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && |
2647 | 3 * II->getName().edit_distance(Other: CurDecl->getIdentifier()->getName()) |
2648 | < II->getLength()) { |
2649 | II = CurDecl->getIdentifier(); |
2650 | return true; |
2651 | } |
2652 | |
2653 | return false; |
2654 | } |
2655 | |
2656 | /// Determine whether the given class is a base class of the given |
2657 | /// class, including looking at dependent bases. |
2658 | static bool findCircularInheritance(const CXXRecordDecl *Class, |
2659 | const CXXRecordDecl *Current) { |
2660 | SmallVector<const CXXRecordDecl*, 8> Queue; |
2661 | |
2662 | Class = Class->getCanonicalDecl(); |
2663 | while (true) { |
2664 | for (const auto &I : Current->bases()) { |
2665 | CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); |
2666 | if (!Base) |
2667 | continue; |
2668 | |
2669 | Base = Base->getDefinition(); |
2670 | if (!Base) |
2671 | continue; |
2672 | |
2673 | if (Base->getCanonicalDecl() == Class) |
2674 | return true; |
2675 | |
2676 | Queue.push_back(Elt: Base); |
2677 | } |
2678 | |
2679 | if (Queue.empty()) |
2680 | return false; |
2681 | |
2682 | Current = Queue.pop_back_val(); |
2683 | } |
2684 | |
2685 | return false; |
2686 | } |
2687 | |
2688 | /// Check the validity of a C++ base class specifier. |
2689 | /// |
2690 | /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics |
2691 | /// and returns NULL otherwise. |
2692 | CXXBaseSpecifier * |
2693 | Sema::CheckBaseSpecifier(CXXRecordDecl *Class, |
2694 | SourceRange SpecifierRange, |
2695 | bool Virtual, AccessSpecifier Access, |
2696 | TypeSourceInfo *TInfo, |
2697 | SourceLocation EllipsisLoc) { |
2698 | // In HLSL, unspecified class access is public rather than private. |
2699 | if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class && |
2700 | Access == AS_none) |
2701 | Access = AS_public; |
2702 | |
2703 | QualType BaseType = TInfo->getType(); |
2704 | if (BaseType->containsErrors()) { |
2705 | // Already emitted a diagnostic when parsing the error type. |
2706 | return nullptr; |
2707 | } |
2708 | // C++ [class.union]p1: |
2709 | // A union shall not have base classes. |
2710 | if (Class->isUnion()) { |
2711 | Diag(Class->getLocation(), diag::err_base_clause_on_union) |
2712 | << SpecifierRange; |
2713 | return nullptr; |
2714 | } |
2715 | |
2716 | if (EllipsisLoc.isValid() && |
2717 | !TInfo->getType()->containsUnexpandedParameterPack()) { |
2718 | Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) |
2719 | << TInfo->getTypeLoc().getSourceRange(); |
2720 | EllipsisLoc = SourceLocation(); |
2721 | } |
2722 | |
2723 | SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); |
2724 | |
2725 | if (BaseType->isDependentType()) { |
2726 | // Make sure that we don't have circular inheritance among our dependent |
2727 | // bases. For non-dependent bases, the check for completeness below handles |
2728 | // this. |
2729 | if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { |
2730 | if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || |
2731 | ((BaseDecl = BaseDecl->getDefinition()) && |
2732 | findCircularInheritance(Class, Current: BaseDecl))) { |
2733 | Diag(BaseLoc, diag::err_circular_inheritance) |
2734 | << BaseType << Context.getTypeDeclType(Class); |
2735 | |
2736 | if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) |
2737 | Diag(BaseDecl->getLocation(), diag::note_previous_decl) |
2738 | << BaseType; |
2739 | |
2740 | return nullptr; |
2741 | } |
2742 | } |
2743 | |
2744 | // Make sure that we don't make an ill-formed AST where the type of the |
2745 | // Class is non-dependent and its attached base class specifier is an |
2746 | // dependent type, which violates invariants in many clang code paths (e.g. |
2747 | // constexpr evaluator). If this case happens (in errory-recovery mode), we |
2748 | // explicitly mark the Class decl invalid. The diagnostic was already |
2749 | // emitted. |
2750 | if (!Class->getTypeForDecl()->isDependentType()) |
2751 | Class->setInvalidDecl(); |
2752 | return new (Context) CXXBaseSpecifier( |
2753 | SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class, |
2754 | Access, TInfo, EllipsisLoc); |
2755 | } |
2756 | |
2757 | // Base specifiers must be record types. |
2758 | if (!BaseType->isRecordType()) { |
2759 | Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; |
2760 | return nullptr; |
2761 | } |
2762 | |
2763 | // C++ [class.union]p1: |
2764 | // A union shall not be used as a base class. |
2765 | if (BaseType->isUnionType()) { |
2766 | Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; |
2767 | return nullptr; |
2768 | } |
2769 | |
2770 | // For the MS ABI, propagate DLL attributes to base class templates. |
2771 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() || |
2772 | Context.getTargetInfo().getTriple().isPS()) { |
2773 | if (Attr *ClassAttr = getDLLAttr(Class)) { |
2774 | if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( |
2775 | Val: BaseType->getAsCXXRecordDecl())) { |
2776 | propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplateSpec: BaseTemplate, |
2777 | BaseLoc); |
2778 | } |
2779 | } |
2780 | } |
2781 | |
2782 | // C++ [class.derived]p2: |
2783 | // The class-name in a base-specifier shall not be an incompletely |
2784 | // defined class. |
2785 | if (RequireCompleteType(BaseLoc, BaseType, |
2786 | diag::err_incomplete_base_class, SpecifierRange)) { |
2787 | Class->setInvalidDecl(); |
2788 | return nullptr; |
2789 | } |
2790 | |
2791 | // If the base class is polymorphic or isn't empty, the new one is/isn't, too. |
2792 | RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); |
2793 | assert(BaseDecl && "Record type has no declaration" ); |
2794 | BaseDecl = BaseDecl->getDefinition(); |
2795 | assert(BaseDecl && "Base type is not incomplete, but has no definition" ); |
2796 | CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(Val: BaseDecl); |
2797 | assert(CXXBaseDecl && "Base type is not a C++ type" ); |
2798 | |
2799 | // Microsoft docs say: |
2800 | // "If a base-class has a code_seg attribute, derived classes must have the |
2801 | // same attribute." |
2802 | const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); |
2803 | const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); |
2804 | if ((DerivedCSA || BaseCSA) && |
2805 | (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { |
2806 | Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); |
2807 | Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) |
2808 | << CXXBaseDecl; |
2809 | return nullptr; |
2810 | } |
2811 | |
2812 | // A class which contains a flexible array member is not suitable for use as a |
2813 | // base class: |
2814 | // - If the layout determines that a base comes before another base, |
2815 | // the flexible array member would index into the subsequent base. |
2816 | // - If the layout determines that base comes before the derived class, |
2817 | // the flexible array member would index into the derived class. |
2818 | if (CXXBaseDecl->hasFlexibleArrayMember()) { |
2819 | Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) |
2820 | << CXXBaseDecl->getDeclName(); |
2821 | return nullptr; |
2822 | } |
2823 | |
2824 | // C++ [class]p3: |
2825 | // If a class is marked final and it appears as a base-type-specifier in |
2826 | // base-clause, the program is ill-formed. |
2827 | if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { |
2828 | Diag(BaseLoc, diag::err_class_marked_final_used_as_base) |
2829 | << CXXBaseDecl->getDeclName() |
2830 | << FA->isSpelledAsSealed(); |
2831 | Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) |
2832 | << CXXBaseDecl->getDeclName() << FA->getRange(); |
2833 | return nullptr; |
2834 | } |
2835 | |
2836 | if (BaseDecl->isInvalidDecl()) |
2837 | Class->setInvalidDecl(); |
2838 | |
2839 | // Create the base specifier. |
2840 | return new (Context) CXXBaseSpecifier( |
2841 | SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class, |
2842 | Access, TInfo, EllipsisLoc); |
2843 | } |
2844 | |
2845 | /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is |
2846 | /// one entry in the base class list of a class specifier, for |
2847 | /// example: |
2848 | /// class foo : public bar, virtual private baz { |
2849 | /// 'public bar' and 'virtual private baz' are each base-specifiers. |
2850 | BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, |
2851 | const ParsedAttributesView &Attributes, |
2852 | bool Virtual, AccessSpecifier Access, |
2853 | ParsedType basetype, SourceLocation BaseLoc, |
2854 | SourceLocation EllipsisLoc) { |
2855 | if (!classdecl) |
2856 | return true; |
2857 | |
2858 | AdjustDeclIfTemplate(Decl&: classdecl); |
2859 | CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Val: classdecl); |
2860 | if (!Class) |
2861 | return true; |
2862 | |
2863 | // We haven't yet attached the base specifiers. |
2864 | Class->setIsParsingBaseSpecifiers(); |
2865 | |
2866 | // We do not support any C++11 attributes on base-specifiers yet. |
2867 | // Diagnose any attributes we see. |
2868 | for (const ParsedAttr &AL : Attributes) { |
2869 | if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) |
2870 | continue; |
2871 | if (AL.getKind() == ParsedAttr::UnknownAttribute) |
2872 | Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) |
2873 | << AL << AL.getRange(); |
2874 | else |
2875 | Diag(AL.getLoc(), diag::err_base_specifier_attribute) |
2876 | << AL << AL.isRegularKeywordAttribute() << AL.getRange(); |
2877 | } |
2878 | |
2879 | TypeSourceInfo *TInfo = nullptr; |
2880 | GetTypeFromParser(Ty: basetype, TInfo: &TInfo); |
2881 | |
2882 | if (EllipsisLoc.isInvalid() && |
2883 | DiagnoseUnexpandedParameterPack(Loc: SpecifierRange.getBegin(), T: TInfo, |
2884 | UPPC: UPPC_BaseType)) |
2885 | return true; |
2886 | |
2887 | if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, |
2888 | Virtual, Access, TInfo, |
2889 | EllipsisLoc)) |
2890 | return BaseSpec; |
2891 | else |
2892 | Class->setInvalidDecl(); |
2893 | |
2894 | return true; |
2895 | } |
2896 | |
2897 | /// Use small set to collect indirect bases. As this is only used |
2898 | /// locally, there's no need to abstract the small size parameter. |
2899 | typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; |
2900 | |
2901 | /// Recursively add the bases of Type. Don't add Type itself. |
2902 | static void |
2903 | NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, |
2904 | const QualType &Type) |
2905 | { |
2906 | // Even though the incoming type is a base, it might not be |
2907 | // a class -- it could be a template parm, for instance. |
2908 | if (auto Rec = Type->getAs<RecordType>()) { |
2909 | auto Decl = Rec->getAsCXXRecordDecl(); |
2910 | |
2911 | // Iterate over its bases. |
2912 | for (const auto &BaseSpec : Decl->bases()) { |
2913 | QualType Base = Context.getCanonicalType(BaseSpec.getType()) |
2914 | .getUnqualifiedType(); |
2915 | if (Set.insert(Base).second) |
2916 | // If we've not already seen it, recurse. |
2917 | NoteIndirectBases(Context, Set, Base); |
2918 | } |
2919 | } |
2920 | } |
2921 | |
2922 | /// Performs the actual work of attaching the given base class |
2923 | /// specifiers to a C++ class. |
2924 | bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, |
2925 | MutableArrayRef<CXXBaseSpecifier *> Bases) { |
2926 | if (Bases.empty()) |
2927 | return false; |
2928 | |
2929 | // Used to keep track of which base types we have already seen, so |
2930 | // that we can properly diagnose redundant direct base types. Note |
2931 | // that the key is always the unqualified canonical type of the base |
2932 | // class. |
2933 | std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; |
2934 | |
2935 | // Used to track indirect bases so we can see if a direct base is |
2936 | // ambiguous. |
2937 | IndirectBaseSet IndirectBaseTypes; |
2938 | |
2939 | // Copy non-redundant base specifiers into permanent storage. |
2940 | unsigned NumGoodBases = 0; |
2941 | bool Invalid = false; |
2942 | for (unsigned idx = 0; idx < Bases.size(); ++idx) { |
2943 | QualType NewBaseType |
2944 | = Context.getCanonicalType(T: Bases[idx]->getType()); |
2945 | NewBaseType = NewBaseType.getLocalUnqualifiedType(); |
2946 | |
2947 | CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; |
2948 | if (KnownBase) { |
2949 | // C++ [class.mi]p3: |
2950 | // A class shall not be specified as a direct base class of a |
2951 | // derived class more than once. |
2952 | Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) |
2953 | << KnownBase->getType() << Bases[idx]->getSourceRange(); |
2954 | |
2955 | // Delete the duplicate base class specifier; we're going to |
2956 | // overwrite its pointer later. |
2957 | Context.Deallocate(Ptr: Bases[idx]); |
2958 | |
2959 | Invalid = true; |
2960 | } else { |
2961 | // Okay, add this new base class. |
2962 | KnownBase = Bases[idx]; |
2963 | Bases[NumGoodBases++] = Bases[idx]; |
2964 | |
2965 | if (NewBaseType->isDependentType()) |
2966 | continue; |
2967 | // Note this base's direct & indirect bases, if there could be ambiguity. |
2968 | if (Bases.size() > 1) |
2969 | NoteIndirectBases(Context, Set&: IndirectBaseTypes, Type: NewBaseType); |
2970 | |
2971 | if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { |
2972 | const CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: Record->getDecl()); |
2973 | if (Class->isInterface() && |
2974 | (!RD->isInterfaceLike() || |
2975 | KnownBase->getAccessSpecifier() != AS_public)) { |
2976 | // The Microsoft extension __interface does not permit bases that |
2977 | // are not themselves public interfaces. |
2978 | Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) |
2979 | << getRecordDiagFromTagKind(RD->getTagKind()) << RD |
2980 | << RD->getSourceRange(); |
2981 | Invalid = true; |
2982 | } |
2983 | if (RD->hasAttr<WeakAttr>()) |
2984 | Class->addAttr(WeakAttr::CreateImplicit(Context)); |
2985 | } |
2986 | } |
2987 | } |
2988 | |
2989 | // Attach the remaining base class specifiers to the derived class. |
2990 | Class->setBases(Bases: Bases.data(), NumBases: NumGoodBases); |
2991 | |
2992 | // Check that the only base classes that are duplicate are virtual. |
2993 | for (unsigned idx = 0; idx < NumGoodBases; ++idx) { |
2994 | // Check whether this direct base is inaccessible due to ambiguity. |
2995 | QualType BaseType = Bases[idx]->getType(); |
2996 | |
2997 | // Skip all dependent types in templates being used as base specifiers. |
2998 | // Checks below assume that the base specifier is a CXXRecord. |
2999 | if (BaseType->isDependentType()) |
3000 | continue; |
3001 | |
3002 | CanQualType CanonicalBase = Context.getCanonicalType(T: BaseType) |
3003 | .getUnqualifiedType(); |
3004 | |
3005 | if (IndirectBaseTypes.count(Ptr: CanonicalBase)) { |
3006 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, |
3007 | /*DetectVirtual=*/true); |
3008 | bool found |
3009 | = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); |
3010 | assert(found); |
3011 | (void)found; |
3012 | |
3013 | if (Paths.isAmbiguous(BaseType: CanonicalBase)) |
3014 | Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) |
3015 | << BaseType << getAmbiguousPathsDisplayString(Paths) |
3016 | << Bases[idx]->getSourceRange(); |
3017 | else |
3018 | assert(Bases[idx]->isVirtual()); |
3019 | } |
3020 | |
3021 | // Delete the base class specifier, since its data has been copied |
3022 | // into the CXXRecordDecl. |
3023 | Context.Deallocate(Ptr: Bases[idx]); |
3024 | } |
3025 | |
3026 | return Invalid; |
3027 | } |
3028 | |
3029 | /// ActOnBaseSpecifiers - Attach the given base specifiers to the |
3030 | /// class, after checking whether there are any duplicate base |
3031 | /// classes. |
3032 | void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, |
3033 | MutableArrayRef<CXXBaseSpecifier *> Bases) { |
3034 | if (!ClassDecl || Bases.empty()) |
3035 | return; |
3036 | |
3037 | AdjustDeclIfTemplate(Decl&: ClassDecl); |
3038 | AttachBaseSpecifiers(Class: cast<CXXRecordDecl>(Val: ClassDecl), Bases); |
3039 | } |
3040 | |
3041 | /// Determine whether the type \p Derived is a C++ class that is |
3042 | /// derived from the type \p Base. |
3043 | bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { |
3044 | if (!getLangOpts().CPlusPlus) |
3045 | return false; |
3046 | |
3047 | CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); |
3048 | if (!DerivedRD) |
3049 | return false; |
3050 | |
3051 | CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); |
3052 | if (!BaseRD) |
3053 | return false; |
3054 | |
3055 | // If either the base or the derived type is invalid, don't try to |
3056 | // check whether one is derived from the other. |
3057 | if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) |
3058 | return false; |
3059 | |
3060 | // FIXME: In a modules build, do we need the entire path to be visible for us |
3061 | // to be able to use the inheritance relationship? |
3062 | if (!isCompleteType(Loc, T: Derived) && !DerivedRD->isBeingDefined()) |
3063 | return false; |
3064 | |
3065 | return DerivedRD->isDerivedFrom(Base: BaseRD); |
3066 | } |
3067 | |
3068 | /// Determine whether the type \p Derived is a C++ class that is |
3069 | /// derived from the type \p Base. |
3070 | bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, |
3071 | CXXBasePaths &Paths) { |
3072 | if (!getLangOpts().CPlusPlus) |
3073 | return false; |
3074 | |
3075 | CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); |
3076 | if (!DerivedRD) |
3077 | return false; |
3078 | |
3079 | CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); |
3080 | if (!BaseRD) |
3081 | return false; |
3082 | |
3083 | if (!isCompleteType(Loc, T: Derived) && !DerivedRD->isBeingDefined()) |
3084 | return false; |
3085 | |
3086 | return DerivedRD->isDerivedFrom(Base: BaseRD, Paths); |
3087 | } |
3088 | |
3089 | static void BuildBasePathArray(const CXXBasePath &Path, |
3090 | CXXCastPath &BasePathArray) { |
3091 | // We first go backward and check if we have a virtual base. |
3092 | // FIXME: It would be better if CXXBasePath had the base specifier for |
3093 | // the nearest virtual base. |
3094 | unsigned Start = 0; |
3095 | for (unsigned I = Path.size(); I != 0; --I) { |
3096 | if (Path[I - 1].Base->isVirtual()) { |
3097 | Start = I - 1; |
3098 | break; |
3099 | } |
3100 | } |
3101 | |
3102 | // Now add all bases. |
3103 | for (unsigned I = Start, E = Path.size(); I != E; ++I) |
3104 | BasePathArray.push_back(Elt: const_cast<CXXBaseSpecifier*>(Path[I].Base)); |
3105 | } |
3106 | |
3107 | |
3108 | void Sema::BuildBasePathArray(const CXXBasePaths &Paths, |
3109 | CXXCastPath &BasePathArray) { |
3110 | assert(BasePathArray.empty() && "Base path array must be empty!" ); |
3111 | assert(Paths.isRecordingPaths() && "Must record paths!" ); |
3112 | return ::BuildBasePathArray(Path: Paths.front(), BasePathArray); |
3113 | } |
3114 | /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base |
3115 | /// conversion (where Derived and Base are class types) is |
3116 | /// well-formed, meaning that the conversion is unambiguous (and |
3117 | /// that all of the base classes are accessible). Returns true |
3118 | /// and emits a diagnostic if the code is ill-formed, returns false |
3119 | /// otherwise. Loc is the location where this routine should point to |
3120 | /// if there is an error, and Range is the source range to highlight |
3121 | /// if there is an error. |
3122 | /// |
3123 | /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the |
3124 | /// diagnostic for the respective type of error will be suppressed, but the |
3125 | /// check for ill-formed code will still be performed. |
3126 | bool |
3127 | Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, |
3128 | unsigned InaccessibleBaseID, |
3129 | unsigned AmbiguousBaseConvID, |
3130 | SourceLocation Loc, SourceRange Range, |
3131 | DeclarationName Name, |
3132 | CXXCastPath *BasePath, |
3133 | bool IgnoreAccess) { |
3134 | // First, determine whether the path from Derived to Base is |
3135 | // ambiguous. This is slightly more expensive than checking whether |
3136 | // the Derived to Base conversion exists, because here we need to |
3137 | // explore multiple paths to determine if there is an ambiguity. |
3138 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, |
3139 | /*DetectVirtual=*/false); |
3140 | bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); |
3141 | if (!DerivationOkay) |
3142 | return true; |
3143 | |
3144 | const CXXBasePath *Path = nullptr; |
3145 | if (!Paths.isAmbiguous(BaseType: Context.getCanonicalType(T: Base).getUnqualifiedType())) |
3146 | Path = &Paths.front(); |
3147 | |
3148 | // For MSVC compatibility, check if Derived directly inherits from Base. Clang |
3149 | // warns about this hierarchy under -Winaccessible-base, but MSVC allows the |
3150 | // user to access such bases. |
3151 | if (!Path && getLangOpts().MSVCCompat) { |
3152 | for (const CXXBasePath &PossiblePath : Paths) { |
3153 | if (PossiblePath.size() == 1) { |
3154 | Path = &PossiblePath; |
3155 | if (AmbiguousBaseConvID) |
3156 | Diag(Loc, diag::ext_ms_ambiguous_direct_base) |
3157 | << Base << Derived << Range; |
3158 | break; |
3159 | } |
3160 | } |
3161 | } |
3162 | |
3163 | if (Path) { |
3164 | if (!IgnoreAccess) { |
3165 | // Check that the base class can be accessed. |
3166 | switch ( |
3167 | CheckBaseClassAccess(AccessLoc: Loc, Base, Derived, Path: *Path, DiagID: InaccessibleBaseID)) { |
3168 | case AR_inaccessible: |
3169 | return true; |
3170 | case AR_accessible: |
3171 | case AR_dependent: |
3172 | case AR_delayed: |
3173 | break; |
3174 | } |
3175 | } |
3176 | |
3177 | // Build a base path if necessary. |
3178 | if (BasePath) |
3179 | ::BuildBasePathArray(Path: *Path, BasePathArray&: *BasePath); |
3180 | return false; |
3181 | } |
3182 | |
3183 | if (AmbiguousBaseConvID) { |
3184 | // We know that the derived-to-base conversion is ambiguous, and |
3185 | // we're going to produce a diagnostic. Perform the derived-to-base |
3186 | // search just one more time to compute all of the possible paths so |
3187 | // that we can print them out. This is more expensive than any of |
3188 | // the previous derived-to-base checks we've done, but at this point |
3189 | // performance isn't as much of an issue. |
3190 | Paths.clear(); |
3191 | Paths.setRecordingPaths(true); |
3192 | bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); |
3193 | assert(StillOkay && "Can only be used with a derived-to-base conversion" ); |
3194 | (void)StillOkay; |
3195 | |
3196 | // Build up a textual representation of the ambiguous paths, e.g., |
3197 | // D -> B -> A, that will be used to illustrate the ambiguous |
3198 | // conversions in the diagnostic. We only print one of the paths |
3199 | // to each base class subobject. |
3200 | std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); |
3201 | |
3202 | Diag(Loc, AmbiguousBaseConvID) |
3203 | << Derived << Base << PathDisplayStr << Range << Name; |
3204 | } |
3205 | return true; |
3206 | } |
3207 | |
3208 | bool |
3209 | Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, |
3210 | SourceLocation Loc, SourceRange Range, |
3211 | CXXCastPath *BasePath, |
3212 | bool IgnoreAccess) { |
3213 | return CheckDerivedToBaseConversion( |
3214 | Derived, Base, diag::err_upcast_to_inaccessible_base, |
3215 | diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), |
3216 | BasePath, IgnoreAccess); |
3217 | } |
3218 | |
3219 | |
3220 | /// Builds a string representing ambiguous paths from a |
3221 | /// specific derived class to different subobjects of the same base |
3222 | /// class. |
3223 | /// |
3224 | /// This function builds a string that can be used in error messages |
3225 | /// to show the different paths that one can take through the |
3226 | /// inheritance hierarchy to go from the derived class to different |
3227 | /// subobjects of a base class. The result looks something like this: |
3228 | /// @code |
3229 | /// struct D -> struct B -> struct A |
3230 | /// struct D -> struct C -> struct A |
3231 | /// @endcode |
3232 | std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { |
3233 | std::string PathDisplayStr; |
3234 | std::set<unsigned> DisplayedPaths; |
3235 | for (CXXBasePaths::paths_iterator Path = Paths.begin(); |
3236 | Path != Paths.end(); ++Path) { |
3237 | if (DisplayedPaths.insert(x: Path->back().SubobjectNumber).second) { |
3238 | // We haven't displayed a path to this particular base |
3239 | // class subobject yet. |
3240 | PathDisplayStr += "\n " ; |
3241 | PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); |
3242 | for (CXXBasePath::const_iterator Element = Path->begin(); |
3243 | Element != Path->end(); ++Element) |
3244 | PathDisplayStr += " -> " + Element->Base->getType().getAsString(); |
3245 | } |
3246 | } |
3247 | |
3248 | return PathDisplayStr; |
3249 | } |
3250 | |
3251 | //===----------------------------------------------------------------------===// |
3252 | // C++ class member Handling |
3253 | //===----------------------------------------------------------------------===// |
3254 | |
3255 | /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. |
3256 | bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, |
3257 | SourceLocation ColonLoc, |
3258 | const ParsedAttributesView &Attrs) { |
3259 | assert(Access != AS_none && "Invalid kind for syntactic access specifier!" ); |
3260 | AccessSpecDecl *ASDecl = AccessSpecDecl::Create(C&: Context, AS: Access, DC: CurContext, |
3261 | ASLoc, ColonLoc); |
3262 | CurContext->addHiddenDecl(ASDecl); |
3263 | return ProcessAccessDeclAttributeList(ASDecl, AttrList: Attrs); |
3264 | } |
3265 | |
3266 | /// CheckOverrideControl - Check C++11 override control semantics. |
3267 | void Sema::CheckOverrideControl(NamedDecl *D) { |
3268 | if (D->isInvalidDecl()) |
3269 | return; |
3270 | |
3271 | // We only care about "override" and "final" declarations. |
3272 | if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) |
3273 | return; |
3274 | |
3275 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D); |
3276 | |
3277 | // We can't check dependent instance methods. |
3278 | if (MD && MD->isInstance() && |
3279 | (MD->getParent()->hasAnyDependentBases() || |
3280 | MD->getType()->isDependentType())) |
3281 | return; |
3282 | |
3283 | if (MD && !MD->isVirtual()) { |
3284 | // If we have a non-virtual method, check if it hides a virtual method. |
3285 | // (In that case, it's most likely the method has the wrong type.) |
3286 | SmallVector<CXXMethodDecl *, 8> OverloadedMethods; |
3287 | FindHiddenVirtualMethods(MD, OverloadedMethods); |
3288 | |
3289 | if (!OverloadedMethods.empty()) { |
3290 | if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { |
3291 | Diag(OA->getLocation(), |
3292 | diag::override_keyword_hides_virtual_member_function) |
3293 | << "override" << (OverloadedMethods.size() > 1); |
3294 | } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { |
3295 | Diag(FA->getLocation(), |
3296 | diag::override_keyword_hides_virtual_member_function) |
3297 | << (FA->isSpelledAsSealed() ? "sealed" : "final" ) |
3298 | << (OverloadedMethods.size() > 1); |
3299 | } |
3300 | NoteHiddenVirtualMethods(MD, OverloadedMethods); |
3301 | MD->setInvalidDecl(); |
3302 | return; |
3303 | } |
3304 | // Fall through into the general case diagnostic. |
3305 | // FIXME: We might want to attempt typo correction here. |
3306 | } |
3307 | |
3308 | if (!MD || !MD->isVirtual()) { |
3309 | if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { |
3310 | Diag(OA->getLocation(), |
3311 | diag::override_keyword_only_allowed_on_virtual_member_functions) |
3312 | << "override" << FixItHint::CreateRemoval(OA->getLocation()); |
3313 | D->dropAttr<OverrideAttr>(); |
3314 | } |
3315 | if (FinalAttr *FA = D->getAttr<FinalAttr>()) { |
3316 | Diag(FA->getLocation(), |
3317 | diag::override_keyword_only_allowed_on_virtual_member_functions) |
3318 | << (FA->isSpelledAsSealed() ? "sealed" : "final" ) |
3319 | << FixItHint::CreateRemoval(FA->getLocation()); |
3320 | D->dropAttr<FinalAttr>(); |
3321 | } |
3322 | return; |
3323 | } |
3324 | |
3325 | // C++11 [class.virtual]p5: |
3326 | // If a function is marked with the virt-specifier override and |
3327 | // does not override a member function of a base class, the program is |
3328 | // ill-formed. |
3329 | bool HasOverriddenMethods = MD->size_overridden_methods() != 0; |
3330 | if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) |
3331 | Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) |
3332 | << MD->getDeclName(); |
3333 | } |
3334 | |
3335 | void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { |
3336 | if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) |
3337 | return; |
3338 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D); |
3339 | if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) |
3340 | return; |
3341 | |
3342 | SourceLocation Loc = MD->getLocation(); |
3343 | SourceLocation SpellingLoc = Loc; |
3344 | if (getSourceManager().isMacroArgExpansion(Loc)) |
3345 | SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); |
3346 | SpellingLoc = getSourceManager().getSpellingLoc(Loc: SpellingLoc); |
3347 | if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(Loc: SpellingLoc)) |
3348 | return; |
3349 | |
3350 | if (MD->size_overridden_methods() > 0) { |
3351 | auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { |
3352 | unsigned DiagID = |
3353 | Inconsistent && !Diags.isIgnored(DiagID: DiagInconsistent, Loc: MD->getLocation()) |
3354 | ? DiagInconsistent |
3355 | : DiagSuggest; |
3356 | Diag(MD->getLocation(), DiagID) << MD->getDeclName(); |
3357 | const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); |
3358 | Diag(OMD->getLocation(), diag::note_overridden_virtual_function); |
3359 | }; |
3360 | if (isa<CXXDestructorDecl>(MD)) |
3361 | EmitDiag( |
3362 | diag::warn_inconsistent_destructor_marked_not_override_overriding, |
3363 | diag::warn_suggest_destructor_marked_not_override_overriding); |
3364 | else |
3365 | EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, |
3366 | diag::warn_suggest_function_marked_not_override_overriding); |
3367 | } |
3368 | } |
3369 | |
3370 | /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member |
3371 | /// function overrides a virtual member function marked 'final', according to |
3372 | /// C++11 [class.virtual]p4. |
3373 | bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, |
3374 | const CXXMethodDecl *Old) { |
3375 | FinalAttr *FA = Old->getAttr<FinalAttr>(); |
3376 | if (!FA) |
3377 | return false; |
3378 | |
3379 | Diag(New->getLocation(), diag::err_final_function_overridden) |
3380 | << New->getDeclName() |
3381 | << FA->isSpelledAsSealed(); |
3382 | Diag(Old->getLocation(), diag::note_overridden_virtual_function); |
3383 | return true; |
3384 | } |
3385 | |
3386 | static bool InitializationHasSideEffects(const FieldDecl &FD) { |
3387 | const Type *T = FD.getType()->getBaseElementTypeUnsafe(); |
3388 | // FIXME: Destruction of ObjC lifetime types has side-effects. |
3389 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) |
3390 | return !RD->isCompleteDefinition() || |
3391 | !RD->hasTrivialDefaultConstructor() || |
3392 | !RD->hasTrivialDestructor(); |
3393 | return false; |
3394 | } |
3395 | |
3396 | // Check if there is a field shadowing. |
3397 | void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, |
3398 | DeclarationName FieldName, |
3399 | const CXXRecordDecl *RD, |
3400 | bool DeclIsField) { |
3401 | if (Diags.isIgnored(diag::warn_shadow_field, Loc)) |
3402 | return; |
3403 | |
3404 | // To record a shadowed field in a base |
3405 | std::map<CXXRecordDecl*, NamedDecl*> Bases; |
3406 | auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, |
3407 | CXXBasePath &Path) { |
3408 | const auto Base = Specifier->getType()->getAsCXXRecordDecl(); |
3409 | // Record an ambiguous path directly |
3410 | if (Bases.find(x: Base) != Bases.end()) |
3411 | return true; |
3412 | for (const auto Field : Base->lookup(FieldName)) { |
3413 | if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && |
3414 | Field->getAccess() != AS_private) { |
3415 | assert(Field->getAccess() != AS_none); |
3416 | assert(Bases.find(Base) == Bases.end()); |
3417 | Bases[Base] = Field; |
3418 | return true; |
3419 | } |
3420 | } |
3421 | return false; |
3422 | }; |
3423 | |
3424 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, |
3425 | /*DetectVirtual=*/true); |
3426 | if (!RD->lookupInBases(BaseMatches: FieldShadowed, Paths)) |
3427 | return; |
3428 | |
3429 | for (const auto &P : Paths) { |
3430 | auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); |
3431 | auto It = Bases.find(x: Base); |
3432 | // Skip duplicated bases |
3433 | if (It == Bases.end()) |
3434 | continue; |
3435 | auto BaseField = It->second; |
3436 | assert(BaseField->getAccess() != AS_private); |
3437 | if (AS_none != |
3438 | CXXRecordDecl::MergeAccess(PathAccess: P.Access, DeclAccess: BaseField->getAccess())) { |
3439 | Diag(Loc, diag::warn_shadow_field) |
3440 | << FieldName << RD << Base << DeclIsField; |
3441 | Diag(BaseField->getLocation(), diag::note_shadow_field); |
3442 | Bases.erase(position: It); |
3443 | } |
3444 | } |
3445 | } |
3446 | |
3447 | /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member |
3448 | /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the |
3449 | /// bitfield width if there is one, 'InitExpr' specifies the initializer if |
3450 | /// one has been parsed, and 'InitStyle' is set if an in-class initializer is |
3451 | /// present (but parsing it has been deferred). |
3452 | NamedDecl * |
3453 | Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, |
3454 | MultiTemplateParamsArg TemplateParameterLists, |
3455 | Expr *BW, const VirtSpecifiers &VS, |
3456 | InClassInitStyle InitStyle) { |
3457 | const DeclSpec &DS = D.getDeclSpec(); |
3458 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); |
3459 | DeclarationName Name = NameInfo.getName(); |
3460 | SourceLocation Loc = NameInfo.getLoc(); |
3461 | |
3462 | // For anonymous bitfields, the location should point to the type. |
3463 | if (Loc.isInvalid()) |
3464 | Loc = D.getBeginLoc(); |
3465 | |
3466 | Expr *BitWidth = static_cast<Expr*>(BW); |
3467 | |
3468 | assert(isa<CXXRecordDecl>(CurContext)); |
3469 | assert(!DS.isFriendSpecified()); |
3470 | |
3471 | bool isFunc = D.isDeclarationOfFunction(); |
3472 | const ParsedAttr *MSPropertyAttr = |
3473 | D.getDeclSpec().getAttributes().getMSPropertyAttr(); |
3474 | |
3475 | if (cast<CXXRecordDecl>(Val: CurContext)->isInterface()) { |
3476 | // The Microsoft extension __interface only permits public member functions |
3477 | // and prohibits constructors, destructors, operators, non-public member |
3478 | // functions, static methods and data members. |
3479 | unsigned InvalidDecl; |
3480 | bool ShowDeclName = true; |
3481 | if (!isFunc && |
3482 | (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) |
3483 | InvalidDecl = 0; |
3484 | else if (!isFunc) |
3485 | InvalidDecl = 1; |
3486 | else if (AS != AS_public) |
3487 | InvalidDecl = 2; |
3488 | else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) |
3489 | InvalidDecl = 3; |
3490 | else switch (Name.getNameKind()) { |
3491 | case DeclarationName::CXXConstructorName: |
3492 | InvalidDecl = 4; |
3493 | ShowDeclName = false; |
3494 | break; |
3495 | |
3496 | case DeclarationName::CXXDestructorName: |
3497 | InvalidDecl = 5; |
3498 | ShowDeclName = false; |
3499 | break; |
3500 | |
3501 | case DeclarationName::CXXOperatorName: |
3502 | case DeclarationName::CXXConversionFunctionName: |
3503 | InvalidDecl = 6; |
3504 | break; |
3505 | |
3506 | default: |
3507 | InvalidDecl = 0; |
3508 | break; |
3509 | } |
3510 | |
3511 | if (InvalidDecl) { |
3512 | if (ShowDeclName) |
3513 | Diag(Loc, diag::err_invalid_member_in_interface) |
3514 | << (InvalidDecl-1) << Name; |
3515 | else |
3516 | Diag(Loc, diag::err_invalid_member_in_interface) |
3517 | << (InvalidDecl-1) << "" ; |
3518 | return nullptr; |
3519 | } |
3520 | } |
3521 | |
3522 | // C++ 9.2p6: A member shall not be declared to have automatic storage |
3523 | // duration (auto, register) or with the extern storage-class-specifier. |
3524 | // C++ 7.1.1p8: The mutable specifier can be applied only to names of class |
3525 | // data members and cannot be applied to names declared const or static, |
3526 | // and cannot be applied to reference members. |
3527 | switch (DS.getStorageClassSpec()) { |
3528 | case DeclSpec::SCS_unspecified: |
3529 | case DeclSpec::SCS_typedef: |
3530 | case DeclSpec::SCS_static: |
3531 | break; |
3532 | case DeclSpec::SCS_mutable: |
3533 | if (isFunc) { |
3534 | Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); |
3535 | |
3536 | // FIXME: It would be nicer if the keyword was ignored only for this |
3537 | // declarator. Otherwise we could get follow-up errors. |
3538 | D.getMutableDeclSpec().ClearStorageClassSpecs(); |
3539 | } |
3540 | break; |
3541 | default: |
3542 | Diag(DS.getStorageClassSpecLoc(), |
3543 | diag::err_storageclass_invalid_for_member); |
3544 | D.getMutableDeclSpec().ClearStorageClassSpecs(); |
3545 | break; |
3546 | } |
3547 | |
3548 | bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || |
3549 | DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && |
3550 | !isFunc); |
3551 | |
3552 | if (DS.hasConstexprSpecifier() && isInstField) { |
3553 | SemaDiagnosticBuilder B = |
3554 | Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); |
3555 | SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); |
3556 | if (InitStyle == ICIS_NoInit) { |
3557 | B << 0 << 0; |
3558 | if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) |
3559 | B << FixItHint::CreateRemoval(RemoveRange: ConstexprLoc); |
3560 | else { |
3561 | B << FixItHint::CreateReplacement(RemoveRange: ConstexprLoc, Code: "const" ); |
3562 | D.getMutableDeclSpec().ClearConstexprSpec(); |
3563 | const char *PrevSpec; |
3564 | unsigned DiagID; |
3565 | bool Failed = D.getMutableDeclSpec().SetTypeQual( |
3566 | T: DeclSpec::TQ_const, Loc: ConstexprLoc, PrevSpec, DiagID, Lang: getLangOpts()); |
3567 | (void)Failed; |
3568 | assert(!Failed && "Making a constexpr member const shouldn't fail" ); |
3569 | } |
3570 | } else { |
3571 | B << 1; |
3572 | const char *PrevSpec; |
3573 | unsigned DiagID; |
3574 | if (D.getMutableDeclSpec().SetStorageClassSpec( |
3575 | S&: *this, SC: DeclSpec::SCS_static, Loc: ConstexprLoc, PrevSpec, DiagID, |
3576 | Policy: Context.getPrintingPolicy())) { |
3577 | assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && |
3578 | "This is the only DeclSpec that should fail to be applied" ); |
3579 | B << 1; |
3580 | } else { |
3581 | B << 0 << FixItHint::CreateInsertion(InsertionLoc: ConstexprLoc, Code: "static " ); |
3582 | isInstField = false; |
3583 | } |
3584 | } |
3585 | } |
3586 | |
3587 | NamedDecl *Member; |
3588 | if (isInstField) { |
3589 | CXXScopeSpec &SS = D.getCXXScopeSpec(); |
3590 | |
3591 | // Data members must have identifiers for names. |
3592 | if (!Name.isIdentifier()) { |
3593 | Diag(Loc, diag::err_bad_variable_name) |
3594 | << Name; |
3595 | return nullptr; |
3596 | } |
3597 | |
3598 | IdentifierInfo *II = Name.getAsIdentifierInfo(); |
3599 | |
3600 | // Member field could not be with "template" keyword. |
3601 | // So TemplateParameterLists should be empty in this case. |
3602 | if (TemplateParameterLists.size()) { |
3603 | TemplateParameterList* TemplateParams = TemplateParameterLists[0]; |
3604 | if (TemplateParams->size()) { |
3605 | // There is no such thing as a member field template. |
3606 | Diag(D.getIdentifierLoc(), diag::err_template_member) |
3607 | << II |
3608 | << SourceRange(TemplateParams->getTemplateLoc(), |
3609 | TemplateParams->getRAngleLoc()); |
3610 | } else { |
3611 | // There is an extraneous 'template<>' for this member. |
3612 | Diag(TemplateParams->getTemplateLoc(), |
3613 | diag::err_template_member_noparams) |
3614 | << II |
3615 | << SourceRange(TemplateParams->getTemplateLoc(), |
3616 | TemplateParams->getRAngleLoc()); |
3617 | } |
3618 | return nullptr; |
3619 | } |
3620 | |
3621 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { |
3622 | Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments) |
3623 | << II |
3624 | << SourceRange(D.getName().TemplateId->LAngleLoc, |
3625 | D.getName().TemplateId->RAngleLoc) |
3626 | << D.getName().TemplateId->LAngleLoc; |
3627 | D.SetIdentifier(Id: II, IdLoc: Loc); |
3628 | } |
3629 | |
3630 | if (SS.isSet() && !SS.isInvalid()) { |
3631 | // The user provided a superfluous scope specifier inside a class |
3632 | // definition: |
3633 | // |
3634 | // class X { |
3635 | // int X::member; |
3636 | // }; |
3637 | if (DeclContext *DC = computeDeclContext(SS, EnteringContext: false)) { |
3638 | TemplateIdAnnotation *TemplateId = |
3639 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId |
3640 | ? D.getName().TemplateId |
3641 | : nullptr; |
3642 | diagnoseQualifiedDeclaration(SS, DC, Name, Loc: D.getIdentifierLoc(), |
3643 | TemplateId, |
3644 | /*IsMemberSpecialization=*/false); |
3645 | } else { |
3646 | Diag(D.getIdentifierLoc(), diag::err_member_qualification) |
3647 | << Name << SS.getRange(); |
3648 | } |
3649 | SS.clear(); |
3650 | } |
3651 | |
3652 | if (MSPropertyAttr) { |
3653 | Member = HandleMSProperty(S, cast<CXXRecordDecl>(Val: CurContext), Loc, D, |
3654 | BitWidth, InitStyle, AS, *MSPropertyAttr); |
3655 | if (!Member) |
3656 | return nullptr; |
3657 | isInstField = false; |
3658 | } else { |
3659 | Member = HandleField(S, cast<CXXRecordDecl>(Val: CurContext), Loc, D, |
3660 | BitWidth, InitStyle, AS); |
3661 | if (!Member) |
3662 | return nullptr; |
3663 | } |
3664 | |
3665 | CheckShadowInheritedFields(Loc, FieldName: Name, RD: cast<CXXRecordDecl>(Val: CurContext)); |
3666 | } else { |
3667 | Member = HandleDeclarator(S, D, TemplateParameterLists); |
3668 | if (!Member) |
3669 | return nullptr; |
3670 | |
3671 | // Non-instance-fields can't have a bitfield. |
3672 | if (BitWidth) { |
3673 | if (Member->isInvalidDecl()) { |
3674 | // don't emit another diagnostic. |
3675 | } else if (isa<VarDecl>(Val: Member) || isa<VarTemplateDecl>(Val: Member)) { |
3676 | // C++ 9.6p3: A bit-field shall not be a static member. |
3677 | // "static member 'A' cannot be a bit-field" |
3678 | Diag(Loc, diag::err_static_not_bitfield) |
3679 | << Name << BitWidth->getSourceRange(); |
3680 | } else if (isa<TypedefDecl>(Val: Member)) { |
3681 | // "typedef member 'x' cannot be a bit-field" |
3682 | Diag(Loc, diag::err_typedef_not_bitfield) |
3683 | << Name << BitWidth->getSourceRange(); |
3684 | } else { |
3685 | // A function typedef ("typedef int f(); f a;"). |
3686 | // C++ 9.6p3: A bit-field shall have integral or enumeration type. |
3687 | Diag(Loc, diag::err_not_integral_type_bitfield) |
3688 | << Name << cast<ValueDecl>(Member)->getType() |
3689 | << BitWidth->getSourceRange(); |
3690 | } |
3691 | |
3692 | BitWidth = nullptr; |
3693 | Member->setInvalidDecl(); |
3694 | } |
3695 | |
3696 | NamedDecl *NonTemplateMember = Member; |
3697 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Member)) |
3698 | NonTemplateMember = FunTmpl->getTemplatedDecl(); |
3699 | else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Val: Member)) |
3700 | NonTemplateMember = VarTmpl->getTemplatedDecl(); |
3701 | |
3702 | Member->setAccess(AS); |
3703 | |
3704 | // If we have declared a member function template or static data member |
3705 | // template, set the access of the templated declaration as well. |
3706 | if (NonTemplateMember != Member) |
3707 | NonTemplateMember->setAccess(AS); |
3708 | |
3709 | // C++ [temp.deduct.guide]p3: |
3710 | // A deduction guide [...] for a member class template [shall be |
3711 | // declared] with the same access [as the template]. |
3712 | if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: NonTemplateMember)) { |
3713 | auto *TD = DG->getDeducedTemplate(); |
3714 | // Access specifiers are only meaningful if both the template and the |
3715 | // deduction guide are from the same scope. |
3716 | if (AS != TD->getAccess() && |
3717 | TD->getDeclContext()->getRedeclContext()->Equals( |
3718 | DG->getDeclContext()->getRedeclContext())) { |
3719 | Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); |
3720 | Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) |
3721 | << TD->getAccess(); |
3722 | const AccessSpecDecl *LastAccessSpec = nullptr; |
3723 | for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { |
3724 | if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) |
3725 | LastAccessSpec = AccessSpec; |
3726 | } |
3727 | assert(LastAccessSpec && "differing access with no access specifier" ); |
3728 | Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) |
3729 | << AS; |
3730 | } |
3731 | } |
3732 | } |
3733 | |
3734 | if (VS.isOverrideSpecified()) |
3735 | Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc())); |
3736 | if (VS.isFinalSpecified()) |
3737 | Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(), |
3738 | VS.isFinalSpelledSealed() |
3739 | ? FinalAttr::Keyword_sealed |
3740 | : FinalAttr::Keyword_final)); |
3741 | |
3742 | if (VS.getLastLocation().isValid()) { |
3743 | // Update the end location of a method that has a virt-specifiers. |
3744 | if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Val: Member)) |
3745 | MD->setRangeEnd(VS.getLastLocation()); |
3746 | } |
3747 | |
3748 | CheckOverrideControl(D: Member); |
3749 | |
3750 | assert((Name || isInstField) && "No identifier for non-field ?" ); |
3751 | |
3752 | if (isInstField) { |
3753 | FieldDecl *FD = cast<FieldDecl>(Val: Member); |
3754 | FieldCollector->Add(D: FD); |
3755 | |
3756 | if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { |
3757 | // Remember all explicit private FieldDecls that have a name, no side |
3758 | // effects and are not part of a dependent type declaration. |
3759 | |
3760 | auto DeclHasUnusedAttr = [](const QualType &T) { |
3761 | if (const TagDecl *TD = T->getAsTagDecl()) |
3762 | return TD->hasAttr<UnusedAttr>(); |
3763 | if (const TypedefType *TDT = T->getAs<TypedefType>()) |
3764 | return TDT->getDecl()->hasAttr<UnusedAttr>(); |
3765 | return false; |
3766 | }; |
3767 | |
3768 | if (!FD->isImplicit() && FD->getDeclName() && |
3769 | FD->getAccess() == AS_private && |
3770 | !FD->hasAttr<UnusedAttr>() && |
3771 | !FD->getParent()->isDependentContext() && |
3772 | !DeclHasUnusedAttr(FD->getType()) && |
3773 | !InitializationHasSideEffects(*FD)) |
3774 | UnusedPrivateFields.insert(FD); |
3775 | } |
3776 | } |
3777 | |
3778 | return Member; |
3779 | } |
3780 | |
3781 | namespace { |
3782 | class UninitializedFieldVisitor |
3783 | : public EvaluatedExprVisitor<UninitializedFieldVisitor> { |
3784 | Sema &S; |
3785 | // List of Decls to generate a warning on. Also remove Decls that become |
3786 | // initialized. |
3787 | llvm::SmallPtrSetImpl<ValueDecl*> &Decls; |
3788 | // List of base classes of the record. Classes are removed after their |
3789 | // initializers. |
3790 | llvm::SmallPtrSetImpl<QualType> &BaseClasses; |
3791 | // Vector of decls to be removed from the Decl set prior to visiting the |
3792 | // nodes. These Decls may have been initialized in the prior initializer. |
3793 | llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; |
3794 | // If non-null, add a note to the warning pointing back to the constructor. |
3795 | const CXXConstructorDecl *Constructor; |
3796 | // Variables to hold state when processing an initializer list. When |
3797 | // InitList is true, special case initialization of FieldDecls matching |
3798 | // InitListFieldDecl. |
3799 | bool InitList; |
3800 | FieldDecl *InitListFieldDecl; |
3801 | llvm::SmallVector<unsigned, 4> InitFieldIndex; |
3802 | |
3803 | public: |
3804 | typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; |
3805 | UninitializedFieldVisitor(Sema &S, |
3806 | llvm::SmallPtrSetImpl<ValueDecl*> &Decls, |
3807 | llvm::SmallPtrSetImpl<QualType> &BaseClasses) |
3808 | : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), |
3809 | Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} |
3810 | |
3811 | // Returns true if the use of ME is not an uninitialized use. |
3812 | bool IsInitListMemberExprInitialized(MemberExpr *ME, |
3813 | bool CheckReferenceOnly) { |
3814 | llvm::SmallVector<FieldDecl*, 4> Fields; |
3815 | bool ReferenceField = false; |
3816 | while (ME) { |
3817 | FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl()); |
3818 | if (!FD) |
3819 | return false; |
3820 | Fields.push_back(Elt: FD); |
3821 | if (FD->getType()->isReferenceType()) |
3822 | ReferenceField = true; |
3823 | ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParenImpCasts()); |
3824 | } |
3825 | |
3826 | // Binding a reference to an uninitialized field is not an |
3827 | // uninitialized use. |
3828 | if (CheckReferenceOnly && !ReferenceField) |
3829 | return true; |
3830 | |
3831 | llvm::SmallVector<unsigned, 4> UsedFieldIndex; |
3832 | // Discard the first field since it is the field decl that is being |
3833 | // initialized. |
3834 | for (const FieldDecl *FD : llvm::drop_begin(RangeOrContainer: llvm::reverse(C&: Fields))) |
3835 | UsedFieldIndex.push_back(Elt: FD->getFieldIndex()); |
3836 | |
3837 | for (auto UsedIter = UsedFieldIndex.begin(), |
3838 | UsedEnd = UsedFieldIndex.end(), |
3839 | OrigIter = InitFieldIndex.begin(), |
3840 | OrigEnd = InitFieldIndex.end(); |
3841 | UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { |
3842 | if (*UsedIter < *OrigIter) |
3843 | return true; |
3844 | if (*UsedIter > *OrigIter) |
3845 | break; |
3846 | } |
3847 | |
3848 | return false; |
3849 | } |
3850 | |
3851 | void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, |
3852 | bool AddressOf) { |
3853 | if (isa<EnumConstantDecl>(Val: ME->getMemberDecl())) |
3854 | return; |
3855 | |
3856 | // FieldME is the inner-most MemberExpr that is not an anonymous struct |
3857 | // or union. |
3858 | MemberExpr *FieldME = ME; |
3859 | |
3860 | bool AllPODFields = FieldME->getType().isPODType(S.Context); |
3861 | |
3862 | Expr *Base = ME; |
3863 | while (MemberExpr *SubME = |
3864 | dyn_cast<MemberExpr>(Val: Base->IgnoreParenImpCasts())) { |
3865 | |
3866 | if (isa<VarDecl>(Val: SubME->getMemberDecl())) |
3867 | return; |
3868 | |
3869 | if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: SubME->getMemberDecl())) |
3870 | if (!FD->isAnonymousStructOrUnion()) |
3871 | FieldME = SubME; |
3872 | |
3873 | if (!FieldME->getType().isPODType(S.Context)) |
3874 | AllPODFields = false; |
3875 | |
3876 | Base = SubME->getBase(); |
3877 | } |
3878 | |
3879 | if (!isa<CXXThisExpr>(Val: Base->IgnoreParenImpCasts())) { |
3880 | Visit(Base); |
3881 | return; |
3882 | } |
3883 | |
3884 | if (AddressOf && AllPODFields) |
3885 | return; |
3886 | |
3887 | ValueDecl* FoundVD = FieldME->getMemberDecl(); |
3888 | |
3889 | if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Val: Base)) { |
3890 | while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { |
3891 | BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); |
3892 | } |
3893 | |
3894 | if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { |
3895 | QualType T = BaseCast->getType(); |
3896 | if (T->isPointerType() && |
3897 | BaseClasses.count(Ptr: T->getPointeeType())) { |
3898 | S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) |
3899 | << T->getPointeeType() << FoundVD; |
3900 | } |
3901 | } |
3902 | } |
3903 | |
3904 | if (!Decls.count(Ptr: FoundVD)) |
3905 | return; |
3906 | |
3907 | const bool IsReference = FoundVD->getType()->isReferenceType(); |
3908 | |
3909 | if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { |
3910 | // Special checking for initializer lists. |
3911 | if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { |
3912 | return; |
3913 | } |
3914 | } else { |
3915 | // Prevent double warnings on use of unbounded references. |
3916 | if (CheckReferenceOnly && !IsReference) |
3917 | return; |
3918 | } |
3919 | |
3920 | unsigned diag = IsReference |
3921 | ? diag::warn_reference_field_is_uninit |
3922 | : diag::warn_field_is_uninit; |
3923 | S.Diag(FieldME->getExprLoc(), diag) << FoundVD; |
3924 | if (Constructor) |
3925 | S.Diag(Constructor->getLocation(), |
3926 | diag::note_uninit_in_this_constructor) |
3927 | << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); |
3928 | |
3929 | } |
3930 | |
3931 | void HandleValue(Expr *E, bool AddressOf) { |
3932 | E = E->IgnoreParens(); |
3933 | |
3934 | if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) { |
3935 | HandleMemberExpr(ME, CheckReferenceOnly: false /*CheckReferenceOnly*/, |
3936 | AddressOf /*AddressOf*/); |
3937 | return; |
3938 | } |
3939 | |
3940 | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) { |
3941 | Visit(CO->getCond()); |
3942 | HandleValue(E: CO->getTrueExpr(), AddressOf); |
3943 | HandleValue(E: CO->getFalseExpr(), AddressOf); |
3944 | return; |
3945 | } |
3946 | |
3947 | if (BinaryConditionalOperator *BCO = |
3948 | dyn_cast<BinaryConditionalOperator>(Val: E)) { |
3949 | Visit(BCO->getCond()); |
3950 | HandleValue(E: BCO->getFalseExpr(), AddressOf); |
3951 | return; |
3952 | } |
3953 | |
3954 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) { |
3955 | HandleValue(E: OVE->getSourceExpr(), AddressOf); |
3956 | return; |
3957 | } |
3958 | |
3959 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) { |
3960 | switch (BO->getOpcode()) { |
3961 | default: |
3962 | break; |
3963 | case(BO_PtrMemD): |
3964 | case(BO_PtrMemI): |
3965 | HandleValue(E: BO->getLHS(), AddressOf); |
3966 | Visit(BO->getRHS()); |
3967 | return; |
3968 | case(BO_Comma): |
3969 | Visit(BO->getLHS()); |
3970 | HandleValue(E: BO->getRHS(), AddressOf); |
3971 | return; |
3972 | } |
3973 | } |
3974 | |
3975 | Visit(E); |
3976 | } |
3977 | |
3978 | void CheckInitListExpr(InitListExpr *ILE) { |
3979 | InitFieldIndex.push_back(Elt: 0); |
3980 | for (auto *Child : ILE->children()) { |
3981 | if (InitListExpr *SubList = dyn_cast<InitListExpr>(Val: Child)) { |
3982 | CheckInitListExpr(ILE: SubList); |
3983 | } else { |
3984 | Visit(S: Child); |
3985 | } |
3986 | ++InitFieldIndex.back(); |
3987 | } |
3988 | InitFieldIndex.pop_back(); |
3989 | } |
3990 | |
3991 | void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, |
3992 | FieldDecl *Field, const Type *BaseClass) { |
3993 | // Remove Decls that may have been initialized in the previous |
3994 | // initializer. |
3995 | for (ValueDecl* VD : DeclsToRemove) |
3996 | Decls.erase(Ptr: VD); |
3997 | DeclsToRemove.clear(); |
3998 | |
3999 | Constructor = FieldConstructor; |
4000 | InitListExpr *ILE = dyn_cast<InitListExpr>(Val: E); |
4001 | |
4002 | if (ILE && Field) { |
4003 | InitList = true; |
4004 | InitListFieldDecl = Field; |
4005 | InitFieldIndex.clear(); |
4006 | CheckInitListExpr(ILE); |
4007 | } else { |
4008 | InitList = false; |
4009 | Visit(E); |
4010 | } |
4011 | |
4012 | if (Field) |
4013 | Decls.erase(Field); |
4014 | if (BaseClass) |
4015 | BaseClasses.erase(Ptr: BaseClass->getCanonicalTypeInternal()); |
4016 | } |
4017 | |
4018 | void VisitMemberExpr(MemberExpr *ME) { |
4019 | // All uses of unbounded reference fields will warn. |
4020 | HandleMemberExpr(ME, CheckReferenceOnly: true /*CheckReferenceOnly*/, AddressOf: false /*AddressOf*/); |
4021 | } |
4022 | |
4023 | void VisitImplicitCastExpr(ImplicitCastExpr *E) { |
4024 | if (E->getCastKind() == CK_LValueToRValue) { |
4025 | HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/); |
4026 | return; |
4027 | } |
4028 | |
4029 | Inherited::VisitImplicitCastExpr(E); |
4030 | } |
4031 | |
4032 | void VisitCXXConstructExpr(CXXConstructExpr *E) { |
4033 | if (E->getConstructor()->isCopyConstructor()) { |
4034 | Expr *ArgExpr = E->getArg(Arg: 0); |
4035 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr)) |
4036 | if (ILE->getNumInits() == 1) |
4037 | ArgExpr = ILE->getInit(Init: 0); |
4038 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr)) |
4039 | if (ICE->getCastKind() == CK_NoOp) |
4040 | ArgExpr = ICE->getSubExpr(); |
4041 | HandleValue(E: ArgExpr, AddressOf: false /*AddressOf*/); |
4042 | return; |
4043 | } |
4044 | Inherited::VisitCXXConstructExpr(E); |
4045 | } |
4046 | |
4047 | void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { |
4048 | Expr *Callee = E->getCallee(); |
4049 | if (isa<MemberExpr>(Val: Callee)) { |
4050 | HandleValue(E: Callee, AddressOf: false /*AddressOf*/); |
4051 | for (auto *Arg : E->arguments()) |
4052 | Visit(Arg); |
4053 | return; |
4054 | } |
4055 | |
4056 | Inherited::VisitCXXMemberCallExpr(E); |
4057 | } |
4058 | |
4059 | void VisitCallExpr(CallExpr *E) { |
4060 | // Treat std::move as a use. |
4061 | if (E->isCallToStdMove()) { |
4062 | HandleValue(E: E->getArg(Arg: 0), /*AddressOf=*/false); |
4063 | return; |
4064 | } |
4065 | |
4066 | Inherited::VisitCallExpr(CE: E); |
4067 | } |
4068 | |
4069 | void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { |
4070 | Expr *Callee = E->getCallee(); |
4071 | |
4072 | if (isa<UnresolvedLookupExpr>(Callee)) |
4073 | return Inherited::VisitCXXOperatorCallExpr(E); |
4074 | |
4075 | Visit(Callee); |
4076 | for (auto *Arg : E->arguments()) |
4077 | HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); |
4078 | } |
4079 | |
4080 | void VisitBinaryOperator(BinaryOperator *E) { |
4081 | // If a field assignment is detected, remove the field from the |
4082 | // uninitiailized field set. |
4083 | if (E->getOpcode() == BO_Assign) |
4084 | if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getLHS())) |
4085 | if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl())) |
4086 | if (!FD->getType()->isReferenceType()) |
4087 | DeclsToRemove.push_back(FD); |
4088 | |
4089 | if (E->isCompoundAssignmentOp()) { |
4090 | HandleValue(E: E->getLHS(), AddressOf: false /*AddressOf*/); |
4091 | Visit(E->getRHS()); |
4092 | return; |
4093 | } |
4094 | |
4095 | Inherited::VisitBinaryOperator(E); |
4096 | } |
4097 | |
4098 | void VisitUnaryOperator(UnaryOperator *E) { |
4099 | if (E->isIncrementDecrementOp()) { |
4100 | HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/); |
4101 | return; |
4102 | } |
4103 | if (E->getOpcode() == UO_AddrOf) { |
4104 | if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getSubExpr())) { |
4105 | HandleValue(E: ME->getBase(), AddressOf: true /*AddressOf*/); |
4106 | return; |
4107 | } |
4108 | } |
4109 | |
4110 | Inherited::VisitUnaryOperator(E); |
4111 | } |
4112 | }; |
4113 | |
4114 | // Diagnose value-uses of fields to initialize themselves, e.g. |
4115 | // foo(foo) |
4116 | // where foo is not also a parameter to the constructor. |
4117 | // Also diagnose across field uninitialized use such as |
4118 | // x(y), y(x) |
4119 | // TODO: implement -Wuninitialized and fold this into that framework. |
4120 | static void DiagnoseUninitializedFields( |
4121 | Sema &SemaRef, const CXXConstructorDecl *Constructor) { |
4122 | |
4123 | if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, |
4124 | Constructor->getLocation())) { |
4125 | return; |
4126 | } |
4127 | |
4128 | if (Constructor->isInvalidDecl()) |
4129 | return; |
4130 | |
4131 | const CXXRecordDecl *RD = Constructor->getParent(); |
4132 | |
4133 | if (RD->isDependentContext()) |
4134 | return; |
4135 | |
4136 | // Holds fields that are uninitialized. |
4137 | llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; |
4138 | |
4139 | // At the beginning, all fields are uninitialized. |
4140 | for (auto *I : RD->decls()) { |
4141 | if (auto *FD = dyn_cast<FieldDecl>(I)) { |
4142 | UninitializedFields.insert(FD); |
4143 | } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { |
4144 | UninitializedFields.insert(IFD->getAnonField()); |
4145 | } |
4146 | } |
4147 | |
4148 | llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; |
4149 | for (const auto &I : RD->bases()) |
4150 | UninitializedBaseClasses.insert(I.getType().getCanonicalType()); |
4151 | |
4152 | if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) |
4153 | return; |
4154 | |
4155 | UninitializedFieldVisitor UninitializedChecker(SemaRef, |
4156 | UninitializedFields, |
4157 | UninitializedBaseClasses); |
4158 | |
4159 | for (const auto *FieldInit : Constructor->inits()) { |
4160 | if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) |
4161 | break; |
4162 | |
4163 | Expr *InitExpr = FieldInit->getInit(); |
4164 | if (!InitExpr) |
4165 | continue; |
4166 | |
4167 | if (CXXDefaultInitExpr *Default = |
4168 | dyn_cast<CXXDefaultInitExpr>(Val: InitExpr)) { |
4169 | InitExpr = Default->getExpr(); |
4170 | if (!InitExpr) |
4171 | continue; |
4172 | // In class initializers will point to the constructor. |
4173 | UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: Constructor, |
4174 | Field: FieldInit->getAnyMember(), |
4175 | BaseClass: FieldInit->getBaseClass()); |
4176 | } else { |
4177 | UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: nullptr, |
4178 | Field: FieldInit->getAnyMember(), |
4179 | BaseClass: FieldInit->getBaseClass()); |
4180 | } |
4181 | } |
4182 | } |
4183 | } // namespace |
4184 | |
4185 | /// Enter a new C++ default initializer scope. After calling this, the |
4186 | /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if |
4187 | /// parsing or instantiating the initializer failed. |
4188 | void Sema::ActOnStartCXXInClassMemberInitializer() { |
4189 | // Create a synthetic function scope to represent the call to the constructor |
4190 | // that notionally surrounds a use of this initializer. |
4191 | PushFunctionScope(); |
4192 | } |
4193 | |
4194 | void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { |
4195 | if (!D.isFunctionDeclarator()) |
4196 | return; |
4197 | auto &FTI = D.getFunctionTypeInfo(); |
4198 | if (!FTI.Params) |
4199 | return; |
4200 | for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, |
4201 | FTI.NumParams)) { |
4202 | auto *ParamDecl = cast<NamedDecl>(Val: Param.Param); |
4203 | if (ParamDecl->getDeclName()) |
4204 | PushOnScopeChains(D: ParamDecl, S, /*AddToContext=*/false); |
4205 | } |
4206 | } |
4207 | |
4208 | ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { |
4209 | return ActOnRequiresClause(ConstraintExpr); |
4210 | } |
4211 | |
4212 | ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { |
4213 | if (ConstraintExpr.isInvalid()) |
4214 | return ExprError(); |
4215 | |
4216 | ConstraintExpr = CorrectDelayedTyposInExpr(ER: ConstraintExpr); |
4217 | if (ConstraintExpr.isInvalid()) |
4218 | return ExprError(); |
4219 | |
4220 | if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr.get(), |
4221 | UPPC: UPPC_RequiresClause)) |
4222 | return ExprError(); |
4223 | |
4224 | return ConstraintExpr; |
4225 | } |
4226 | |
4227 | ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD, |
4228 | Expr *InitExpr, |
4229 | SourceLocation InitLoc) { |
4230 | InitializedEntity Entity = |
4231 | InitializedEntity::InitializeMemberFromDefaultMemberInitializer(Member: FD); |
4232 | InitializationKind Kind = |
4233 | FD->getInClassInitStyle() == ICIS_ListInit |
4234 | ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), |
4235 | InitExpr->getBeginLoc(), |
4236 | InitExpr->getEndLoc()) |
4237 | : InitializationKind::CreateCopy(InitLoc: InitExpr->getBeginLoc(), EqualLoc: InitLoc); |
4238 | InitializationSequence Seq(*this, Entity, Kind, InitExpr); |
4239 | return Seq.Perform(S&: *this, Entity, Kind, Args: InitExpr); |
4240 | } |
4241 | |
4242 | /// This is invoked after parsing an in-class initializer for a |
4243 | /// non-static C++ class member, and after instantiating an in-class initializer |
4244 | /// in a class template. Such actions are deferred until the class is complete. |
4245 | void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, |
4246 | SourceLocation InitLoc, |
4247 | Expr *InitExpr) { |
4248 | // Pop the notional constructor scope we created earlier. |
4249 | PopFunctionScopeInfo(WP: nullptr, D); |
4250 | |
4251 | FieldDecl *FD = dyn_cast<FieldDecl>(Val: D); |
4252 | assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && |
4253 | "must set init style when field is created" ); |
4254 | |
4255 | if (!InitExpr) { |
4256 | D->setInvalidDecl(); |
4257 | if (FD) |
4258 | FD->removeInClassInitializer(); |
4259 | return; |
4260 | } |
4261 | |
4262 | if (DiagnoseUnexpandedParameterPack(E: InitExpr, UPPC: UPPC_Initializer)) { |
4263 | FD->setInvalidDecl(); |
4264 | FD->removeInClassInitializer(); |
4265 | return; |
4266 | } |
4267 | |
4268 | ExprResult Init = CorrectDelayedTyposInExpr(E: InitExpr, /*InitDecl=*/nullptr, |
4269 | /*RecoverUncorrectedTypos=*/true); |
4270 | assert(Init.isUsable() && "Init should at least have a RecoveryExpr" ); |
4271 | if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) { |
4272 | Init = ConvertMemberDefaultInitExpression(FD, InitExpr: Init.get(), InitLoc); |
4273 | // C++11 [class.base.init]p7: |
4274 | // The initialization of each base and member constitutes a |
4275 | // full-expression. |
4276 | if (!Init.isInvalid()) |
4277 | Init = ActOnFinishFullExpr(Expr: Init.get(), /*DiscarededValue=*/DiscardedValue: false); |
4278 | if (Init.isInvalid()) { |
4279 | FD->setInvalidDecl(); |
4280 | return; |
4281 | } |
4282 | } |
4283 | |
4284 | FD->setInClassInitializer(Init.get()); |
4285 | } |
4286 | |
4287 | /// Find the direct and/or virtual base specifiers that |
4288 | /// correspond to the given base type, for use in base initialization |
4289 | /// within a constructor. |
4290 | static bool FindBaseInitializer(Sema &SemaRef, |
4291 | CXXRecordDecl *ClassDecl, |
4292 | QualType BaseType, |
4293 | const CXXBaseSpecifier *&DirectBaseSpec, |
4294 | const CXXBaseSpecifier *&VirtualBaseSpec) { |
4295 | // First, check for a direct base class. |
4296 | DirectBaseSpec = nullptr; |
4297 | for (const auto &Base : ClassDecl->bases()) { |
4298 | if (SemaRef.Context.hasSameUnqualifiedType(T1: BaseType, T2: Base.getType())) { |
4299 | // We found a direct base of this type. That's what we're |
4300 | // initializing. |
4301 | DirectBaseSpec = &Base; |
4302 | break; |
4303 | } |
4304 | } |
4305 | |
4306 | // Check for a virtual base class. |
4307 | // FIXME: We might be able to short-circuit this if we know in advance that |
4308 | // there are no virtual bases. |
4309 | VirtualBaseSpec = nullptr; |
4310 | if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { |
4311 | // We haven't found a base yet; search the class hierarchy for a |
4312 | // virtual base class. |
4313 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, |
4314 | /*DetectVirtual=*/false); |
4315 | if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), |
4316 | SemaRef.Context.getTypeDeclType(ClassDecl), |
4317 | BaseType, Paths)) { |
4318 | for (CXXBasePaths::paths_iterator Path = Paths.begin(); |
4319 | Path != Paths.end(); ++Path) { |
4320 | if (Path->back().Base->isVirtual()) { |
4321 | VirtualBaseSpec = Path->back().Base; |
4322 | break; |
4323 | } |
4324 | } |
4325 | } |
4326 | } |
4327 | |
4328 | return DirectBaseSpec || VirtualBaseSpec; |
4329 | } |
4330 | |
4331 | /// Handle a C++ member initializer using braced-init-list syntax. |
4332 | MemInitResult |
4333 | Sema::ActOnMemInitializer(Decl *ConstructorD, |
4334 | Scope *S, |
4335 | CXXScopeSpec &SS, |
4336 | IdentifierInfo *MemberOrBase, |
4337 | ParsedType TemplateTypeTy, |
4338 | const DeclSpec &DS, |
4339 | SourceLocation IdLoc, |
4340 | Expr *InitList, |
4341 | SourceLocation EllipsisLoc) { |
4342 | return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, |
4343 | DS, IdLoc, Init: InitList, |
4344 | EllipsisLoc); |
4345 | } |
4346 | |
4347 | /// Handle a C++ member initializer using parentheses syntax. |
4348 | MemInitResult |
4349 | Sema::ActOnMemInitializer(Decl *ConstructorD, |
4350 | Scope *S, |
4351 | CXXScopeSpec &SS, |
4352 | IdentifierInfo *MemberOrBase, |
4353 | ParsedType TemplateTypeTy, |
4354 | const DeclSpec &DS, |
4355 | SourceLocation IdLoc, |
4356 | SourceLocation LParenLoc, |
4357 | ArrayRef<Expr *> Args, |
4358 | SourceLocation RParenLoc, |
4359 | SourceLocation EllipsisLoc) { |
4360 | Expr *List = ParenListExpr::Create(Ctx: Context, LParenLoc, Exprs: Args, RParenLoc); |
4361 | return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, |
4362 | DS, IdLoc, Init: List, EllipsisLoc); |
4363 | } |
4364 | |
4365 | namespace { |
4366 | |
4367 | // Callback to only accept typo corrections that can be a valid C++ member |
4368 | // initializer: either a non-static field member or a base class. |
4369 | class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { |
4370 | public: |
4371 | explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) |
4372 | : ClassDecl(ClassDecl) {} |
4373 | |
4374 | bool ValidateCandidate(const TypoCorrection &candidate) override { |
4375 | if (NamedDecl *ND = candidate.getCorrectionDecl()) { |
4376 | if (FieldDecl *Member = dyn_cast<FieldDecl>(Val: ND)) |
4377 | return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); |
4378 | return isa<TypeDecl>(Val: ND); |
4379 | } |
4380 | return false; |
4381 | } |
4382 | |
4383 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
4384 | return std::make_unique<MemInitializerValidatorCCC>(args&: *this); |
4385 | } |
4386 | |
4387 | private: |
4388 | CXXRecordDecl *ClassDecl; |
4389 | }; |
4390 | |
4391 | } |
4392 | |
4393 | bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc, |
4394 | RecordDecl *ClassDecl, |
4395 | const IdentifierInfo *Name) { |
4396 | DeclContextLookupResult Result = ClassDecl->lookup(Name); |
4397 | DeclContextLookupResult::iterator Found = |
4398 | llvm::find_if(Range&: Result, P: [this](const NamedDecl *Elem) { |
4399 | return isa<FieldDecl, IndirectFieldDecl>(Val: Elem) && |
4400 | Elem->isPlaceholderVar(LangOpts: getLangOpts()); |
4401 | }); |
4402 | // We did not find a placeholder variable |
4403 | if (Found == Result.end()) |
4404 | return false; |
4405 | Diag(Loc, diag::err_using_placeholder_variable) << Name; |
4406 | for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) { |
4407 | const NamedDecl *ND = *It; |
4408 | if (ND->getDeclContext() != ND->getDeclContext()) |
4409 | break; |
4410 | if (isa<FieldDecl, IndirectFieldDecl>(ND) && |
4411 | ND->isPlaceholderVar(getLangOpts())) |
4412 | Diag(ND->getLocation(), diag::note_reference_placeholder) << ND; |
4413 | } |
4414 | return true; |
4415 | } |
4416 | |
4417 | ValueDecl * |
4418 | Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl, |
4419 | const IdentifierInfo *MemberOrBase) { |
4420 | ValueDecl *ND = nullptr; |
4421 | for (auto *D : ClassDecl->lookup(MemberOrBase)) { |
4422 | if (isa<FieldDecl, IndirectFieldDecl>(D)) { |
4423 | bool IsPlaceholder = D->isPlaceholderVar(getLangOpts()); |
4424 | if (ND) { |
4425 | if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext()) |
4426 | return nullptr; |
4427 | break; |
4428 | } |
4429 | if (!IsPlaceholder) |
4430 | return cast<ValueDecl>(D); |
4431 | ND = cast<ValueDecl>(D); |
4432 | } |
4433 | } |
4434 | return ND; |
4435 | } |
4436 | |
4437 | ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, |
4438 | CXXScopeSpec &SS, |
4439 | ParsedType TemplateTypeTy, |
4440 | IdentifierInfo *MemberOrBase) { |
4441 | if (SS.getScopeRep() || TemplateTypeTy) |
4442 | return nullptr; |
4443 | return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase); |
4444 | } |
4445 | |
4446 | /// Handle a C++ member initializer. |
4447 | MemInitResult |
4448 | Sema::BuildMemInitializer(Decl *ConstructorD, |
4449 | Scope *S, |
4450 | CXXScopeSpec &SS, |
4451 | IdentifierInfo *MemberOrBase, |
4452 | ParsedType TemplateTypeTy, |
4453 | const DeclSpec &DS, |
4454 | SourceLocation IdLoc, |
4455 | Expr *Init, |
4456 | SourceLocation EllipsisLoc) { |
4457 | ExprResult Res = CorrectDelayedTyposInExpr(E: Init, /*InitDecl=*/nullptr, |
4458 | /*RecoverUncorrectedTypos=*/true); |
4459 | if (!Res.isUsable()) |
4460 | return true; |
4461 | Init = Res.get(); |
4462 | |
4463 | if (!ConstructorD) |
4464 | return true; |
4465 | |
4466 | AdjustDeclIfTemplate(Decl&: ConstructorD); |
4467 | |
4468 | CXXConstructorDecl *Constructor |
4469 | = dyn_cast<CXXConstructorDecl>(Val: ConstructorD); |
4470 | if (!Constructor) { |
4471 | // The user wrote a constructor initializer on a function that is |
4472 | // not a C++ constructor. Ignore the error for now, because we may |
4473 | // have more member initializers coming; we'll diagnose it just |
4474 | // once in ActOnMemInitializers. |
4475 | return true; |
4476 | } |
4477 | |
4478 | CXXRecordDecl *ClassDecl = Constructor->getParent(); |
4479 | |
4480 | // C++ [class.base.init]p2: |
4481 | // Names in a mem-initializer-id are looked up in the scope of the |
4482 | // constructor's class and, if not found in that scope, are looked |
4483 | // up in the scope containing the constructor's definition. |
4484 | // [Note: if the constructor's class contains a member with the |
4485 | // same name as a direct or virtual base class of the class, a |
4486 | // mem-initializer-id naming the member or base class and composed |
4487 | // of a single identifier refers to the class member. A |
4488 | // mem-initializer-id for the hidden base class may be specified |
4489 | // using a qualified name. ] |
4490 | |
4491 | // Look for a member, first. |
4492 | if (ValueDecl *Member = tryLookupCtorInitMemberDecl( |
4493 | ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { |
4494 | if (EllipsisLoc.isValid()) |
4495 | Diag(EllipsisLoc, diag::err_pack_expansion_member_init) |
4496 | << MemberOrBase |
4497 | << SourceRange(IdLoc, Init->getSourceRange().getEnd()); |
4498 | |
4499 | return BuildMemberInitializer(Member, Init, IdLoc); |
4500 | } |
4501 | // It didn't name a member, so see if it names a class. |
4502 | QualType BaseType; |
4503 | TypeSourceInfo *TInfo = nullptr; |
4504 | |
4505 | if (TemplateTypeTy) { |
4506 | BaseType = GetTypeFromParser(Ty: TemplateTypeTy, TInfo: &TInfo); |
4507 | if (BaseType.isNull()) |
4508 | return true; |
4509 | } else if (DS.getTypeSpecType() == TST_decltype) { |
4510 | BaseType = BuildDecltypeType(E: DS.getRepAsExpr()); |
4511 | } else if (DS.getTypeSpecType() == TST_decltype_auto) { |
4512 | Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); |
4513 | return true; |
4514 | } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) { |
4515 | BaseType = |
4516 | BuildPackIndexingType(Pattern: DS.getRepAsType().get(), IndexExpr: DS.getPackIndexingExpr(), |
4517 | Loc: DS.getBeginLoc(), EllipsisLoc: DS.getEllipsisLoc()); |
4518 | } else { |
4519 | LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); |
4520 | LookupParsedName(R, S, SS: &SS); |
4521 | |
4522 | TypeDecl *TyD = R.getAsSingle<TypeDecl>(); |
4523 | if (!TyD) { |
4524 | if (R.isAmbiguous()) return true; |
4525 | |
4526 | // We don't want access-control diagnostics here. |
4527 | R.suppressDiagnostics(); |
4528 | |
4529 | if (SS.isSet() && isDependentScopeSpecifier(SS)) { |
4530 | bool NotUnknownSpecialization = false; |
4531 | DeclContext *DC = computeDeclContext(SS, EnteringContext: false); |
4532 | if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Val: DC)) |
4533 | NotUnknownSpecialization = !Record->hasAnyDependentBases(); |
4534 | |
4535 | if (!NotUnknownSpecialization) { |
4536 | // When the scope specifier can refer to a member of an unknown |
4537 | // specialization, we take it as a type name. |
4538 | BaseType = CheckTypenameType( |
4539 | Keyword: ElaboratedTypeKeyword::None, KeywordLoc: SourceLocation(), |
4540 | QualifierLoc: SS.getWithLocInContext(Context), II: *MemberOrBase, IILoc: IdLoc); |
4541 | if (BaseType.isNull()) |
4542 | return true; |
4543 | |
4544 | TInfo = Context.CreateTypeSourceInfo(T: BaseType); |
4545 | DependentNameTypeLoc TL = |
4546 | TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); |
4547 | if (!TL.isNull()) { |
4548 | TL.setNameLoc(IdLoc); |
4549 | TL.setElaboratedKeywordLoc(SourceLocation()); |
4550 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); |
4551 | } |
4552 | |
4553 | R.clear(); |
4554 | R.setLookupName(MemberOrBase); |
4555 | } |
4556 | } |
4557 | |
4558 | if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) { |
4559 | if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) { |
4560 | auto *TempSpec = cast<TemplateSpecializationType>( |
4561 | Val: UnqualifiedBase->getInjectedClassNameSpecialization()); |
4562 | TemplateName TN = TempSpec->getTemplateName(); |
4563 | for (auto const &Base : ClassDecl->bases()) { |
4564 | auto BaseTemplate = |
4565 | Base.getType()->getAs<TemplateSpecializationType>(); |
4566 | if (BaseTemplate && Context.hasSameTemplateName( |
4567 | BaseTemplate->getTemplateName(), TN)) { |
4568 | Diag(IdLoc, diag::ext_unqualified_base_class) |
4569 | << SourceRange(IdLoc, Init->getSourceRange().getEnd()); |
4570 | BaseType = Base.getType(); |
4571 | break; |
4572 | } |
4573 | } |
4574 | } |
4575 | } |
4576 | |
4577 | // If no results were found, try to correct typos. |
4578 | TypoCorrection Corr; |
4579 | MemInitializerValidatorCCC CCC(ClassDecl); |
4580 | if (R.empty() && BaseType.isNull() && |
4581 | (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, |
4582 | CCC, CTK_ErrorRecovery, ClassDecl))) { |
4583 | if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { |
4584 | // We have found a non-static data member with a similar |
4585 | // name to what was typed; complain and initialize that |
4586 | // member. |
4587 | diagnoseTypo(Corr, |
4588 | PDiag(diag::err_mem_init_not_member_or_class_suggest) |
4589 | << MemberOrBase << true); |
4590 | return BuildMemberInitializer(Member, Init, IdLoc); |
4591 | } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { |
4592 | const CXXBaseSpecifier *DirectBaseSpec; |
4593 | const CXXBaseSpecifier *VirtualBaseSpec; |
4594 | if (FindBaseInitializer(SemaRef&: *this, ClassDecl, |
4595 | BaseType: Context.getTypeDeclType(Decl: Type), |
4596 | DirectBaseSpec, VirtualBaseSpec)) { |
4597 | // We have found a direct or virtual base class with a |
4598 | // similar name to what was typed; complain and initialize |
4599 | // that base class. |
4600 | diagnoseTypo(Corr, |
4601 | PDiag(diag::err_mem_init_not_member_or_class_suggest) |
4602 | << MemberOrBase << false, |
4603 | PDiag() /*Suppress note, we provide our own.*/); |
4604 | |
4605 | const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec |
4606 | : VirtualBaseSpec; |
4607 | Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) |
4608 | << BaseSpec->getType() << BaseSpec->getSourceRange(); |
4609 | |
4610 | TyD = Type; |
4611 | } |
4612 | } |
4613 | } |
4614 | |
4615 | if (!TyD && BaseType.isNull()) { |
4616 | Diag(IdLoc, diag::err_mem_init_not_member_or_class) |
4617 | << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); |
4618 | return true; |
4619 | } |
4620 | } |
4621 | |
4622 | if (BaseType.isNull()) { |
4623 | BaseType = getElaboratedType(Keyword: ElaboratedTypeKeyword::None, SS, |
4624 | T: Context.getTypeDeclType(Decl: TyD)); |
4625 | MarkAnyDeclReferenced(Loc: TyD->getLocation(), D: TyD, /*OdrUse=*/MightBeOdrUse: false); |
4626 | TInfo = Context.CreateTypeSourceInfo(T: BaseType); |
4627 | ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); |
4628 | TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); |
4629 | TL.setElaboratedKeywordLoc(SourceLocation()); |
4630 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); |
4631 | } |
4632 | } |
4633 | |
4634 | if (!TInfo) |
4635 | TInfo = Context.getTrivialTypeSourceInfo(T: BaseType, Loc: IdLoc); |
4636 | |
4637 | return BuildBaseInitializer(BaseType, BaseTInfo: TInfo, Init, ClassDecl, EllipsisLoc); |
4638 | } |
4639 | |
4640 | MemInitResult |
4641 | Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, |
4642 | SourceLocation IdLoc) { |
4643 | FieldDecl *DirectMember = dyn_cast<FieldDecl>(Val: Member); |
4644 | IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Val: Member); |
4645 | assert((DirectMember || IndirectMember) && |
4646 | "Member must be a FieldDecl or IndirectFieldDecl" ); |
4647 | |
4648 | if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) |
4649 | return true; |
4650 | |
4651 | if (Member->isInvalidDecl()) |
4652 | return true; |
4653 | |
4654 | MultiExprArg Args; |
4655 | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) { |
4656 | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); |
4657 | } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) { |
4658 | Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); |
4659 | } else { |
4660 | // Template instantiation doesn't reconstruct ParenListExprs for us. |
4661 | Args = Init; |
4662 | } |
4663 | |
4664 | SourceRange InitRange = Init->getSourceRange(); |
4665 | |
4666 | if (Member->getType()->isDependentType() || Init->isTypeDependent()) { |
4667 | // Can't check initialization for a member of dependent type or when |
4668 | // any of the arguments are type-dependent expressions. |
4669 | DiscardCleanupsInEvaluationContext(); |
4670 | } else { |
4671 | bool InitList = false; |
4672 | if (isa<InitListExpr>(Val: Init)) { |
4673 | InitList = true; |
4674 | Args = Init; |
4675 | } |
4676 | |
4677 | // Initialize the member. |
4678 | InitializedEntity MemberEntity = |
4679 | DirectMember ? InitializedEntity::InitializeMember(Member: DirectMember, Parent: nullptr) |
4680 | : InitializedEntity::InitializeMember(Member: IndirectMember, |
4681 | Parent: nullptr); |
4682 | InitializationKind Kind = |
4683 | InitList ? InitializationKind::CreateDirectList( |
4684 | IdLoc, Init->getBeginLoc(), Init->getEndLoc()) |
4685 | : InitializationKind::CreateDirect(InitLoc: IdLoc, LParenLoc: InitRange.getBegin(), |
4686 | RParenLoc: InitRange.getEnd()); |
4687 | |
4688 | InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); |
4689 | ExprResult MemberInit = InitSeq.Perform(S&: *this, Entity: MemberEntity, Kind, Args, |
4690 | ResultType: nullptr); |
4691 | if (!MemberInit.isInvalid()) { |
4692 | // C++11 [class.base.init]p7: |
4693 | // The initialization of each base and member constitutes a |
4694 | // full-expression. |
4695 | MemberInit = ActOnFinishFullExpr(Expr: MemberInit.get(), CC: InitRange.getBegin(), |
4696 | /*DiscardedValue*/ false); |
4697 | } |
4698 | |
4699 | if (MemberInit.isInvalid()) { |
4700 | // Args were sensible expressions but we couldn't initialize the member |
4701 | // from them. Preserve them in a RecoveryExpr instead. |
4702 | Init = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), SubExprs: Args, |
4703 | T: Member->getType()) |
4704 | .get(); |
4705 | if (!Init) |
4706 | return true; |
4707 | } else { |
4708 | Init = MemberInit.get(); |
4709 | } |
4710 | } |
4711 | |
4712 | if (DirectMember) { |
4713 | return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, |
4714 | InitRange.getBegin(), Init, |
4715 | InitRange.getEnd()); |
4716 | } else { |
4717 | return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, |
4718 | InitRange.getBegin(), Init, |
4719 | InitRange.getEnd()); |
4720 | } |
4721 | } |
4722 | |
4723 | MemInitResult |
4724 | Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, |
4725 | CXXRecordDecl *ClassDecl) { |
4726 | SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin(); |
4727 | if (!LangOpts.CPlusPlus11) |
4728 | return Diag(NameLoc, diag::err_delegating_ctor) |
4729 | << TInfo->getTypeLoc().getSourceRange(); |
4730 | Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); |
4731 | |
4732 | bool InitList = true; |
4733 | MultiExprArg Args = Init; |
4734 | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) { |
4735 | InitList = false; |
4736 | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); |
4737 | } |
4738 | |
4739 | SourceRange InitRange = Init->getSourceRange(); |
4740 | // Initialize the object. |
4741 | InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( |
4742 | Type: QualType(ClassDecl->getTypeForDecl(), 0)); |
4743 | InitializationKind Kind = |
4744 | InitList ? InitializationKind::CreateDirectList( |
4745 | NameLoc, Init->getBeginLoc(), Init->getEndLoc()) |
4746 | : InitializationKind::CreateDirect(InitLoc: NameLoc, LParenLoc: InitRange.getBegin(), |
4747 | RParenLoc: InitRange.getEnd()); |
4748 | InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); |
4749 | ExprResult DelegationInit = InitSeq.Perform(S&: *this, Entity: DelegationEntity, Kind, |
4750 | Args, ResultType: nullptr); |
4751 | if (!DelegationInit.isInvalid()) { |
4752 | assert((DelegationInit.get()->containsErrors() || |
4753 | cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) && |
4754 | "Delegating constructor with no target?" ); |
4755 | |
4756 | // C++11 [class.base.init]p7: |
4757 | // The initialization of each base and member constitutes a |
4758 | // full-expression. |
4759 | DelegationInit = ActOnFinishFullExpr( |
4760 | Expr: DelegationInit.get(), CC: InitRange.getBegin(), /*DiscardedValue*/ false); |
4761 | } |
4762 | |
4763 | if (DelegationInit.isInvalid()) { |
4764 | DelegationInit = |
4765 | CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), SubExprs: Args, |
4766 | T: QualType(ClassDecl->getTypeForDecl(), 0)); |
4767 | if (DelegationInit.isInvalid()) |
4768 | return true; |
4769 | } else { |
4770 | // If we are in a dependent context, template instantiation will |
4771 | // perform this type-checking again. Just save the arguments that we |
4772 | // received in a ParenListExpr. |
4773 | // FIXME: This isn't quite ideal, since our ASTs don't capture all |
4774 | // of the information that we have about the base |
4775 | // initializer. However, deconstructing the ASTs is a dicey process, |
4776 | // and this approach is far more likely to get the corner cases right. |
4777 | if (CurContext->isDependentContext()) |
4778 | DelegationInit = Init; |
4779 | } |
4780 | |
4781 | return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), |
4782 | DelegationInit.getAs<Expr>(), |
4783 | InitRange.getEnd()); |
4784 | } |
4785 | |
4786 | MemInitResult |
4787 | Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, |
4788 | Expr *Init, CXXRecordDecl *ClassDecl, |
4789 | SourceLocation EllipsisLoc) { |
4790 | SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc(); |
4791 | |
4792 | if (!BaseType->isDependentType() && !BaseType->isRecordType()) |
4793 | return Diag(BaseLoc, diag::err_base_init_does_not_name_class) |
4794 | << BaseType << BaseTInfo->getTypeLoc().getSourceRange(); |
4795 | |
4796 | // C++ [class.base.init]p2: |
4797 | // [...] Unless the mem-initializer-id names a nonstatic data |
4798 | // member of the constructor's class or a direct or virtual base |
4799 | // of that class, the mem-initializer is ill-formed. A |
4800 | // mem-initializer-list can initialize a base class using any |
4801 | // name that denotes that base class type. |
4802 | |
4803 | // We can store the initializers in "as-written" form and delay analysis until |
4804 | // instantiation if the constructor is dependent. But not for dependent |
4805 | // (broken) code in a non-template! SetCtorInitializers does not expect this. |
4806 | bool Dependent = CurContext->isDependentContext() && |
4807 | (BaseType->isDependentType() || Init->isTypeDependent()); |
4808 | |
4809 | SourceRange InitRange = Init->getSourceRange(); |
4810 | if (EllipsisLoc.isValid()) { |
4811 | // This is a pack expansion. |
4812 | if (!BaseType->containsUnexpandedParameterPack()) { |
4813 | Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) |
4814 | << SourceRange(BaseLoc, InitRange.getEnd()); |
4815 | |
4816 | EllipsisLoc = SourceLocation(); |
4817 | } |
4818 | } else { |
4819 | // Check for any unexpanded parameter packs. |
4820 | if (DiagnoseUnexpandedParameterPack(Loc: BaseLoc, T: BaseTInfo, UPPC: UPPC_Initializer)) |
4821 | return true; |
4822 | |
4823 | if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer)) |
4824 | return true; |
4825 | } |
4826 | |
4827 | // Check for direct and virtual base classes. |
4828 | const CXXBaseSpecifier *DirectBaseSpec = nullptr; |
4829 | const CXXBaseSpecifier *VirtualBaseSpec = nullptr; |
4830 | if (!Dependent) { |
4831 | if (Context.hasSameUnqualifiedType(T1: QualType(ClassDecl->getTypeForDecl(),0), |
4832 | T2: BaseType)) |
4833 | return BuildDelegatingInitializer(TInfo: BaseTInfo, Init, ClassDecl); |
4834 | |
4835 | FindBaseInitializer(SemaRef&: *this, ClassDecl, BaseType, DirectBaseSpec, |
4836 | VirtualBaseSpec); |
4837 | |
4838 | // C++ [base.class.init]p2: |
4839 | // Unless the mem-initializer-id names a nonstatic data member of the |
4840 | // constructor's class or a direct or virtual base of that class, the |
4841 | // mem-initializer is ill-formed. |
4842 | if (!DirectBaseSpec && !VirtualBaseSpec) { |
4843 | // If the class has any dependent bases, then it's possible that |
4844 | // one of those types will resolve to the same type as |
4845 | // BaseType. Therefore, just treat this as a dependent base |
4846 | // class initialization. FIXME: Should we try to check the |
4847 | // initialization anyway? It seems odd. |
4848 | if (ClassDecl->hasAnyDependentBases()) |
4849 | Dependent = true; |
4850 | else |
4851 | return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) |
4852 | << BaseType << Context.getTypeDeclType(ClassDecl) |
4853 | << BaseTInfo->getTypeLoc().getSourceRange(); |
4854 | } |
4855 | } |
4856 | |
4857 | if (Dependent) { |
4858 | DiscardCleanupsInEvaluationContext(); |
4859 | |
4860 | return new (Context) CXXCtorInitializer(Context, BaseTInfo, |
4861 | /*IsVirtual=*/false, |
4862 | InitRange.getBegin(), Init, |
4863 | InitRange.getEnd(), EllipsisLoc); |
4864 | } |
4865 | |
4866 | // C++ [base.class.init]p2: |
4867 | // If a mem-initializer-id is ambiguous because it designates both |
4868 | // a direct non-virtual base class and an inherited virtual base |
4869 | // class, the mem-initializer is ill-formed. |
4870 | if (DirectBaseSpec && VirtualBaseSpec) |
4871 | return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) |
4872 | << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); |
4873 | |
4874 | const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; |
4875 | if (!BaseSpec) |
4876 | BaseSpec = VirtualBaseSpec; |
4877 | |
4878 | // Initialize the base. |
4879 | bool InitList = true; |
4880 | MultiExprArg Args = Init; |
4881 | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) { |
4882 | InitList = false; |
4883 | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); |
4884 | } |
4885 | |
4886 | InitializedEntity BaseEntity = |
4887 | InitializedEntity::InitializeBase(Context, Base: BaseSpec, IsInheritedVirtualBase: VirtualBaseSpec); |
4888 | InitializationKind Kind = |
4889 | InitList ? InitializationKind::CreateDirectList(InitLoc: BaseLoc) |
4890 | : InitializationKind::CreateDirect(InitLoc: BaseLoc, LParenLoc: InitRange.getBegin(), |
4891 | RParenLoc: InitRange.getEnd()); |
4892 | InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); |
4893 | ExprResult BaseInit = InitSeq.Perform(S&: *this, Entity: BaseEntity, Kind, Args, ResultType: nullptr); |
4894 | if (!BaseInit.isInvalid()) { |
4895 | // C++11 [class.base.init]p7: |
4896 | // The initialization of each base and member constitutes a |
4897 | // full-expression. |
4898 | BaseInit = ActOnFinishFullExpr(Expr: BaseInit.get(), CC: InitRange.getBegin(), |
4899 | /*DiscardedValue*/ false); |
4900 | } |
4901 | |
4902 | if (BaseInit.isInvalid()) { |
4903 | BaseInit = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), |
4904 | SubExprs: Args, T: BaseType); |
4905 | if (BaseInit.isInvalid()) |
4906 | return true; |
4907 | } else { |
4908 | // If we are in a dependent context, template instantiation will |
4909 | // perform this type-checking again. Just save the arguments that we |
4910 | // received in a ParenListExpr. |
4911 | // FIXME: This isn't quite ideal, since our ASTs don't capture all |
4912 | // of the information that we have about the base |
4913 | // initializer. However, deconstructing the ASTs is a dicey process, |
4914 | // and this approach is far more likely to get the corner cases right. |
4915 | if (CurContext->isDependentContext()) |
4916 | BaseInit = Init; |
4917 | } |
4918 | |
4919 | return new (Context) CXXCtorInitializer(Context, BaseTInfo, |
4920 | BaseSpec->isVirtual(), |
4921 | InitRange.getBegin(), |
4922 | BaseInit.getAs<Expr>(), |
4923 | InitRange.getEnd(), EllipsisLoc); |
4924 | } |
4925 | |
4926 | // Create a static_cast\<T&&>(expr). |
4927 | static Expr *CastForMoving(Sema &SemaRef, Expr *E) { |
4928 | QualType TargetType = |
4929 | SemaRef.BuildReferenceType(T: E->getType(), /*SpelledAsLValue*/ LValueRef: false, |
4930 | Loc: SourceLocation(), Entity: DeclarationName()); |
4931 | SourceLocation ExprLoc = E->getBeginLoc(); |
4932 | TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( |
4933 | T: TargetType, Loc: ExprLoc); |
4934 | |
4935 | return SemaRef.BuildCXXNamedCast(OpLoc: ExprLoc, Kind: tok::kw_static_cast, Ty: TargetLoc, E, |
4936 | AngleBrackets: SourceRange(ExprLoc, ExprLoc), |
4937 | Parens: E->getSourceRange()).get(); |
4938 | } |
4939 | |
4940 | /// ImplicitInitializerKind - How an implicit base or member initializer should |
4941 | /// initialize its base or member. |
4942 | enum ImplicitInitializerKind { |
4943 | IIK_Default, |
4944 | IIK_Copy, |
4945 | IIK_Move, |
4946 | IIK_Inherit |
4947 | }; |
4948 | |
4949 | static bool |
4950 | BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, |
4951 | ImplicitInitializerKind ImplicitInitKind, |
4952 | CXXBaseSpecifier *BaseSpec, |
4953 | bool IsInheritedVirtualBase, |
4954 | CXXCtorInitializer *&CXXBaseInit) { |
4955 | InitializedEntity InitEntity |
4956 | = InitializedEntity::InitializeBase(Context&: SemaRef.Context, Base: BaseSpec, |
4957 | IsInheritedVirtualBase); |
4958 | |
4959 | ExprResult BaseInit; |
4960 | |
4961 | switch (ImplicitInitKind) { |
4962 | case IIK_Inherit: |
4963 | case IIK_Default: { |
4964 | InitializationKind InitKind |
4965 | = InitializationKind::CreateDefault(InitLoc: Constructor->getLocation()); |
4966 | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt); |
4967 | BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: std::nullopt); |
4968 | break; |
4969 | } |
4970 | |
4971 | case IIK_Move: |
4972 | case IIK_Copy: { |
4973 | bool Moving = ImplicitInitKind == IIK_Move; |
4974 | ParmVarDecl *Param = Constructor->getParamDecl(0); |
4975 | QualType ParamType = Param->getType().getNonReferenceType(); |
4976 | |
4977 | Expr *CopyCtorArg = |
4978 | DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), |
4979 | SourceLocation(), Param, false, |
4980 | Constructor->getLocation(), ParamType, |
4981 | VK_LValue, nullptr); |
4982 | |
4983 | SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: CopyCtorArg)); |
4984 | |
4985 | // Cast to the base class to avoid ambiguities. |
4986 | QualType ArgTy = |
4987 | SemaRef.Context.getQualifiedType(T: BaseSpec->getType().getUnqualifiedType(), |
4988 | Qs: ParamType.getQualifiers()); |
4989 | |
4990 | if (Moving) { |
4991 | CopyCtorArg = CastForMoving(SemaRef, E: CopyCtorArg); |
4992 | } |
4993 | |
4994 | CXXCastPath BasePath; |
4995 | BasePath.push_back(Elt: BaseSpec); |
4996 | CopyCtorArg = SemaRef.ImpCastExprToType(E: CopyCtorArg, Type: ArgTy, |
4997 | CK: CK_UncheckedDerivedToBase, |
4998 | VK: Moving ? VK_XValue : VK_LValue, |
4999 | BasePath: &BasePath).get(); |
5000 | |
5001 | InitializationKind InitKind |
5002 | = InitializationKind::CreateDirect(InitLoc: Constructor->getLocation(), |
5003 | LParenLoc: SourceLocation(), RParenLoc: SourceLocation()); |
5004 | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); |
5005 | BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: CopyCtorArg); |
5006 | break; |
5007 | } |
5008 | } |
5009 | |
5010 | BaseInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: BaseInit); |
5011 | if (BaseInit.isInvalid()) |
5012 | return true; |
5013 | |
5014 | CXXBaseInit = |
5015 | new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, |
5016 | SemaRef.Context.getTrivialTypeSourceInfo(T: BaseSpec->getType(), |
5017 | Loc: SourceLocation()), |
5018 | BaseSpec->isVirtual(), |
5019 | SourceLocation(), |
5020 | BaseInit.getAs<Expr>(), |
5021 | SourceLocation(), |
5022 | SourceLocation()); |
5023 | |
5024 | return false; |
5025 | } |
5026 | |
5027 | static bool RefersToRValueRef(Expr *MemRef) { |
5028 | ValueDecl *Referenced = cast<MemberExpr>(Val: MemRef)->getMemberDecl(); |
5029 | return Referenced->getType()->isRValueReferenceType(); |
5030 | } |
5031 | |
5032 | static bool |
5033 | BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, |
5034 | ImplicitInitializerKind ImplicitInitKind, |
5035 | FieldDecl *Field, IndirectFieldDecl *Indirect, |
5036 | CXXCtorInitializer *&CXXMemberInit) { |
5037 | if (Field->isInvalidDecl()) |
5038 | return true; |
5039 | |
5040 | SourceLocation Loc = Constructor->getLocation(); |
5041 | |
5042 | if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { |
5043 | bool Moving = ImplicitInitKind == IIK_Move; |
5044 | ParmVarDecl *Param = Constructor->getParamDecl(0); |
5045 | QualType ParamType = Param->getType().getNonReferenceType(); |
5046 | |
5047 | // Suppress copying zero-width bitfields. |
5048 | if (Field->isZeroLengthBitField(Ctx: SemaRef.Context)) |
5049 | return false; |
5050 | |
5051 | Expr *MemberExprBase = |
5052 | DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), |
5053 | SourceLocation(), Param, false, |
5054 | Loc, ParamType, VK_LValue, nullptr); |
5055 | |
5056 | SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: MemberExprBase)); |
5057 | |
5058 | if (Moving) { |
5059 | MemberExprBase = CastForMoving(SemaRef, E: MemberExprBase); |
5060 | } |
5061 | |
5062 | // Build a reference to this field within the parameter. |
5063 | CXXScopeSpec SS; |
5064 | LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, |
5065 | Sema::LookupMemberName); |
5066 | MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Val: Indirect) |
5067 | : cast<ValueDecl>(Val: Field), AS_public); |
5068 | MemberLookup.resolveKind(); |
5069 | ExprResult CtorArg |
5070 | = SemaRef.BuildMemberReferenceExpr(Base: MemberExprBase, |
5071 | BaseType: ParamType, OpLoc: Loc, |
5072 | /*IsArrow=*/false, |
5073 | SS, |
5074 | /*TemplateKWLoc=*/SourceLocation(), |
5075 | /*FirstQualifierInScope=*/nullptr, |
5076 | R&: MemberLookup, |
5077 | /*TemplateArgs=*/nullptr, |
5078 | /*S*/nullptr); |
5079 | if (CtorArg.isInvalid()) |
5080 | return true; |
5081 | |
5082 | // C++11 [class.copy]p15: |
5083 | // - if a member m has rvalue reference type T&&, it is direct-initialized |
5084 | // with static_cast<T&&>(x.m); |
5085 | if (RefersToRValueRef(MemRef: CtorArg.get())) { |
5086 | CtorArg = CastForMoving(SemaRef, E: CtorArg.get()); |
5087 | } |
5088 | |
5089 | InitializedEntity Entity = |
5090 | Indirect ? InitializedEntity::InitializeMember(Member: Indirect, Parent: nullptr, |
5091 | /*Implicit*/ true) |
5092 | : InitializedEntity::InitializeMember(Member: Field, Parent: nullptr, |
5093 | /*Implicit*/ true); |
5094 | |
5095 | // Direct-initialize to use the copy constructor. |
5096 | InitializationKind InitKind = |
5097 | InitializationKind::CreateDirect(InitLoc: Loc, LParenLoc: SourceLocation(), RParenLoc: SourceLocation()); |
5098 | |
5099 | Expr *CtorArgE = CtorArg.getAs<Expr>(); |
5100 | InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); |
5101 | ExprResult MemberInit = |
5102 | InitSeq.Perform(S&: SemaRef, Entity, Kind: InitKind, Args: MultiExprArg(&CtorArgE, 1)); |
5103 | MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit); |
5104 | if (MemberInit.isInvalid()) |
5105 | return true; |
5106 | |
5107 | if (Indirect) |
5108 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( |
5109 | SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); |
5110 | else |
5111 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( |
5112 | SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); |
5113 | return false; |
5114 | } |
5115 | |
5116 | assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && |
5117 | "Unhandled implicit init kind!" ); |
5118 | |
5119 | QualType FieldBaseElementType = |
5120 | SemaRef.Context.getBaseElementType(Field->getType()); |
5121 | |
5122 | if (FieldBaseElementType->isRecordType()) { |
5123 | InitializedEntity InitEntity = |
5124 | Indirect ? InitializedEntity::InitializeMember(Member: Indirect, Parent: nullptr, |
5125 | /*Implicit*/ true) |
5126 | : InitializedEntity::InitializeMember(Member: Field, Parent: nullptr, |
5127 | /*Implicit*/ true); |
5128 | InitializationKind InitKind = |
5129 | InitializationKind::CreateDefault(InitLoc: Loc); |
5130 | |
5131 | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt); |
5132 | ExprResult MemberInit = |
5133 | InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: std::nullopt); |
5134 | |
5135 | MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit); |
5136 | if (MemberInit.isInvalid()) |
5137 | return true; |
5138 | |
5139 | if (Indirect) |
5140 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, |
5141 | Indirect, Loc, |
5142 | Loc, |
5143 | MemberInit.get(), |
5144 | Loc); |
5145 | else |
5146 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, |
5147 | Field, Loc, Loc, |
5148 | MemberInit.get(), |
5149 | Loc); |
5150 | return false; |
5151 | } |
5152 | |
5153 | if (!Field->getParent()->isUnion()) { |
5154 | if (FieldBaseElementType->isReferenceType()) { |
5155 | SemaRef.Diag(Constructor->getLocation(), |
5156 | diag::err_uninitialized_member_in_ctor) |
5157 | << (int)Constructor->isImplicit() |
5158 | << SemaRef.Context.getTagDeclType(Constructor->getParent()) |
5159 | << 0 << Field->getDeclName(); |
5160 | SemaRef.Diag(Field->getLocation(), diag::note_declared_at); |
5161 | return true; |
5162 | } |
5163 | |
5164 | if (FieldBaseElementType.isConstQualified()) { |
5165 | SemaRef.Diag(Constructor->getLocation(), |
5166 | diag::err_uninitialized_member_in_ctor) |
5167 | << (int)Constructor->isImplicit() |
5168 | << SemaRef.Context.getTagDeclType(Constructor->getParent()) |
5169 | << 1 << Field->getDeclName(); |
5170 | SemaRef.Diag(Field->getLocation(), diag::note_declared_at); |
5171 | return true; |
5172 | } |
5173 | } |
5174 | |
5175 | if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { |
5176 | // ARC and Weak: |
5177 | // Default-initialize Objective-C pointers to NULL. |
5178 | CXXMemberInit |
5179 | = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, |
5180 | Loc, Loc, |
5181 | new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), |
5182 | Loc); |
5183 | return false; |
5184 | } |
5185 | |
5186 | // Nothing to initialize. |
5187 | CXXMemberInit = nullptr; |
5188 | return false; |
5189 | } |
5190 | |
5191 | namespace { |
5192 | struct BaseAndFieldInfo { |
5193 | Sema &S; |
5194 | CXXConstructorDecl *Ctor; |
5195 | bool AnyErrorsInInits; |
5196 | ImplicitInitializerKind IIK; |
5197 | llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; |
5198 | SmallVector<CXXCtorInitializer*, 8> AllToInit; |
5199 | llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; |
5200 | |
5201 | BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) |
5202 | : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { |
5203 | bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); |
5204 | if (Ctor->getInheritedConstructor()) |
5205 | IIK = IIK_Inherit; |
5206 | else if (Generated && Ctor->isCopyConstructor()) |
5207 | IIK = IIK_Copy; |
5208 | else if (Generated && Ctor->isMoveConstructor()) |
5209 | IIK = IIK_Move; |
5210 | else |
5211 | IIK = IIK_Default; |
5212 | } |
5213 | |
5214 | bool isImplicitCopyOrMove() const { |
5215 | switch (IIK) { |
5216 | case IIK_Copy: |
5217 | case IIK_Move: |
5218 | return true; |
5219 | |
5220 | case IIK_Default: |
5221 | case IIK_Inherit: |
5222 | return false; |
5223 | } |
5224 | |
5225 | llvm_unreachable("Invalid ImplicitInitializerKind!" ); |
5226 | } |
5227 | |
5228 | bool addFieldInitializer(CXXCtorInitializer *Init) { |
5229 | AllToInit.push_back(Elt: Init); |
5230 | |
5231 | // Check whether this initializer makes the field "used". |
5232 | if (Init->getInit()->HasSideEffects(Ctx: S.Context)) |
5233 | S.UnusedPrivateFields.remove(Init->getAnyMember()); |
5234 | |
5235 | return false; |
5236 | } |
5237 | |
5238 | bool isInactiveUnionMember(FieldDecl *Field) { |
5239 | RecordDecl *Record = Field->getParent(); |
5240 | if (!Record->isUnion()) |
5241 | return false; |
5242 | |
5243 | if (FieldDecl *Active = |
5244 | ActiveUnionMember.lookup(Val: Record->getCanonicalDecl())) |
5245 | return Active != Field->getCanonicalDecl(); |
5246 | |
5247 | // In an implicit copy or move constructor, ignore any in-class initializer. |
5248 | if (isImplicitCopyOrMove()) |
5249 | return true; |
5250 | |
5251 | // If there's no explicit initialization, the field is active only if it |
5252 | // has an in-class initializer... |
5253 | if (Field->hasInClassInitializer()) |
5254 | return false; |
5255 | // ... or it's an anonymous struct or union whose class has an in-class |
5256 | // initializer. |
5257 | if (!Field->isAnonymousStructOrUnion()) |
5258 | return true; |
5259 | CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); |
5260 | return !FieldRD->hasInClassInitializer(); |
5261 | } |
5262 | |
5263 | /// Determine whether the given field is, or is within, a union member |
5264 | /// that is inactive (because there was an initializer given for a different |
5265 | /// member of the union, or because the union was not initialized at all). |
5266 | bool isWithinInactiveUnionMember(FieldDecl *Field, |
5267 | IndirectFieldDecl *Indirect) { |
5268 | if (!Indirect) |
5269 | return isInactiveUnionMember(Field); |
5270 | |
5271 | for (auto *C : Indirect->chain()) { |
5272 | FieldDecl *Field = dyn_cast<FieldDecl>(Val: C); |
5273 | if (Field && isInactiveUnionMember(Field)) |
5274 | return true; |
5275 | } |
5276 | return false; |
5277 | } |
5278 | }; |
5279 | } |
5280 | |
5281 | /// Determine whether the given type is an incomplete or zero-lenfgth |
5282 | /// array type. |
5283 | static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { |
5284 | if (T->isIncompleteArrayType()) |
5285 | return true; |
5286 | |
5287 | while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { |
5288 | if (ArrayT->isZeroSize()) |
5289 | return true; |
5290 | |
5291 | T = ArrayT->getElementType(); |
5292 | } |
5293 | |
5294 | return false; |
5295 | } |
5296 | |
5297 | static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, |
5298 | FieldDecl *Field, |
5299 | IndirectFieldDecl *Indirect = nullptr) { |
5300 | if (Field->isInvalidDecl()) |
5301 | return false; |
5302 | |
5303 | // Overwhelmingly common case: we have a direct initializer for this field. |
5304 | if (CXXCtorInitializer *Init = |
5305 | Info.AllBaseFields.lookup(Val: Field->getCanonicalDecl())) |
5306 | return Info.addFieldInitializer(Init); |
5307 | |
5308 | // C++11 [class.base.init]p8: |
5309 | // if the entity is a non-static data member that has a |
5310 | // brace-or-equal-initializer and either |
5311 | // -- the constructor's class is a union and no other variant member of that |
5312 | // union is designated by a mem-initializer-id or |
5313 | // -- the constructor's class is not a union, and, if the entity is a member |
5314 | // of an anonymous union, no other member of that union is designated by |
5315 | // a mem-initializer-id, |
5316 | // the entity is initialized as specified in [dcl.init]. |
5317 | // |
5318 | // We also apply the same rules to handle anonymous structs within anonymous |
5319 | // unions. |
5320 | if (Info.isWithinInactiveUnionMember(Field, Indirect)) |
5321 | return false; |
5322 | |
5323 | if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { |
5324 | ExprResult DIE = |
5325 | SemaRef.BuildCXXDefaultInitExpr(Loc: Info.Ctor->getLocation(), Field); |
5326 | if (DIE.isInvalid()) |
5327 | return true; |
5328 | |
5329 | auto Entity = InitializedEntity::InitializeMember(Member: Field, Parent: nullptr, Implicit: true); |
5330 | SemaRef.checkInitializerLifetime(Entity, Init: DIE.get()); |
5331 | |
5332 | CXXCtorInitializer *Init; |
5333 | if (Indirect) |
5334 | Init = new (SemaRef.Context) |
5335 | CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), |
5336 | SourceLocation(), DIE.get(), SourceLocation()); |
5337 | else |
5338 | Init = new (SemaRef.Context) |
5339 | CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), |
5340 | SourceLocation(), DIE.get(), SourceLocation()); |
5341 | return Info.addFieldInitializer(Init); |
5342 | } |
5343 | |
5344 | // Don't initialize incomplete or zero-length arrays. |
5345 | if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) |
5346 | return false; |
5347 | |
5348 | // Don't try to build an implicit initializer if there were semantic |
5349 | // errors in any of the initializers (and therefore we might be |
5350 | // missing some that the user actually wrote). |
5351 | if (Info.AnyErrorsInInits) |
5352 | return false; |
5353 | |
5354 | CXXCtorInitializer *Init = nullptr; |
5355 | if (BuildImplicitMemberInitializer(SemaRef&: Info.S, Constructor: Info.Ctor, ImplicitInitKind: Info.IIK, Field, |
5356 | Indirect, CXXMemberInit&: Init)) |
5357 | return true; |
5358 | |
5359 | if (!Init) |
5360 | return false; |
5361 | |
5362 | return Info.addFieldInitializer(Init); |
5363 | } |
5364 | |
5365 | bool |
5366 | Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, |
5367 | CXXCtorInitializer *Initializer) { |
5368 | assert(Initializer->isDelegatingInitializer()); |
5369 | Constructor->setNumCtorInitializers(1); |
5370 | CXXCtorInitializer **initializer = |
5371 | new (Context) CXXCtorInitializer*[1]; |
5372 | memcpy(dest: initializer, src: &Initializer, n: sizeof (CXXCtorInitializer*)); |
5373 | Constructor->setCtorInitializers(initializer); |
5374 | |
5375 | if (CXXDestructorDecl *Dtor = LookupDestructor(Class: Constructor->getParent())) { |
5376 | MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); |
5377 | DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); |
5378 | } |
5379 | |
5380 | DelegatingCtorDecls.push_back(LocalValue: Constructor); |
5381 | |
5382 | DiagnoseUninitializedFields(SemaRef&: *this, Constructor); |
5383 | |
5384 | return false; |
5385 | } |
5386 | |
5387 | bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, |
5388 | ArrayRef<CXXCtorInitializer *> Initializers) { |
5389 | if (Constructor->isDependentContext()) { |
5390 | // Just store the initializers as written, they will be checked during |
5391 | // instantiation. |
5392 | if (!Initializers.empty()) { |
5393 | Constructor->setNumCtorInitializers(Initializers.size()); |
5394 | CXXCtorInitializer **baseOrMemberInitializers = |
5395 | new (Context) CXXCtorInitializer*[Initializers.size()]; |
5396 | memcpy(dest: baseOrMemberInitializers, src: Initializers.data(), |
5397 | n: Initializers.size() * sizeof(CXXCtorInitializer*)); |
5398 | Constructor->setCtorInitializers(baseOrMemberInitializers); |
5399 | } |
5400 | |
5401 | // Let template instantiation know whether we had errors. |
5402 | if (AnyErrors) |
5403 | Constructor->setInvalidDecl(); |
5404 | |
5405 | return false; |
5406 | } |
5407 | |
5408 | BaseAndFieldInfo Info(*this, Constructor, AnyErrors); |
5409 | |
5410 | // We need to build the initializer AST according to order of construction |
5411 | // and not what user specified in the Initializers list. |
5412 | CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); |
5413 | if (!ClassDecl) |
5414 | return true; |
5415 | |
5416 | bool HadError = false; |
5417 | |
5418 | for (unsigned i = 0; i < Initializers.size(); i++) { |
5419 | CXXCtorInitializer *Member = Initializers[i]; |
5420 | |
5421 | if (Member->isBaseInitializer()) |
5422 | Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; |
5423 | else { |
5424 | Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; |
5425 | |
5426 | if (IndirectFieldDecl *F = Member->getIndirectMember()) { |
5427 | for (auto *C : F->chain()) { |
5428 | FieldDecl *FD = dyn_cast<FieldDecl>(Val: C); |
5429 | if (FD && FD->getParent()->isUnion()) |
5430 | Info.ActiveUnionMember.insert(std::make_pair( |
5431 | FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); |
5432 | } |
5433 | } else if (FieldDecl *FD = Member->getMember()) { |
5434 | if (FD->getParent()->isUnion()) |
5435 | Info.ActiveUnionMember.insert(std::make_pair( |
5436 | FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); |
5437 | } |
5438 | } |
5439 | } |
5440 | |
5441 | // Keep track of the direct virtual bases. |
5442 | llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; |
5443 | for (auto &I : ClassDecl->bases()) { |
5444 | if (I.isVirtual()) |
5445 | DirectVBases.insert(&I); |
5446 | } |
5447 | |
5448 | // Push virtual bases before others. |
5449 | for (auto &VBase : ClassDecl->vbases()) { |
5450 | if (CXXCtorInitializer *Value |
5451 | = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { |
5452 | // [class.base.init]p7, per DR257: |
5453 | // A mem-initializer where the mem-initializer-id names a virtual base |
5454 | // class is ignored during execution of a constructor of any class that |
5455 | // is not the most derived class. |
5456 | if (ClassDecl->isAbstract()) { |
5457 | // FIXME: Provide a fixit to remove the base specifier. This requires |
5458 | // tracking the location of the associated comma for a base specifier. |
5459 | Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) |
5460 | << VBase.getType() << ClassDecl; |
5461 | DiagnoseAbstractType(ClassDecl); |
5462 | } |
5463 | |
5464 | Info.AllToInit.push_back(Value); |
5465 | } else if (!AnyErrors && !ClassDecl->isAbstract()) { |
5466 | // [class.base.init]p8, per DR257: |
5467 | // If a given [...] base class is not named by a mem-initializer-id |
5468 | // [...] and the entity is not a virtual base class of an abstract |
5469 | // class, then [...] the entity is default-initialized. |
5470 | bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); |
5471 | CXXCtorInitializer *CXXBaseInit; |
5472 | if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, |
5473 | &VBase, IsInheritedVirtualBase, |
5474 | CXXBaseInit)) { |
5475 | HadError = true; |
5476 | continue; |
5477 | } |
5478 | |
5479 | Info.AllToInit.push_back(CXXBaseInit); |
5480 | } |
5481 | } |
5482 | |
5483 | // Non-virtual bases. |
5484 | for (auto &Base : ClassDecl->bases()) { |
5485 | // Virtuals are in the virtual base list and already constructed. |
5486 | if (Base.isVirtual()) |
5487 | continue; |
5488 | |
5489 | if (CXXCtorInitializer *Value |
5490 | = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { |
5491 | Info.AllToInit.push_back(Value); |
5492 | } else if (!AnyErrors) { |
5493 | CXXCtorInitializer *CXXBaseInit; |
5494 | if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, |
5495 | &Base, /*IsInheritedVirtualBase=*/false, |
5496 | CXXBaseInit)) { |
5497 | HadError = true; |
5498 | continue; |
5499 | } |
5500 | |
5501 | Info.AllToInit.push_back(CXXBaseInit); |
5502 | } |
5503 | } |
5504 | |
5505 | // Fields. |
5506 | for (auto *Mem : ClassDecl->decls()) { |
5507 | if (auto *F = dyn_cast<FieldDecl>(Mem)) { |
5508 | // C++ [class.bit]p2: |
5509 | // A declaration for a bit-field that omits the identifier declares an |
5510 | // unnamed bit-field. Unnamed bit-fields are not members and cannot be |
5511 | // initialized. |
5512 | if (F->isUnnamedBitField()) |
5513 | continue; |
5514 | |
5515 | // If we're not generating the implicit copy/move constructor, then we'll |
5516 | // handle anonymous struct/union fields based on their individual |
5517 | // indirect fields. |
5518 | if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) |
5519 | continue; |
5520 | |
5521 | if (CollectFieldInitializer(*this, Info, F)) |
5522 | HadError = true; |
5523 | continue; |
5524 | } |
5525 | |
5526 | // Beyond this point, we only consider default initialization. |
5527 | if (Info.isImplicitCopyOrMove()) |
5528 | continue; |
5529 | |
5530 | if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { |
5531 | if (F->getType()->isIncompleteArrayType()) { |
5532 | assert(ClassDecl->hasFlexibleArrayMember() && |
5533 | "Incomplete array type is not valid" ); |
5534 | continue; |
5535 | } |
5536 | |
5537 | // Initialize each field of an anonymous struct individually. |
5538 | if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) |
5539 | HadError = true; |
5540 | |
5541 | continue; |
5542 | } |
5543 | } |
5544 | |
5545 | unsigned NumInitializers = Info.AllToInit.size(); |
5546 | if (NumInitializers > 0) { |
5547 | Constructor->setNumCtorInitializers(NumInitializers); |
5548 | CXXCtorInitializer **baseOrMemberInitializers = |
5549 | new (Context) CXXCtorInitializer*[NumInitializers]; |
5550 | memcpy(dest: baseOrMemberInitializers, src: Info.AllToInit.data(), |
5551 | n: NumInitializers * sizeof(CXXCtorInitializer*)); |
5552 | Constructor->setCtorInitializers(baseOrMemberInitializers); |
5553 | |
5554 | // Constructors implicitly reference the base and member |
5555 | // destructors. |
5556 | MarkBaseAndMemberDestructorsReferenced(Loc: Constructor->getLocation(), |
5557 | Record: Constructor->getParent()); |
5558 | } |
5559 | |
5560 | return HadError; |
5561 | } |
5562 | |
5563 | static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { |
5564 | if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { |
5565 | const RecordDecl *RD = RT->getDecl(); |
5566 | if (RD->isAnonymousStructOrUnion()) { |
5567 | for (auto *Field : RD->fields()) |
5568 | PopulateKeysForFields(Field, IdealInits); |
5569 | return; |
5570 | } |
5571 | } |
5572 | IdealInits.push_back(Elt: Field->getCanonicalDecl()); |
5573 | } |
5574 | |
5575 | static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { |
5576 | return Context.getCanonicalType(T: BaseType).getTypePtr(); |
5577 | } |
5578 | |
5579 | static const void *GetKeyForMember(ASTContext &Context, |
5580 | CXXCtorInitializer *Member) { |
5581 | if (!Member->isAnyMemberInitializer()) |
5582 | return GetKeyForBase(Context, BaseType: QualType(Member->getBaseClass(), 0)); |
5583 | |
5584 | return Member->getAnyMember()->getCanonicalDecl(); |
5585 | } |
5586 | |
5587 | static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, |
5588 | const CXXCtorInitializer *Previous, |
5589 | const CXXCtorInitializer *Current) { |
5590 | if (Previous->isAnyMemberInitializer()) |
5591 | Diag << 0 << Previous->getAnyMember(); |
5592 | else |
5593 | Diag << 1 << Previous->getTypeSourceInfo()->getType(); |
5594 | |
5595 | if (Current->isAnyMemberInitializer()) |
5596 | Diag << 0 << Current->getAnyMember(); |
5597 | else |
5598 | Diag << 1 << Current->getTypeSourceInfo()->getType(); |
5599 | } |
5600 | |
5601 | static void DiagnoseBaseOrMemInitializerOrder( |
5602 | Sema &SemaRef, const CXXConstructorDecl *Constructor, |
5603 | ArrayRef<CXXCtorInitializer *> Inits) { |
5604 | if (Constructor->getDeclContext()->isDependentContext()) |
5605 | return; |
5606 | |
5607 | // Don't check initializers order unless the warning is enabled at the |
5608 | // location of at least one initializer. |
5609 | bool ShouldCheckOrder = false; |
5610 | for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { |
5611 | CXXCtorInitializer *Init = Inits[InitIndex]; |
5612 | if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, |
5613 | Init->getSourceLocation())) { |
5614 | ShouldCheckOrder = true; |
5615 | break; |
5616 | } |
5617 | } |
5618 | if (!ShouldCheckOrder) |
5619 | return; |
5620 | |
5621 | // Build the list of bases and members in the order that they'll |
5622 | // actually be initialized. The explicit initializers should be in |
5623 | // this same order but may be missing things. |
5624 | SmallVector<const void*, 32> IdealInitKeys; |
5625 | |
5626 | const CXXRecordDecl *ClassDecl = Constructor->getParent(); |
5627 | |
5628 | // 1. Virtual bases. |
5629 | for (const auto &VBase : ClassDecl->vbases()) |
5630 | IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); |
5631 | |
5632 | // 2. Non-virtual bases. |
5633 | for (const auto &Base : ClassDecl->bases()) { |
5634 | if (Base.isVirtual()) |
5635 | continue; |
5636 | IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); |
5637 | } |
5638 | |
5639 | // 3. Direct fields. |
5640 | for (auto *Field : ClassDecl->fields()) { |
5641 | if (Field->isUnnamedBitField()) |
5642 | continue; |
5643 | |
5644 | PopulateKeysForFields(Field, IdealInitKeys); |
5645 | } |
5646 | |
5647 | unsigned NumIdealInits = IdealInitKeys.size(); |
5648 | unsigned IdealIndex = 0; |
5649 | |
5650 | // Track initializers that are in an incorrect order for either a warning or |
5651 | // note if multiple ones occur. |
5652 | SmallVector<unsigned> WarnIndexes; |
5653 | // Correlates the index of an initializer in the init-list to the index of |
5654 | // the field/base in the class. |
5655 | SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder; |
5656 | |
5657 | for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { |
5658 | const void *InitKey = GetKeyForMember(Context&: SemaRef.Context, Member: Inits[InitIndex]); |
5659 | |
5660 | // Scan forward to try to find this initializer in the idealized |
5661 | // initializers list. |
5662 | for (; IdealIndex != NumIdealInits; ++IdealIndex) |
5663 | if (InitKey == IdealInitKeys[IdealIndex]) |
5664 | break; |
5665 | |
5666 | // If we didn't find this initializer, it must be because we |
5667 | // scanned past it on a previous iteration. That can only |
5668 | // happen if we're out of order; emit a warning. |
5669 | if (IdealIndex == NumIdealInits && InitIndex) { |
5670 | WarnIndexes.push_back(Elt: InitIndex); |
5671 | |
5672 | // Move back to the initializer's location in the ideal list. |
5673 | for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) |
5674 | if (InitKey == IdealInitKeys[IdealIndex]) |
5675 | break; |
5676 | |
5677 | assert(IdealIndex < NumIdealInits && |
5678 | "initializer not found in initializer list" ); |
5679 | } |
5680 | CorrelatedInitOrder.emplace_back(Args&: IdealIndex, Args&: InitIndex); |
5681 | } |
5682 | |
5683 | if (WarnIndexes.empty()) |
5684 | return; |
5685 | |
5686 | // Sort based on the ideal order, first in the pair. |
5687 | llvm::sort(C&: CorrelatedInitOrder, Comp: llvm::less_first()); |
5688 | |
5689 | // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to |
5690 | // emit the diagnostic before we can try adding notes. |
5691 | { |
5692 | Sema::SemaDiagnosticBuilder D = SemaRef.Diag( |
5693 | Inits[WarnIndexes.front() - 1]->getSourceLocation(), |
5694 | WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order |
5695 | : diag::warn_some_initializers_out_of_order); |
5696 | |
5697 | for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) { |
5698 | if (CorrelatedInitOrder[I].second == I) |
5699 | continue; |
5700 | // Ideally we would be using InsertFromRange here, but clang doesn't |
5701 | // appear to handle InsertFromRange correctly when the source range is |
5702 | // modified by another fix-it. |
5703 | D << FixItHint::CreateReplacement( |
5704 | RemoveRange: Inits[I]->getSourceRange(), |
5705 | Code: Lexer::getSourceText( |
5706 | Range: CharSourceRange::getTokenRange( |
5707 | R: Inits[CorrelatedInitOrder[I].second]->getSourceRange()), |
5708 | SM: SemaRef.getSourceManager(), LangOpts: SemaRef.getLangOpts())); |
5709 | } |
5710 | |
5711 | // If there is only 1 item out of order, the warning expects the name and |
5712 | // type of each being added to it. |
5713 | if (WarnIndexes.size() == 1) { |
5714 | AddInitializerToDiag(Diag: D, Previous: Inits[WarnIndexes.front() - 1], |
5715 | Current: Inits[WarnIndexes.front()]); |
5716 | return; |
5717 | } |
5718 | } |
5719 | // More than 1 item to warn, create notes letting the user know which ones |
5720 | // are bad. |
5721 | for (unsigned WarnIndex : WarnIndexes) { |
5722 | const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1]; |
5723 | auto D = SemaRef.Diag(PrevInit->getSourceLocation(), |
5724 | diag::note_initializer_out_of_order); |
5725 | AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]); |
5726 | D << PrevInit->getSourceRange(); |
5727 | } |
5728 | } |
5729 | |
5730 | namespace { |
5731 | bool CheckRedundantInit(Sema &S, |
5732 | CXXCtorInitializer *Init, |
5733 | CXXCtorInitializer *&PrevInit) { |
5734 | if (!PrevInit) { |
5735 | PrevInit = Init; |
5736 | return false; |
5737 | } |
5738 | |
5739 | if (FieldDecl *Field = Init->getAnyMember()) |
5740 | S.Diag(Init->getSourceLocation(), |
5741 | diag::err_multiple_mem_initialization) |
5742 | << Field->getDeclName() |
5743 | << Init->getSourceRange(); |
5744 | else { |
5745 | const Type *BaseClass = Init->getBaseClass(); |
5746 | assert(BaseClass && "neither field nor base" ); |
5747 | S.Diag(Init->getSourceLocation(), |
5748 | diag::err_multiple_base_initialization) |
5749 | << QualType(BaseClass, 0) |
5750 | << Init->getSourceRange(); |
5751 | } |
5752 | S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) |
5753 | << 0 << PrevInit->getSourceRange(); |
5754 | |
5755 | return true; |
5756 | } |
5757 | |
5758 | typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; |
5759 | typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; |
5760 | |
5761 | bool CheckRedundantUnionInit(Sema &S, |
5762 | CXXCtorInitializer *Init, |
5763 | RedundantUnionMap &Unions) { |
5764 | FieldDecl *Field = Init->getAnyMember(); |
5765 | RecordDecl *Parent = Field->getParent(); |
5766 | NamedDecl *Child = Field; |
5767 | |
5768 | while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { |
5769 | if (Parent->isUnion()) { |
5770 | UnionEntry &En = Unions[Parent]; |
5771 | if (En.first && En.first != Child) { |
5772 | S.Diag(Init->getSourceLocation(), |
5773 | diag::err_multiple_mem_union_initialization) |
5774 | << Field->getDeclName() |
5775 | << Init->getSourceRange(); |
5776 | S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) |
5777 | << 0 << En.second->getSourceRange(); |
5778 | return true; |
5779 | } |
5780 | if (!En.first) { |
5781 | En.first = Child; |
5782 | En.second = Init; |
5783 | } |
5784 | if (!Parent->isAnonymousStructOrUnion()) |
5785 | return false; |
5786 | } |
5787 | |
5788 | Child = Parent; |
5789 | Parent = cast<RecordDecl>(Parent->getDeclContext()); |
5790 | } |
5791 | |
5792 | return false; |
5793 | } |
5794 | } // namespace |
5795 | |
5796 | /// ActOnMemInitializers - Handle the member initializers for a constructor. |
5797 | void Sema::ActOnMemInitializers(Decl *ConstructorDecl, |
5798 | SourceLocation ColonLoc, |
5799 | ArrayRef<CXXCtorInitializer*> MemInits, |
5800 | bool AnyErrors) { |
5801 | if (!ConstructorDecl) |
5802 | return; |
5803 | |
5804 | AdjustDeclIfTemplate(Decl&: ConstructorDecl); |
5805 | |
5806 | CXXConstructorDecl *Constructor |
5807 | = dyn_cast<CXXConstructorDecl>(Val: ConstructorDecl); |
5808 | |
5809 | if (!Constructor) { |
5810 | Diag(ColonLoc, diag::err_only_constructors_take_base_inits); |
5811 | return; |
5812 | } |
5813 | |
5814 | // Mapping for the duplicate initializers check. |
5815 | // For member initializers, this is keyed with a FieldDecl*. |
5816 | // For base initializers, this is keyed with a Type*. |
5817 | llvm::DenseMap<const void *, CXXCtorInitializer *> Members; |
5818 | |
5819 | // Mapping for the inconsistent anonymous-union initializers check. |
5820 | RedundantUnionMap MemberUnions; |
5821 | |
5822 | bool HadError = false; |
5823 | for (unsigned i = 0; i < MemInits.size(); i++) { |
5824 | CXXCtorInitializer *Init = MemInits[i]; |
5825 | |
5826 | // Set the source order index. |
5827 | Init->setSourceOrder(i); |
5828 | |
5829 | if (Init->isAnyMemberInitializer()) { |
5830 | const void *Key = GetKeyForMember(Context, Member: Init); |
5831 | if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]) || |
5832 | CheckRedundantUnionInit(S&: *this, Init, Unions&: MemberUnions)) |
5833 | HadError = true; |
5834 | } else if (Init->isBaseInitializer()) { |
5835 | const void *Key = GetKeyForMember(Context, Member: Init); |
5836 | if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key])) |
5837 | HadError = true; |
5838 | } else { |
5839 | assert(Init->isDelegatingInitializer()); |
5840 | // This must be the only initializer |
5841 | if (MemInits.size() != 1) { |
5842 | Diag(Init->getSourceLocation(), |
5843 | diag::err_delegating_initializer_alone) |
5844 | << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); |
5845 | // We will treat this as being the only initializer. |
5846 | } |
5847 | SetDelegatingInitializer(Constructor, Initializer: MemInits[i]); |
5848 | // Return immediately as the initializer is set. |
5849 | return; |
5850 | } |
5851 | } |
5852 | |
5853 | if (HadError) |
5854 | return; |
5855 | |
5856 | DiagnoseBaseOrMemInitializerOrder(SemaRef&: *this, Constructor, Inits: MemInits); |
5857 | |
5858 | SetCtorInitializers(Constructor, AnyErrors, Initializers: MemInits); |
5859 | |
5860 | DiagnoseUninitializedFields(SemaRef&: *this, Constructor); |
5861 | } |
5862 | |
5863 | void |
5864 | Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, |
5865 | CXXRecordDecl *ClassDecl) { |
5866 | // Ignore dependent contexts. Also ignore unions, since their members never |
5867 | // have destructors implicitly called. |
5868 | if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) |
5869 | return; |
5870 | |
5871 | // FIXME: all the access-control diagnostics are positioned on the |
5872 | // field/base declaration. That's probably good; that said, the |
5873 | // user might reasonably want to know why the destructor is being |
5874 | // emitted, and we currently don't say. |
5875 | |
5876 | // Non-static data members. |
5877 | for (auto *Field : ClassDecl->fields()) { |
5878 | if (Field->isInvalidDecl()) |
5879 | continue; |
5880 | |
5881 | // Don't destroy incomplete or zero-length arrays. |
5882 | if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) |
5883 | continue; |
5884 | |
5885 | QualType FieldType = Context.getBaseElementType(Field->getType()); |
5886 | |
5887 | const RecordType* RT = FieldType->getAs<RecordType>(); |
5888 | if (!RT) |
5889 | continue; |
5890 | |
5891 | CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); |
5892 | if (FieldClassDecl->isInvalidDecl()) |
5893 | continue; |
5894 | if (FieldClassDecl->hasIrrelevantDestructor()) |
5895 | continue; |
5896 | // The destructor for an implicit anonymous union member is never invoked. |
5897 | if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) |
5898 | continue; |
5899 | |
5900 | CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); |
5901 | // Dtor might still be missing, e.g because it's invalid. |
5902 | if (!Dtor) |
5903 | continue; |
5904 | CheckDestructorAccess(Field->getLocation(), Dtor, |
5905 | PDiag(diag::err_access_dtor_field) |
5906 | << Field->getDeclName() |
5907 | << FieldType); |
5908 | |
5909 | MarkFunctionReferenced(Location, Dtor); |
5910 | DiagnoseUseOfDecl(Dtor, Location); |
5911 | } |
5912 | |
5913 | // We only potentially invoke the destructors of potentially constructed |
5914 | // subobjects. |
5915 | bool VisitVirtualBases = !ClassDecl->isAbstract(); |
5916 | |
5917 | // If the destructor exists and has already been marked used in the MS ABI, |
5918 | // then virtual base destructors have already been checked and marked used. |
5919 | // Skip checking them again to avoid duplicate diagnostics. |
5920 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
5921 | CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); |
5922 | if (Dtor && Dtor->isUsed()) |
5923 | VisitVirtualBases = false; |
5924 | } |
5925 | |
5926 | llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; |
5927 | |
5928 | // Bases. |
5929 | for (const auto &Base : ClassDecl->bases()) { |
5930 | const RecordType *RT = Base.getType()->getAs<RecordType>(); |
5931 | if (!RT) |
5932 | continue; |
5933 | |
5934 | // Remember direct virtual bases. |
5935 | if (Base.isVirtual()) { |
5936 | if (!VisitVirtualBases) |
5937 | continue; |
5938 | DirectVirtualBases.insert(Ptr: RT); |
5939 | } |
5940 | |
5941 | CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(Val: RT->getDecl()); |
5942 | // If our base class is invalid, we probably can't get its dtor anyway. |
5943 | if (BaseClassDecl->isInvalidDecl()) |
5944 | continue; |
5945 | if (BaseClassDecl->hasIrrelevantDestructor()) |
5946 | continue; |
5947 | |
5948 | CXXDestructorDecl *Dtor = LookupDestructor(Class: BaseClassDecl); |
5949 | // Dtor might still be missing, e.g because it's invalid. |
5950 | if (!Dtor) |
5951 | continue; |
5952 | |
5953 | // FIXME: caret should be on the start of the class name |
5954 | CheckDestructorAccess(Base.getBeginLoc(), Dtor, |
5955 | PDiag(diag::err_access_dtor_base) |
5956 | << Base.getType() << Base.getSourceRange(), |
5957 | Context.getTypeDeclType(ClassDecl)); |
5958 | |
5959 | MarkFunctionReferenced(Location, Dtor); |
5960 | DiagnoseUseOfDecl(Dtor, Location); |
5961 | } |
5962 | |
5963 | if (VisitVirtualBases) |
5964 | MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, |
5965 | DirectVirtualBases: &DirectVirtualBases); |
5966 | } |
5967 | |
5968 | void Sema::MarkVirtualBaseDestructorsReferenced( |
5969 | SourceLocation Location, CXXRecordDecl *ClassDecl, |
5970 | llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { |
5971 | // Virtual bases. |
5972 | for (const auto &VBase : ClassDecl->vbases()) { |
5973 | // Bases are always records in a well-formed non-dependent class. |
5974 | const RecordType *RT = VBase.getType()->castAs<RecordType>(); |
5975 | |
5976 | // Ignore already visited direct virtual bases. |
5977 | if (DirectVirtualBases && DirectVirtualBases->count(Ptr: RT)) |
5978 | continue; |
5979 | |
5980 | CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(Val: RT->getDecl()); |
5981 | // If our base class is invalid, we probably can't get its dtor anyway. |
5982 | if (BaseClassDecl->isInvalidDecl()) |
5983 | continue; |
5984 | if (BaseClassDecl->hasIrrelevantDestructor()) |
5985 | continue; |
5986 | |
5987 | CXXDestructorDecl *Dtor = LookupDestructor(Class: BaseClassDecl); |
5988 | // Dtor might still be missing, e.g because it's invalid. |
5989 | if (!Dtor) |
5990 | continue; |
5991 | if (CheckDestructorAccess( |
5992 | ClassDecl->getLocation(), Dtor, |
5993 | PDiag(diag::err_access_dtor_vbase) |
5994 | << Context.getTypeDeclType(ClassDecl) << VBase.getType(), |
5995 | Context.getTypeDeclType(ClassDecl)) == |
5996 | AR_accessible) { |
5997 | CheckDerivedToBaseConversion( |
5998 | Context.getTypeDeclType(ClassDecl), VBase.getType(), |
5999 | diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), |
6000 | SourceRange(), DeclarationName(), nullptr); |
6001 | } |
6002 | |
6003 | MarkFunctionReferenced(Location, Dtor); |
6004 | DiagnoseUseOfDecl(Dtor, Location); |
6005 | } |
6006 | } |
6007 | |
6008 | void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { |
6009 | if (!CDtorDecl) |
6010 | return; |
6011 | |
6012 | if (CXXConstructorDecl *Constructor |
6013 | = dyn_cast<CXXConstructorDecl>(Val: CDtorDecl)) { |
6014 | if (CXXRecordDecl *ClassDecl = Constructor->getParent(); |
6015 | !ClassDecl || ClassDecl->isInvalidDecl()) { |
6016 | return; |
6017 | } |
6018 | SetCtorInitializers(Constructor, /*AnyErrors=*/false); |
6019 | DiagnoseUninitializedFields(SemaRef&: *this, Constructor); |
6020 | } |
6021 | } |
6022 | |
6023 | bool Sema::isAbstractType(SourceLocation Loc, QualType T) { |
6024 | if (!getLangOpts().CPlusPlus) |
6025 | return false; |
6026 | |
6027 | const auto *RD = Context.getBaseElementType(QT: T)->getAsCXXRecordDecl(); |
6028 | if (!RD) |
6029 | return false; |
6030 | |
6031 | // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a |
6032 | // class template specialization here, but doing so breaks a lot of code. |
6033 | |
6034 | // We can't answer whether something is abstract until it has a |
6035 | // definition. If it's currently being defined, we'll walk back |
6036 | // over all the declarations when we have a full definition. |
6037 | const CXXRecordDecl *Def = RD->getDefinition(); |
6038 | if (!Def || Def->isBeingDefined()) |
6039 | return false; |
6040 | |
6041 | return RD->isAbstract(); |
6042 | } |
6043 | |
6044 | bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, |
6045 | TypeDiagnoser &Diagnoser) { |
6046 | if (!isAbstractType(Loc, T)) |
6047 | return false; |
6048 | |
6049 | T = Context.getBaseElementType(QT: T); |
6050 | Diagnoser.diagnose(S&: *this, Loc, T); |
6051 | DiagnoseAbstractType(RD: T->getAsCXXRecordDecl()); |
6052 | return true; |
6053 | } |
6054 | |
6055 | void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { |
6056 | // Check if we've already emitted the list of pure virtual functions |
6057 | // for this class. |
6058 | if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(Ptr: RD)) |
6059 | return; |
6060 | |
6061 | // If the diagnostic is suppressed, don't emit the notes. We're only |
6062 | // going to emit them once, so try to attach them to a diagnostic we're |
6063 | // actually going to show. |
6064 | if (Diags.isLastDiagnosticIgnored()) |
6065 | return; |
6066 | |
6067 | CXXFinalOverriderMap FinalOverriders; |
6068 | RD->getFinalOverriders(FinaOverriders&: FinalOverriders); |
6069 | |
6070 | // Keep a set of seen pure methods so we won't diagnose the same method |
6071 | // more than once. |
6072 | llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; |
6073 | |
6074 | for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), |
6075 | MEnd = FinalOverriders.end(); |
6076 | M != MEnd; |
6077 | ++M) { |
6078 | for (OverridingMethods::iterator SO = M->second.begin(), |
6079 | SOEnd = M->second.end(); |
6080 | SO != SOEnd; ++SO) { |
6081 | // C++ [class.abstract]p4: |
6082 | // A class is abstract if it contains or inherits at least one |
6083 | // pure virtual function for which the final overrider is pure |
6084 | // virtual. |
6085 | |
6086 | // |
6087 | if (SO->second.size() != 1) |
6088 | continue; |
6089 | |
6090 | if (!SO->second.front().Method->isPureVirtual()) |
6091 | continue; |
6092 | |
6093 | if (!SeenPureMethods.insert(Ptr: SO->second.front().Method).second) |
6094 | continue; |
6095 | |
6096 | Diag(SO->second.front().Method->getLocation(), |
6097 | diag::note_pure_virtual_function) |
6098 | << SO->second.front().Method->getDeclName() << RD->getDeclName(); |
6099 | } |
6100 | } |
6101 | |
6102 | if (!PureVirtualClassDiagSet) |
6103 | PureVirtualClassDiagSet.reset(p: new RecordDeclSetTy); |
6104 | PureVirtualClassDiagSet->insert(Ptr: RD); |
6105 | } |
6106 | |
6107 | namespace { |
6108 | struct AbstractUsageInfo { |
6109 | Sema &S; |
6110 | CXXRecordDecl *Record; |
6111 | CanQualType AbstractType; |
6112 | bool Invalid; |
6113 | |
6114 | AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) |
6115 | : S(S), Record(Record), |
6116 | AbstractType(S.Context.getCanonicalType( |
6117 | S.Context.getTypeDeclType(Record))), |
6118 | Invalid(false) {} |
6119 | |
6120 | void DiagnoseAbstractType() { |
6121 | if (Invalid) return; |
6122 | S.DiagnoseAbstractType(RD: Record); |
6123 | Invalid = true; |
6124 | } |
6125 | |
6126 | void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); |
6127 | }; |
6128 | |
6129 | struct CheckAbstractUsage { |
6130 | AbstractUsageInfo &Info; |
6131 | const NamedDecl *Ctx; |
6132 | |
6133 | CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) |
6134 | : Info(Info), Ctx(Ctx) {} |
6135 | |
6136 | void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { |
6137 | switch (TL.getTypeLocClass()) { |
6138 | #define ABSTRACT_TYPELOC(CLASS, PARENT) |
6139 | #define TYPELOC(CLASS, PARENT) \ |
6140 | case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; |
6141 | #include "clang/AST/TypeLocNodes.def" |
6142 | } |
6143 | } |
6144 | |
6145 | void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { |
6146 | Visit(TL: TL.getReturnLoc(), Sel: Sema::AbstractReturnType); |
6147 | for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { |
6148 | if (!TL.getParam(I)) |
6149 | continue; |
6150 | |
6151 | TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); |
6152 | if (TSI) Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractParamType); |
6153 | } |
6154 | } |
6155 | |
6156 | void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { |
6157 | Visit(TL: TL.getElementLoc(), Sel: Sema::AbstractArrayType); |
6158 | } |
6159 | |
6160 | void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { |
6161 | // Visit the type parameters from a permissive context. |
6162 | for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { |
6163 | TemplateArgumentLoc TAL = TL.getArgLoc(i: I); |
6164 | if (TAL.getArgument().getKind() == TemplateArgument::Type) |
6165 | if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) |
6166 | Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone); |
6167 | // TODO: other template argument types? |
6168 | } |
6169 | } |
6170 | |
6171 | // Visit pointee types from a permissive context. |
6172 | #define CheckPolymorphic(Type) \ |
6173 | void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ |
6174 | Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ |
6175 | } |
6176 | CheckPolymorphic(PointerTypeLoc) |
6177 | CheckPolymorphic(ReferenceTypeLoc) |
6178 | CheckPolymorphic(MemberPointerTypeLoc) |
6179 | CheckPolymorphic(BlockPointerTypeLoc) |
6180 | CheckPolymorphic(AtomicTypeLoc) |
6181 | |
6182 | /// Handle all the types we haven't given a more specific |
6183 | /// implementation for above. |
6184 | void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { |
6185 | // Every other kind of type that we haven't called out already |
6186 | // that has an inner type is either (1) sugar or (2) contains that |
6187 | // inner type in some way as a subobject. |
6188 | if (TypeLoc Next = TL.getNextTypeLoc()) |
6189 | return Visit(TL: Next, Sel); |
6190 | |
6191 | // If there's no inner type and we're in a permissive context, |
6192 | // don't diagnose. |
6193 | if (Sel == Sema::AbstractNone) return; |
6194 | |
6195 | // Check whether the type matches the abstract type. |
6196 | QualType T = TL.getType(); |
6197 | if (T->isArrayType()) { |
6198 | Sel = Sema::AbstractArrayType; |
6199 | T = Info.S.Context.getBaseElementType(QT: T); |
6200 | } |
6201 | CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); |
6202 | if (CT != Info.AbstractType) return; |
6203 | |
6204 | // It matched; do some magic. |
6205 | // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646. |
6206 | if (Sel == Sema::AbstractArrayType) { |
6207 | Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) |
6208 | << T << TL.getSourceRange(); |
6209 | } else { |
6210 | Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) |
6211 | << Sel << T << TL.getSourceRange(); |
6212 | } |
6213 | Info.DiagnoseAbstractType(); |
6214 | } |
6215 | }; |
6216 | |
6217 | void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, |
6218 | Sema::AbstractDiagSelID Sel) { |
6219 | CheckAbstractUsage(*this, D).Visit(TL, Sel); |
6220 | } |
6221 | |
6222 | } |
6223 | |
6224 | /// Check for invalid uses of an abstract type in a function declaration. |
6225 | static void CheckAbstractClassUsage(AbstractUsageInfo &Info, |
6226 | FunctionDecl *FD) { |
6227 | // Only definitions are required to refer to complete and |
6228 | // non-abstract types. |
6229 | if (!FD->doesThisDeclarationHaveABody()) |
6230 | return; |
6231 | |
6232 | // For safety's sake, just ignore it if we don't have type source |
6233 | // information. This should never happen for non-implicit methods, |
6234 | // but... |
6235 | if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) |
6236 | Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone); |
6237 | } |
6238 | |
6239 | /// Check for invalid uses of an abstract type in a variable0 declaration. |
6240 | static void CheckAbstractClassUsage(AbstractUsageInfo &Info, |
6241 | VarDecl *VD) { |
6242 | // No need to do the check on definitions, which require that |
6243 | // the type is complete. |
6244 | if (VD->isThisDeclarationADefinition()) |
6245 | return; |
6246 | |
6247 | Info.CheckType(D: VD, TL: VD->getTypeSourceInfo()->getTypeLoc(), |
6248 | Sel: Sema::AbstractVariableType); |
6249 | } |
6250 | |
6251 | /// Check for invalid uses of an abstract type within a class definition. |
6252 | static void CheckAbstractClassUsage(AbstractUsageInfo &Info, |
6253 | CXXRecordDecl *RD) { |
6254 | for (auto *D : RD->decls()) { |
6255 | if (D->isImplicit()) continue; |
6256 | |
6257 | // Step through friends to the befriended declaration. |
6258 | if (auto *FD = dyn_cast<FriendDecl>(D)) { |
6259 | D = FD->getFriendDecl(); |
6260 | if (!D) continue; |
6261 | } |
6262 | |
6263 | // Functions and function templates. |
6264 | if (auto *FD = dyn_cast<FunctionDecl>(D)) { |
6265 | CheckAbstractClassUsage(Info, FD); |
6266 | } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) { |
6267 | CheckAbstractClassUsage(Info, FTD->getTemplatedDecl()); |
6268 | |
6269 | // Fields and static variables. |
6270 | } else if (auto *FD = dyn_cast<FieldDecl>(D)) { |
6271 | if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) |
6272 | Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); |
6273 | } else if (auto *VD = dyn_cast<VarDecl>(D)) { |
6274 | CheckAbstractClassUsage(Info, VD); |
6275 | } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) { |
6276 | CheckAbstractClassUsage(Info, VTD->getTemplatedDecl()); |
6277 | |
6278 | // Nested classes and class templates. |
6279 | } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { |
6280 | CheckAbstractClassUsage(Info, RD); |
6281 | } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) { |
6282 | CheckAbstractClassUsage(Info, CTD->getTemplatedDecl()); |
6283 | } |
6284 | } |
6285 | } |
6286 | |
6287 | static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { |
6288 | Attr *ClassAttr = getDLLAttr(Class); |
6289 | if (!ClassAttr) |
6290 | return; |
6291 | |
6292 | assert(ClassAttr->getKind() == attr::DLLExport); |
6293 | |
6294 | TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); |
6295 | |
6296 | if (TSK == TSK_ExplicitInstantiationDeclaration) |
6297 | // Don't go any further if this is just an explicit instantiation |
6298 | // declaration. |
6299 | return; |
6300 | |
6301 | // Add a context note to explain how we got to any diagnostics produced below. |
6302 | struct MarkingClassDllexported { |
6303 | Sema &S; |
6304 | MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, |
6305 | SourceLocation AttrLoc) |
6306 | : S(S) { |
6307 | Sema::CodeSynthesisContext Ctx; |
6308 | Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; |
6309 | Ctx.PointOfInstantiation = AttrLoc; |
6310 | Ctx.Entity = Class; |
6311 | S.pushCodeSynthesisContext(Ctx); |
6312 | } |
6313 | ~MarkingClassDllexported() { |
6314 | S.popCodeSynthesisContext(); |
6315 | } |
6316 | } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); |
6317 | |
6318 | if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) |
6319 | S.MarkVTableUsed(Loc: Class->getLocation(), Class, DefinitionRequired: true); |
6320 | |
6321 | for (Decl *Member : Class->decls()) { |
6322 | // Skip members that were not marked exported. |
6323 | if (!Member->hasAttr<DLLExportAttr>()) |
6324 | continue; |
6325 | |
6326 | // Defined static variables that are members of an exported base |
6327 | // class must be marked export too. |
6328 | auto *VD = dyn_cast<VarDecl>(Member); |
6329 | if (VD && VD->getStorageClass() == SC_Static && |
6330 | TSK == TSK_ImplicitInstantiation) |
6331 | S.MarkVariableReferenced(VD->getLocation(), VD); |
6332 | |
6333 | auto *MD = dyn_cast<CXXMethodDecl>(Member); |
6334 | if (!MD) |
6335 | continue; |
6336 | |
6337 | if (MD->isUserProvided()) { |
6338 | // Instantiate non-default class member functions ... |
6339 | |
6340 | // .. except for certain kinds of template specializations. |
6341 | if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) |
6342 | continue; |
6343 | |
6344 | // If this is an MS ABI dllexport default constructor, instantiate any |
6345 | // default arguments. |
6346 | if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
6347 | auto *CD = dyn_cast<CXXConstructorDecl>(MD); |
6348 | if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) { |
6349 | S.InstantiateDefaultCtorDefaultArgs(CD); |
6350 | } |
6351 | } |
6352 | |
6353 | S.MarkFunctionReferenced(Class->getLocation(), MD); |
6354 | |
6355 | // The function will be passed to the consumer when its definition is |
6356 | // encountered. |
6357 | } else if (MD->isExplicitlyDefaulted()) { |
6358 | // Synthesize and instantiate explicitly defaulted methods. |
6359 | S.MarkFunctionReferenced(Class->getLocation(), MD); |
6360 | |
6361 | if (TSK != TSK_ExplicitInstantiationDefinition) { |
6362 | // Except for explicit instantiation defs, we will not see the |
6363 | // definition again later, so pass it to the consumer now. |
6364 | S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); |
6365 | } |
6366 | } else if (!MD->isTrivial() || |
6367 | MD->isCopyAssignmentOperator() || |
6368 | MD->isMoveAssignmentOperator()) { |
6369 | // Synthesize and instantiate non-trivial implicit methods, and the copy |
6370 | // and move assignment operators. The latter are exported even if they |
6371 | // are trivial, because the address of an operator can be taken and |
6372 | // should compare equal across libraries. |
6373 | S.MarkFunctionReferenced(Class->getLocation(), MD); |
6374 | |
6375 | // There is no later point when we will see the definition of this |
6376 | // function, so pass it to the consumer now. |
6377 | S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); |
6378 | } |
6379 | } |
6380 | } |
6381 | |
6382 | static void checkForMultipleExportedDefaultConstructors(Sema &S, |
6383 | CXXRecordDecl *Class) { |
6384 | // Only the MS ABI has default constructor closures, so we don't need to do |
6385 | // this semantic checking anywhere else. |
6386 | if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) |
6387 | return; |
6388 | |
6389 | CXXConstructorDecl *LastExportedDefaultCtor = nullptr; |
6390 | for (Decl *Member : Class->decls()) { |
6391 | // Look for exported default constructors. |
6392 | auto *CD = dyn_cast<CXXConstructorDecl>(Member); |
6393 | if (!CD || !CD->isDefaultConstructor()) |
6394 | continue; |
6395 | auto *Attr = CD->getAttr<DLLExportAttr>(); |
6396 | if (!Attr) |
6397 | continue; |
6398 | |
6399 | // If the class is non-dependent, mark the default arguments as ODR-used so |
6400 | // that we can properly codegen the constructor closure. |
6401 | if (!Class->isDependentContext()) { |
6402 | for (ParmVarDecl *PD : CD->parameters()) { |
6403 | (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); |
6404 | S.DiscardCleanupsInEvaluationContext(); |
6405 | } |
6406 | } |
6407 | |
6408 | if (LastExportedDefaultCtor) { |
6409 | S.Diag(LastExportedDefaultCtor->getLocation(), |
6410 | diag::err_attribute_dll_ambiguous_default_ctor) |
6411 | << Class; |
6412 | S.Diag(CD->getLocation(), diag::note_entity_declared_at) |
6413 | << CD->getDeclName(); |
6414 | return; |
6415 | } |
6416 | LastExportedDefaultCtor = CD; |
6417 | } |
6418 | } |
6419 | |
6420 | static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, |
6421 | CXXRecordDecl *Class) { |
6422 | bool ErrorReported = false; |
6423 | auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, |
6424 | ClassTemplateDecl *TD) { |
6425 | if (ErrorReported) |
6426 | return; |
6427 | S.Diag(TD->getLocation(), |
6428 | diag::err_cuda_device_builtin_surftex_cls_template) |
6429 | << /*surface*/ 0 << TD; |
6430 | ErrorReported = true; |
6431 | }; |
6432 | |
6433 | ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); |
6434 | if (!TD) { |
6435 | auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class); |
6436 | if (!SD) { |
6437 | S.Diag(Class->getLocation(), |
6438 | diag::err_cuda_device_builtin_surftex_ref_decl) |
6439 | << /*surface*/ 0 << Class; |
6440 | S.Diag(Class->getLocation(), |
6441 | diag::note_cuda_device_builtin_surftex_should_be_template_class) |
6442 | << Class; |
6443 | return; |
6444 | } |
6445 | TD = SD->getSpecializedTemplate(); |
6446 | } |
6447 | |
6448 | TemplateParameterList *Params = TD->getTemplateParameters(); |
6449 | unsigned N = Params->size(); |
6450 | |
6451 | if (N != 2) { |
6452 | reportIllegalClassTemplate(S, TD); |
6453 | S.Diag(TD->getLocation(), |
6454 | diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) |
6455 | << TD << 2; |
6456 | } |
6457 | if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) { |
6458 | reportIllegalClassTemplate(S, TD); |
6459 | S.Diag(TD->getLocation(), |
6460 | diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) |
6461 | << TD << /*1st*/ 0 << /*type*/ 0; |
6462 | } |
6463 | if (N > 1) { |
6464 | auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1)); |
6465 | if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { |
6466 | reportIllegalClassTemplate(S, TD); |
6467 | S.Diag(TD->getLocation(), |
6468 | diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) |
6469 | << TD << /*2nd*/ 1 << /*integer*/ 1; |
6470 | } |
6471 | } |
6472 | } |
6473 | |
6474 | static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, |
6475 | CXXRecordDecl *Class) { |
6476 | bool ErrorReported = false; |
6477 | auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, |
6478 | ClassTemplateDecl *TD) { |
6479 | if (ErrorReported) |
6480 | return; |
6481 | S.Diag(TD->getLocation(), |
6482 | diag::err_cuda_device_builtin_surftex_cls_template) |
6483 | << /*texture*/ 1 << TD; |
6484 | ErrorReported = true; |
6485 | }; |
6486 | |
6487 | ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); |
6488 | if (!TD) { |
6489 | auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class); |
6490 | if (!SD) { |
6491 | S.Diag(Class->getLocation(), |
6492 | diag::err_cuda_device_builtin_surftex_ref_decl) |
6493 | << /*texture*/ 1 << Class; |
6494 | S.Diag(Class->getLocation(), |
6495 | diag::note_cuda_device_builtin_surftex_should_be_template_class) |
6496 | << Class; |
6497 | return; |
6498 | } |
6499 | TD = SD->getSpecializedTemplate(); |
6500 | } |
6501 | |
6502 | TemplateParameterList *Params = TD->getTemplateParameters(); |
6503 | unsigned N = Params->size(); |
6504 | |
6505 | if (N != 3) { |
6506 | reportIllegalClassTemplate(S, TD); |
6507 | S.Diag(TD->getLocation(), |
6508 | diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) |
6509 | << TD << 3; |
6510 | } |
6511 | if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) { |
6512 | reportIllegalClassTemplate(S, TD); |
6513 | S.Diag(TD->getLocation(), |
6514 | diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) |
6515 | << TD << /*1st*/ 0 << /*type*/ 0; |
6516 | } |
6517 | if (N > 1) { |
6518 | auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1)); |
6519 | if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { |
6520 | reportIllegalClassTemplate(S, TD); |
6521 | S.Diag(TD->getLocation(), |
6522 | diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) |
6523 | << TD << /*2nd*/ 1 << /*integer*/ 1; |
6524 | } |
6525 | } |
6526 | if (N > 2) { |
6527 | auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 2)); |
6528 | if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { |
6529 | reportIllegalClassTemplate(S, TD); |
6530 | S.Diag(TD->getLocation(), |
6531 | diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) |
6532 | << TD << /*3rd*/ 2 << /*integer*/ 1; |
6533 | } |
6534 | } |
6535 | } |
6536 | |
6537 | void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { |
6538 | // Mark any compiler-generated routines with the implicit code_seg attribute. |
6539 | for (auto *Method : Class->methods()) { |
6540 | if (Method->isUserProvided()) |
6541 | continue; |
6542 | if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) |
6543 | Method->addAttr(A); |
6544 | } |
6545 | } |
6546 | |
6547 | /// Check class-level dllimport/dllexport attribute. |
6548 | void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { |
6549 | Attr *ClassAttr = getDLLAttr(Class); |
6550 | |
6551 | // MSVC inherits DLL attributes to partial class template specializations. |
6552 | if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { |
6553 | if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Class)) { |
6554 | if (Attr *TemplateAttr = |
6555 | getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { |
6556 | auto *A = cast<InheritableAttr>(Val: TemplateAttr->clone(C&: getASTContext())); |
6557 | A->setInherited(true); |
6558 | ClassAttr = A; |
6559 | } |
6560 | } |
6561 | } |
6562 | |
6563 | if (!ClassAttr) |
6564 | return; |
6565 | |
6566 | // MSVC allows imported or exported template classes that have UniqueExternal |
6567 | // linkage. This occurs when the template class has been instantiated with |
6568 | // a template parameter which itself has internal linkage. |
6569 | // We drop the attribute to avoid exporting or importing any members. |
6570 | if ((Context.getTargetInfo().getCXXABI().isMicrosoft() || |
6571 | Context.getTargetInfo().getTriple().isPS()) && |
6572 | (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) { |
6573 | Class->dropAttrs<DLLExportAttr, DLLImportAttr>(); |
6574 | return; |
6575 | } |
6576 | |
6577 | if (!Class->isExternallyVisible()) { |
6578 | Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) |
6579 | << Class << ClassAttr; |
6580 | return; |
6581 | } |
6582 | |
6583 | if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && |
6584 | !ClassAttr->isInherited()) { |
6585 | // Diagnose dll attributes on members of class with dll attribute. |
6586 | for (Decl *Member : Class->decls()) { |
6587 | if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) |
6588 | continue; |
6589 | InheritableAttr *MemberAttr = getDLLAttr(Member); |
6590 | if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) |
6591 | continue; |
6592 | |
6593 | Diag(MemberAttr->getLocation(), |
6594 | diag::err_attribute_dll_member_of_dll_class) |
6595 | << MemberAttr << ClassAttr; |
6596 | Diag(ClassAttr->getLocation(), diag::note_previous_attribute); |
6597 | Member->setInvalidDecl(); |
6598 | } |
6599 | } |
6600 | |
6601 | if (Class->getDescribedClassTemplate()) |
6602 | // Don't inherit dll attribute until the template is instantiated. |
6603 | return; |
6604 | |
6605 | // The class is either imported or exported. |
6606 | const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; |
6607 | |
6608 | // Check if this was a dllimport attribute propagated from a derived class to |
6609 | // a base class template specialization. We don't apply these attributes to |
6610 | // static data members. |
6611 | const bool PropagatedImport = |
6612 | !ClassExported && |
6613 | cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); |
6614 | |
6615 | TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); |
6616 | |
6617 | // Ignore explicit dllexport on explicit class template instantiation |
6618 | // declarations, except in MinGW mode. |
6619 | if (ClassExported && !ClassAttr->isInherited() && |
6620 | TSK == TSK_ExplicitInstantiationDeclaration && |
6621 | !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { |
6622 | Class->dropAttr<DLLExportAttr>(); |
6623 | return; |
6624 | } |
6625 | |
6626 | // Force declaration of implicit members so they can inherit the attribute. |
6627 | ForceDeclarationOfImplicitMembers(Class); |
6628 | |
6629 | // FIXME: MSVC's docs say all bases must be exportable, but this doesn't |
6630 | // seem to be true in practice? |
6631 | |
6632 | for (Decl *Member : Class->decls()) { |
6633 | VarDecl *VD = dyn_cast<VarDecl>(Member); |
6634 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); |
6635 | |
6636 | // Only methods and static fields inherit the attributes. |
6637 | if (!VD && !MD) |
6638 | continue; |
6639 | |
6640 | if (MD) { |
6641 | // Don't process deleted methods. |
6642 | if (MD->isDeleted()) |
6643 | continue; |
6644 | |
6645 | if (MD->isInlined()) { |
6646 | // MinGW does not import or export inline methods. But do it for |
6647 | // template instantiations. |
6648 | if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && |
6649 | TSK != TSK_ExplicitInstantiationDeclaration && |
6650 | TSK != TSK_ExplicitInstantiationDefinition) |
6651 | continue; |
6652 | |
6653 | // MSVC versions before 2015 don't export the move assignment operators |
6654 | // and move constructor, so don't attempt to import/export them if |
6655 | // we have a definition. |
6656 | auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); |
6657 | if ((MD->isMoveAssignmentOperator() || |
6658 | (Ctor && Ctor->isMoveConstructor())) && |
6659 | !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) |
6660 | continue; |
6661 | |
6662 | // MSVC2015 doesn't export trivial defaulted x-tor but copy assign |
6663 | // operator is exported anyway. |
6664 | if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && |
6665 | (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) |
6666 | continue; |
6667 | } |
6668 | } |
6669 | |
6670 | // Don't apply dllimport attributes to static data members of class template |
6671 | // instantiations when the attribute is propagated from a derived class. |
6672 | if (VD && PropagatedImport) |
6673 | continue; |
6674 | |
6675 | if (!cast<NamedDecl>(Member)->isExternallyVisible()) |
6676 | continue; |
6677 | |
6678 | if (!getDLLAttr(Member)) { |
6679 | InheritableAttr *NewAttr = nullptr; |
6680 | |
6681 | // Do not export/import inline function when -fno-dllexport-inlines is |
6682 | // passed. But add attribute for later local static var check. |
6683 | if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && |
6684 | TSK != TSK_ExplicitInstantiationDeclaration && |
6685 | TSK != TSK_ExplicitInstantiationDefinition) { |
6686 | if (ClassExported) { |
6687 | NewAttr = ::new (getASTContext()) |
6688 | DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); |
6689 | } else { |
6690 | NewAttr = ::new (getASTContext()) |
6691 | DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); |
6692 | } |
6693 | } else { |
6694 | NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); |
6695 | } |
6696 | |
6697 | NewAttr->setInherited(true); |
6698 | Member->addAttr(NewAttr); |
6699 | |
6700 | if (MD) { |
6701 | // Propagate DLLAttr to friend re-declarations of MD that have already |
6702 | // been constructed. |
6703 | for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; |
6704 | FD = FD->getPreviousDecl()) { |
6705 | if (FD->getFriendObjectKind() == Decl::FOK_None) |
6706 | continue; |
6707 | assert(!getDLLAttr(FD) && |
6708 | "friend re-decl should not already have a DLLAttr" ); |
6709 | NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); |
6710 | NewAttr->setInherited(true); |
6711 | FD->addAttr(NewAttr); |
6712 | } |
6713 | } |
6714 | } |
6715 | } |
6716 | |
6717 | if (ClassExported) |
6718 | DelayedDllExportClasses.push_back(Elt: Class); |
6719 | } |
6720 | |
6721 | /// Perform propagation of DLL attributes from a derived class to a |
6722 | /// templated base class for MS compatibility. |
6723 | void Sema::propagateDLLAttrToBaseClassTemplate( |
6724 | CXXRecordDecl *Class, Attr *ClassAttr, |
6725 | ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { |
6726 | if (getDLLAttr( |
6727 | BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { |
6728 | // If the base class template has a DLL attribute, don't try to change it. |
6729 | return; |
6730 | } |
6731 | |
6732 | auto TSK = BaseTemplateSpec->getSpecializationKind(); |
6733 | if (!getDLLAttr(BaseTemplateSpec) && |
6734 | (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || |
6735 | TSK == TSK_ImplicitInstantiation)) { |
6736 | // The template hasn't been instantiated yet (or it has, but only as an |
6737 | // explicit instantiation declaration or implicit instantiation, which means |
6738 | // we haven't codegenned any members yet), so propagate the attribute. |
6739 | auto *NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext())); |
6740 | NewAttr->setInherited(true); |
6741 | BaseTemplateSpec->addAttr(NewAttr); |
6742 | |
6743 | // If this was an import, mark that we propagated it from a derived class to |
6744 | // a base class template specialization. |
6745 | if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) |
6746 | ImportAttr->setPropagatedToBaseTemplate(); |
6747 | |
6748 | // If the template is already instantiated, checkDLLAttributeRedeclaration() |
6749 | // needs to be run again to work see the new attribute. Otherwise this will |
6750 | // get run whenever the template is instantiated. |
6751 | if (TSK != TSK_Undeclared) |
6752 | checkClassLevelDLLAttribute(BaseTemplateSpec); |
6753 | |
6754 | return; |
6755 | } |
6756 | |
6757 | if (getDLLAttr(BaseTemplateSpec)) { |
6758 | // The template has already been specialized or instantiated with an |
6759 | // attribute, explicitly or through propagation. We should not try to change |
6760 | // it. |
6761 | return; |
6762 | } |
6763 | |
6764 | // The template was previously instantiated or explicitly specialized without |
6765 | // a dll attribute, It's too late for us to add an attribute, so warn that |
6766 | // this is unsupported. |
6767 | Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) |
6768 | << BaseTemplateSpec->isExplicitSpecialization(); |
6769 | Diag(ClassAttr->getLocation(), diag::note_attribute); |
6770 | if (BaseTemplateSpec->isExplicitSpecialization()) { |
6771 | Diag(BaseTemplateSpec->getLocation(), |
6772 | diag::note_template_class_explicit_specialization_was_here) |
6773 | << BaseTemplateSpec; |
6774 | } else { |
6775 | Diag(BaseTemplateSpec->getPointOfInstantiation(), |
6776 | diag::note_template_class_instantiation_was_here) |
6777 | << BaseTemplateSpec; |
6778 | } |
6779 | } |
6780 | |
6781 | /// Determine the kind of defaulting that would be done for a given function. |
6782 | /// |
6783 | /// If the function is both a default constructor and a copy / move constructor |
6784 | /// (due to having a default argument for the first parameter), this picks |
6785 | /// CXXSpecialMemberKind::DefaultConstructor. |
6786 | /// |
6787 | /// FIXME: Check that case is properly handled by all callers. |
6788 | Sema::DefaultedFunctionKind |
6789 | Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { |
6790 | if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) { |
6791 | if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) { |
6792 | if (Ctor->isDefaultConstructor()) |
6793 | return CXXSpecialMemberKind::DefaultConstructor; |
6794 | |
6795 | if (Ctor->isCopyConstructor()) |
6796 | return CXXSpecialMemberKind::CopyConstructor; |
6797 | |
6798 | if (Ctor->isMoveConstructor()) |
6799 | return CXXSpecialMemberKind::MoveConstructor; |
6800 | } |
6801 | |
6802 | if (MD->isCopyAssignmentOperator()) |
6803 | return CXXSpecialMemberKind::CopyAssignment; |
6804 | |
6805 | if (MD->isMoveAssignmentOperator()) |
6806 | return CXXSpecialMemberKind::MoveAssignment; |
6807 | |
6808 | if (isa<CXXDestructorDecl>(Val: FD)) |
6809 | return CXXSpecialMemberKind::Destructor; |
6810 | } |
6811 | |
6812 | switch (FD->getDeclName().getCXXOverloadedOperator()) { |
6813 | case OO_EqualEqual: |
6814 | return DefaultedComparisonKind::Equal; |
6815 | |
6816 | case OO_ExclaimEqual: |
6817 | return DefaultedComparisonKind::NotEqual; |
6818 | |
6819 | case OO_Spaceship: |
6820 | // No point allowing this if <=> doesn't exist in the current language mode. |
6821 | if (!getLangOpts().CPlusPlus20) |
6822 | break; |
6823 | return DefaultedComparisonKind::ThreeWay; |
6824 | |
6825 | case OO_Less: |
6826 | case OO_LessEqual: |
6827 | case OO_Greater: |
6828 | case OO_GreaterEqual: |
6829 | // No point allowing this if <=> doesn't exist in the current language mode. |
6830 | if (!getLangOpts().CPlusPlus20) |
6831 | break; |
6832 | return DefaultedComparisonKind::Relational; |
6833 | |
6834 | default: |
6835 | break; |
6836 | } |
6837 | |
6838 | // Not defaultable. |
6839 | return DefaultedFunctionKind(); |
6840 | } |
6841 | |
6842 | static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, |
6843 | SourceLocation DefaultLoc) { |
6844 | Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); |
6845 | if (DFK.isComparison()) |
6846 | return S.DefineDefaultedComparison(Loc: DefaultLoc, FD, DCK: DFK.asComparison()); |
6847 | |
6848 | switch (DFK.asSpecialMember()) { |
6849 | case CXXSpecialMemberKind::DefaultConstructor: |
6850 | S.DefineImplicitDefaultConstructor(CurrentLocation: DefaultLoc, |
6851 | Constructor: cast<CXXConstructorDecl>(Val: FD)); |
6852 | break; |
6853 | case CXXSpecialMemberKind::CopyConstructor: |
6854 | S.DefineImplicitCopyConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD)); |
6855 | break; |
6856 | case CXXSpecialMemberKind::CopyAssignment: |
6857 | S.DefineImplicitCopyAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD)); |
6858 | break; |
6859 | case CXXSpecialMemberKind::Destructor: |
6860 | S.DefineImplicitDestructor(CurrentLocation: DefaultLoc, Destructor: cast<CXXDestructorDecl>(Val: FD)); |
6861 | break; |
6862 | case CXXSpecialMemberKind::MoveConstructor: |
6863 | S.DefineImplicitMoveConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD)); |
6864 | break; |
6865 | case CXXSpecialMemberKind::MoveAssignment: |
6866 | S.DefineImplicitMoveAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD)); |
6867 | break; |
6868 | case CXXSpecialMemberKind::Invalid: |
6869 | llvm_unreachable("Invalid special member." ); |
6870 | } |
6871 | } |
6872 | |
6873 | /// Determine whether a type is permitted to be passed or returned in |
6874 | /// registers, per C++ [class.temporary]p3. |
6875 | static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, |
6876 | TargetInfo::CallingConvKind CCK) { |
6877 | if (D->isDependentType() || D->isInvalidDecl()) |
6878 | return false; |
6879 | |
6880 | // Clang <= 4 used the pre-C++11 rule, which ignores move operations. |
6881 | // The PS4 platform ABI follows the behavior of Clang 3.2. |
6882 | if (CCK == TargetInfo::CCK_ClangABI4OrPS4) |
6883 | return !D->hasNonTrivialDestructorForCall() && |
6884 | !D->hasNonTrivialCopyConstructorForCall(); |
6885 | |
6886 | if (CCK == TargetInfo::CCK_MicrosoftWin64) { |
6887 | bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; |
6888 | bool DtorIsTrivialForCall = false; |
6889 | |
6890 | // If a class has at least one eligible, trivial copy constructor, it |
6891 | // is passed according to the C ABI. Otherwise, it is passed indirectly. |
6892 | // |
6893 | // Note: This permits classes with non-trivial copy or move ctors to be |
6894 | // passed in registers, so long as they *also* have a trivial copy ctor, |
6895 | // which is non-conforming. |
6896 | if (D->needsImplicitCopyConstructor()) { |
6897 | if (!D->defaultedCopyConstructorIsDeleted()) { |
6898 | if (D->hasTrivialCopyConstructor()) |
6899 | CopyCtorIsTrivial = true; |
6900 | if (D->hasTrivialCopyConstructorForCall()) |
6901 | CopyCtorIsTrivialForCall = true; |
6902 | } |
6903 | } else { |
6904 | for (const CXXConstructorDecl *CD : D->ctors()) { |
6905 | if (CD->isCopyConstructor() && !CD->isDeleted() && |
6906 | !CD->isIneligibleOrNotSelected()) { |
6907 | if (CD->isTrivial()) |
6908 | CopyCtorIsTrivial = true; |
6909 | if (CD->isTrivialForCall()) |
6910 | CopyCtorIsTrivialForCall = true; |
6911 | } |
6912 | } |
6913 | } |
6914 | |
6915 | if (D->needsImplicitDestructor()) { |
6916 | if (!D->defaultedDestructorIsDeleted() && |
6917 | D->hasTrivialDestructorForCall()) |
6918 | DtorIsTrivialForCall = true; |
6919 | } else if (const auto *DD = D->getDestructor()) { |
6920 | if (!DD->isDeleted() && DD->isTrivialForCall()) |
6921 | DtorIsTrivialForCall = true; |
6922 | } |
6923 | |
6924 | // If the copy ctor and dtor are both trivial-for-calls, pass direct. |
6925 | if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) |
6926 | return true; |
6927 | |
6928 | // If a class has a destructor, we'd really like to pass it indirectly |
6929 | // because it allows us to elide copies. Unfortunately, MSVC makes that |
6930 | // impossible for small types, which it will pass in a single register or |
6931 | // stack slot. Most objects with dtors are large-ish, so handle that early. |
6932 | // We can't call out all large objects as being indirect because there are |
6933 | // multiple x64 calling conventions and the C++ ABI code shouldn't dictate |
6934 | // how we pass large POD types. |
6935 | |
6936 | // Note: This permits small classes with nontrivial destructors to be |
6937 | // passed in registers, which is non-conforming. |
6938 | bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); |
6939 | uint64_t TypeSize = isAArch64 ? 128 : 64; |
6940 | |
6941 | if (CopyCtorIsTrivial && |
6942 | S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) |
6943 | return true; |
6944 | return false; |
6945 | } |
6946 | |
6947 | // Per C++ [class.temporary]p3, the relevant condition is: |
6948 | // each copy constructor, move constructor, and destructor of X is |
6949 | // either trivial or deleted, and X has at least one non-deleted copy |
6950 | // or move constructor |
6951 | bool HasNonDeletedCopyOrMove = false; |
6952 | |
6953 | if (D->needsImplicitCopyConstructor() && |
6954 | !D->defaultedCopyConstructorIsDeleted()) { |
6955 | if (!D->hasTrivialCopyConstructorForCall()) |
6956 | return false; |
6957 | HasNonDeletedCopyOrMove = true; |
6958 | } |
6959 | |
6960 | if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && |
6961 | !D->defaultedMoveConstructorIsDeleted()) { |
6962 | if (!D->hasTrivialMoveConstructorForCall()) |
6963 | return false; |
6964 | HasNonDeletedCopyOrMove = true; |
6965 | } |
6966 | |
6967 | if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && |
6968 | !D->hasTrivialDestructorForCall()) |
6969 | return false; |
6970 | |
6971 | for (const CXXMethodDecl *MD : D->methods()) { |
6972 | if (MD->isDeleted() || MD->isIneligibleOrNotSelected()) |
6973 | continue; |
6974 | |
6975 | auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD); |
6976 | if (CD && CD->isCopyOrMoveConstructor()) |
6977 | HasNonDeletedCopyOrMove = true; |
6978 | else if (!isa<CXXDestructorDecl>(Val: MD)) |
6979 | continue; |
6980 | |
6981 | if (!MD->isTrivialForCall()) |
6982 | return false; |
6983 | } |
6984 | |
6985 | return HasNonDeletedCopyOrMove; |
6986 | } |
6987 | |
6988 | /// Report an error regarding overriding, along with any relevant |
6989 | /// overridden methods. |
6990 | /// |
6991 | /// \param DiagID the primary error to report. |
6992 | /// \param MD the overriding method. |
6993 | static bool |
6994 | ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, |
6995 | llvm::function_ref<bool(const CXXMethodDecl *)> Report) { |
6996 | bool IssuedDiagnostic = false; |
6997 | for (const CXXMethodDecl *O : MD->overridden_methods()) { |
6998 | if (Report(O)) { |
6999 | if (!IssuedDiagnostic) { |
7000 | S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); |
7001 | IssuedDiagnostic = true; |
7002 | } |
7003 | S.Diag(O->getLocation(), diag::note_overridden_virtual_function); |
7004 | } |
7005 | } |
7006 | return IssuedDiagnostic; |
7007 | } |
7008 | |
7009 | /// Perform semantic checks on a class definition that has been |
7010 | /// completing, introducing implicitly-declared members, checking for |
7011 | /// abstract types, etc. |
7012 | /// |
7013 | /// \param S The scope in which the class was parsed. Null if we didn't just |
7014 | /// parse a class definition. |
7015 | /// \param Record The completed class. |
7016 | void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { |
7017 | if (!Record) |
7018 | return; |
7019 | |
7020 | if (Record->isAbstract() && !Record->isInvalidDecl()) { |
7021 | AbstractUsageInfo Info(*this, Record); |
7022 | CheckAbstractClassUsage(Info, RD: Record); |
7023 | } |
7024 | |
7025 | // If this is not an aggregate type and has no user-declared constructor, |
7026 | // complain about any non-static data members of reference or const scalar |
7027 | // type, since they will never get initializers. |
7028 | if (!Record->isInvalidDecl() && !Record->isDependentType() && |
7029 | !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && |
7030 | !Record->isLambda()) { |
7031 | bool Complained = false; |
7032 | for (const auto *F : Record->fields()) { |
7033 | if (F->hasInClassInitializer() || F->isUnnamedBitField()) |
7034 | continue; |
7035 | |
7036 | if (F->getType()->isReferenceType() || |
7037 | (F->getType().isConstQualified() && F->getType()->isScalarType())) { |
7038 | if (!Complained) { |
7039 | Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) |
7040 | << llvm::to_underlying(Record->getTagKind()) << Record; |
7041 | Complained = true; |
7042 | } |
7043 | |
7044 | Diag(F->getLocation(), diag::note_refconst_member_not_initialized) |
7045 | << F->getType()->isReferenceType() |
7046 | << F->getDeclName(); |
7047 | } |
7048 | } |
7049 | } |
7050 | |
7051 | if (Record->getIdentifier()) { |
7052 | // C++ [class.mem]p13: |
7053 | // If T is the name of a class, then each of the following shall have a |
7054 | // name different from T: |
7055 | // - every member of every anonymous union that is a member of class T. |
7056 | // |
7057 | // C++ [class.mem]p14: |
7058 | // In addition, if class T has a user-declared constructor (12.1), every |
7059 | // non-static data member of class T shall have a name different from T. |
7060 | DeclContext::lookup_result R = Record->lookup(Name: Record->getDeclName()); |
7061 | for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; |
7062 | ++I) { |
7063 | NamedDecl *D = (*I)->getUnderlyingDecl(); |
7064 | if (((isa<FieldDecl>(Val: D) || isa<UnresolvedUsingValueDecl>(Val: D)) && |
7065 | Record->hasUserDeclaredConstructor()) || |
7066 | isa<IndirectFieldDecl>(Val: D)) { |
7067 | Diag((*I)->getLocation(), diag::err_member_name_of_class) |
7068 | << D->getDeclName(); |
7069 | break; |
7070 | } |
7071 | } |
7072 | } |
7073 | |
7074 | // Warn if the class has virtual methods but non-virtual public destructor. |
7075 | if (Record->isPolymorphic() && !Record->isDependentType()) { |
7076 | CXXDestructorDecl *dtor = Record->getDestructor(); |
7077 | if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && |
7078 | !Record->hasAttr<FinalAttr>()) |
7079 | Diag(dtor ? dtor->getLocation() : Record->getLocation(), |
7080 | diag::warn_non_virtual_dtor) << Context.getRecordType(Record); |
7081 | } |
7082 | |
7083 | if (Record->isAbstract()) { |
7084 | if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { |
7085 | Diag(Record->getLocation(), diag::warn_abstract_final_class) |
7086 | << FA->isSpelledAsSealed(); |
7087 | DiagnoseAbstractType(RD: Record); |
7088 | } |
7089 | } |
7090 | |
7091 | // Warn if the class has a final destructor but is not itself marked final. |
7092 | if (!Record->hasAttr<FinalAttr>()) { |
7093 | if (const CXXDestructorDecl *dtor = Record->getDestructor()) { |
7094 | if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { |
7095 | Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) |
7096 | << FA->isSpelledAsSealed() |
7097 | << FixItHint::CreateInsertion( |
7098 | getLocForEndOfToken(Record->getLocation()), |
7099 | (FA->isSpelledAsSealed() ? " sealed" : " final" )); |
7100 | Diag(Record->getLocation(), |
7101 | diag::note_final_dtor_non_final_class_silence) |
7102 | << Context.getRecordType(Record) << FA->isSpelledAsSealed(); |
7103 | } |
7104 | } |
7105 | } |
7106 | |
7107 | // See if trivial_abi has to be dropped. |
7108 | if (Record->hasAttr<TrivialABIAttr>()) |
7109 | checkIllFormedTrivialABIStruct(RD&: *Record); |
7110 | |
7111 | // Set HasTrivialSpecialMemberForCall if the record has attribute |
7112 | // "trivial_abi". |
7113 | bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); |
7114 | |
7115 | if (HasTrivialABI) |
7116 | Record->setHasTrivialSpecialMemberForCall(); |
7117 | |
7118 | // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). |
7119 | // We check these last because they can depend on the properties of the |
7120 | // primary comparison functions (==, <=>). |
7121 | llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; |
7122 | |
7123 | // Perform checks that can't be done until we know all the properties of a |
7124 | // member function (whether it's defaulted, deleted, virtual, overriding, |
7125 | // ...). |
7126 | auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { |
7127 | // A static function cannot override anything. |
7128 | if (MD->getStorageClass() == SC_Static) { |
7129 | if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, |
7130 | [](const CXXMethodDecl *) { return true; })) |
7131 | return; |
7132 | } |
7133 | |
7134 | // A deleted function cannot override a non-deleted function and vice |
7135 | // versa. |
7136 | if (ReportOverrides(*this, |
7137 | MD->isDeleted() ? diag::err_deleted_override |
7138 | : diag::err_non_deleted_override, |
7139 | MD, [&](const CXXMethodDecl *V) { |
7140 | return MD->isDeleted() != V->isDeleted(); |
7141 | })) { |
7142 | if (MD->isDefaulted() && MD->isDeleted()) |
7143 | // Explain why this defaulted function was deleted. |
7144 | DiagnoseDeletedDefaultedFunction(MD); |
7145 | return; |
7146 | } |
7147 | |
7148 | // A consteval function cannot override a non-consteval function and vice |
7149 | // versa. |
7150 | if (ReportOverrides(*this, |
7151 | MD->isConsteval() ? diag::err_consteval_override |
7152 | : diag::err_non_consteval_override, |
7153 | MD, [&](const CXXMethodDecl *V) { |
7154 | return MD->isConsteval() != V->isConsteval(); |
7155 | })) { |
7156 | if (MD->isDefaulted() && MD->isDeleted()) |
7157 | // Explain why this defaulted function was deleted. |
7158 | DiagnoseDeletedDefaultedFunction(MD); |
7159 | return; |
7160 | } |
7161 | }; |
7162 | |
7163 | auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { |
7164 | if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) |
7165 | return false; |
7166 | |
7167 | DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); |
7168 | if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || |
7169 | DFK.asComparison() == DefaultedComparisonKind::Relational) { |
7170 | DefaultedSecondaryComparisons.push_back(Elt: FD); |
7171 | return true; |
7172 | } |
7173 | |
7174 | CheckExplicitlyDefaultedFunction(S, MD: FD); |
7175 | return false; |
7176 | }; |
7177 | |
7178 | auto CompleteMemberFunction = [&](CXXMethodDecl *M) { |
7179 | // Check whether the explicitly-defaulted members are valid. |
7180 | bool Incomplete = CheckForDefaultedFunction(M); |
7181 | |
7182 | // Skip the rest of the checks for a member of a dependent class. |
7183 | if (Record->isDependentType()) |
7184 | return; |
7185 | |
7186 | // For an explicitly defaulted or deleted special member, we defer |
7187 | // determining triviality until the class is complete. That time is now! |
7188 | CXXSpecialMemberKind CSM = getSpecialMember(MD: M); |
7189 | if (!M->isImplicit() && !M->isUserProvided()) { |
7190 | if (CSM != CXXSpecialMemberKind::Invalid) { |
7191 | M->setTrivial(SpecialMemberIsTrivial(MD: M, CSM)); |
7192 | // Inform the class that we've finished declaring this member. |
7193 | Record->finishedDefaultedOrDeletedMember(MD: M); |
7194 | M->setTrivialForCall( |
7195 | HasTrivialABI || |
7196 | SpecialMemberIsTrivial(MD: M, CSM, TAH: TAH_ConsiderTrivialABI)); |
7197 | Record->setTrivialForCallFlags(M); |
7198 | } |
7199 | } |
7200 | |
7201 | // Set triviality for the purpose of calls if this is a user-provided |
7202 | // copy/move constructor or destructor. |
7203 | if ((CSM == CXXSpecialMemberKind::CopyConstructor || |
7204 | CSM == CXXSpecialMemberKind::MoveConstructor || |
7205 | CSM == CXXSpecialMemberKind::Destructor) && |
7206 | M->isUserProvided()) { |
7207 | M->setTrivialForCall(HasTrivialABI); |
7208 | Record->setTrivialForCallFlags(M); |
7209 | } |
7210 | |
7211 | if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && |
7212 | M->hasAttr<DLLExportAttr>()) { |
7213 | if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && |
7214 | M->isTrivial() && |
7215 | (CSM == CXXSpecialMemberKind::DefaultConstructor || |
7216 | CSM == CXXSpecialMemberKind::CopyConstructor || |
7217 | CSM == CXXSpecialMemberKind::Destructor)) |
7218 | M->dropAttr<DLLExportAttr>(); |
7219 | |
7220 | if (M->hasAttr<DLLExportAttr>()) { |
7221 | // Define after any fields with in-class initializers have been parsed. |
7222 | DelayedDllExportMemberFunctions.push_back(Elt: M); |
7223 | } |
7224 | } |
7225 | |
7226 | // Define defaulted constexpr virtual functions that override a base class |
7227 | // function right away. |
7228 | // FIXME: We can defer doing this until the vtable is marked as used. |
7229 | if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() && |
7230 | M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) |
7231 | DefineDefaultedFunction(*this, M, M->getLocation()); |
7232 | |
7233 | if (!Incomplete) |
7234 | CheckCompletedMemberFunction(M); |
7235 | }; |
7236 | |
7237 | // Check the destructor before any other member function. We need to |
7238 | // determine whether it's trivial in order to determine whether the claas |
7239 | // type is a literal type, which is a prerequisite for determining whether |
7240 | // other special member functions are valid and whether they're implicitly |
7241 | // 'constexpr'. |
7242 | if (CXXDestructorDecl *Dtor = Record->getDestructor()) |
7243 | CompleteMemberFunction(Dtor); |
7244 | |
7245 | bool HasMethodWithOverrideControl = false, |
7246 | HasOverridingMethodWithoutOverrideControl = false; |
7247 | for (auto *D : Record->decls()) { |
7248 | if (auto *M = dyn_cast<CXXMethodDecl>(D)) { |
7249 | // FIXME: We could do this check for dependent types with non-dependent |
7250 | // bases. |
7251 | if (!Record->isDependentType()) { |
7252 | // See if a method overloads virtual methods in a base |
7253 | // class without overriding any. |
7254 | if (!M->isStatic()) |
7255 | DiagnoseHiddenVirtualMethods(M); |
7256 | if (M->hasAttr<OverrideAttr>()) |
7257 | HasMethodWithOverrideControl = true; |
7258 | else if (M->size_overridden_methods() > 0) |
7259 | HasOverridingMethodWithoutOverrideControl = true; |
7260 | } |
7261 | |
7262 | if (!isa<CXXDestructorDecl>(M)) |
7263 | CompleteMemberFunction(M); |
7264 | } else if (auto *F = dyn_cast<FriendDecl>(D)) { |
7265 | CheckForDefaultedFunction( |
7266 | dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); |
7267 | } |
7268 | } |
7269 | |
7270 | if (HasOverridingMethodWithoutOverrideControl) { |
7271 | bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; |
7272 | for (auto *M : Record->methods()) |
7273 | DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); |
7274 | } |
7275 | |
7276 | // Check the defaulted secondary comparisons after any other member functions. |
7277 | for (FunctionDecl *FD : DefaultedSecondaryComparisons) { |
7278 | CheckExplicitlyDefaultedFunction(S, MD: FD); |
7279 | |
7280 | // If this is a member function, we deferred checking it until now. |
7281 | if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) |
7282 | CheckCompletedMemberFunction(MD); |
7283 | } |
7284 | |
7285 | // ms_struct is a request to use the same ABI rules as MSVC. Check |
7286 | // whether this class uses any C++ features that are implemented |
7287 | // completely differently in MSVC, and if so, emit a diagnostic. |
7288 | // That diagnostic defaults to an error, but we allow projects to |
7289 | // map it down to a warning (or ignore it). It's a fairly common |
7290 | // practice among users of the ms_struct pragma to mass-annotate |
7291 | // headers, sweeping up a bunch of types that the project doesn't |
7292 | // really rely on MSVC-compatible layout for. We must therefore |
7293 | // support "ms_struct except for C++ stuff" as a secondary ABI. |
7294 | // Don't emit this diagnostic if the feature was enabled as a |
7295 | // language option (as opposed to via a pragma or attribute), as |
7296 | // the option -mms-bitfields otherwise essentially makes it impossible |
7297 | // to build C++ code, unless this diagnostic is turned off. |
7298 | if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && |
7299 | (Record->isPolymorphic() || Record->getNumBases())) { |
7300 | Diag(Record->getLocation(), diag::warn_cxx_ms_struct); |
7301 | } |
7302 | |
7303 | checkClassLevelDLLAttribute(Class: Record); |
7304 | checkClassLevelCodeSegAttribute(Class: Record); |
7305 | |
7306 | bool ClangABICompat4 = |
7307 | Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; |
7308 | TargetInfo::CallingConvKind CCK = |
7309 | Context.getTargetInfo().getCallingConvKind(ClangABICompat4); |
7310 | bool CanPass = canPassInRegisters(S&: *this, D: Record, CCK); |
7311 | |
7312 | // Do not change ArgPassingRestrictions if it has already been set to |
7313 | // RecordArgPassingKind::CanNeverPassInRegs. |
7314 | if (Record->getArgPassingRestrictions() != |
7315 | RecordArgPassingKind::CanNeverPassInRegs) |
7316 | Record->setArgPassingRestrictions( |
7317 | CanPass ? RecordArgPassingKind::CanPassInRegs |
7318 | : RecordArgPassingKind::CannotPassInRegs); |
7319 | |
7320 | // If canPassInRegisters returns true despite the record having a non-trivial |
7321 | // destructor, the record is destructed in the callee. This happens only when |
7322 | // the record or one of its subobjects has a field annotated with trivial_abi |
7323 | // or a field qualified with ObjC __strong/__weak. |
7324 | if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) |
7325 | Record->setParamDestroyedInCallee(true); |
7326 | else if (Record->hasNonTrivialDestructor()) |
7327 | Record->setParamDestroyedInCallee(CanPass); |
7328 | |
7329 | if (getLangOpts().ForceEmitVTables) { |
7330 | // If we want to emit all the vtables, we need to mark it as used. This |
7331 | // is especially required for cases like vtable assumption loads. |
7332 | MarkVTableUsed(Loc: Record->getInnerLocStart(), Class: Record); |
7333 | } |
7334 | |
7335 | if (getLangOpts().CUDA) { |
7336 | if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) |
7337 | checkCUDADeviceBuiltinSurfaceClassTemplate(S&: *this, Class: Record); |
7338 | else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) |
7339 | checkCUDADeviceBuiltinTextureClassTemplate(S&: *this, Class: Record); |
7340 | } |
7341 | } |
7342 | |
7343 | /// Look up the special member function that would be called by a special |
7344 | /// member function for a subobject of class type. |
7345 | /// |
7346 | /// \param Class The class type of the subobject. |
7347 | /// \param CSM The kind of special member function. |
7348 | /// \param FieldQuals If the subobject is a field, its cv-qualifiers. |
7349 | /// \param ConstRHS True if this is a copy operation with a const object |
7350 | /// on its RHS, that is, if the argument to the outer special member |
7351 | /// function is 'const' and this is not a field marked 'mutable'. |
7352 | static Sema::SpecialMemberOverloadResult |
7353 | lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class, |
7354 | CXXSpecialMemberKind CSM, unsigned FieldQuals, |
7355 | bool ConstRHS) { |
7356 | unsigned LHSQuals = 0; |
7357 | if (CSM == CXXSpecialMemberKind::CopyAssignment || |
7358 | CSM == CXXSpecialMemberKind::MoveAssignment) |
7359 | LHSQuals = FieldQuals; |
7360 | |
7361 | unsigned RHSQuals = FieldQuals; |
7362 | if (CSM == CXXSpecialMemberKind::DefaultConstructor || |
7363 | CSM == CXXSpecialMemberKind::Destructor) |
7364 | RHSQuals = 0; |
7365 | else if (ConstRHS) |
7366 | RHSQuals |= Qualifiers::Const; |
7367 | |
7368 | return S.LookupSpecialMember(D: Class, SM: CSM, |
7369 | ConstArg: RHSQuals & Qualifiers::Const, |
7370 | VolatileArg: RHSQuals & Qualifiers::Volatile, |
7371 | RValueThis: false, |
7372 | ConstThis: LHSQuals & Qualifiers::Const, |
7373 | VolatileThis: LHSQuals & Qualifiers::Volatile); |
7374 | } |
7375 | |
7376 | class Sema::InheritedConstructorInfo { |
7377 | Sema &S; |
7378 | SourceLocation UseLoc; |
7379 | |
7380 | /// A mapping from the base classes through which the constructor was |
7381 | /// inherited to the using shadow declaration in that base class (or a null |
7382 | /// pointer if the constructor was declared in that base class). |
7383 | llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> |
7384 | InheritedFromBases; |
7385 | |
7386 | public: |
7387 | InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, |
7388 | ConstructorUsingShadowDecl *Shadow) |
7389 | : S(S), UseLoc(UseLoc) { |
7390 | bool DiagnosedMultipleConstructedBases = false; |
7391 | CXXRecordDecl *ConstructedBase = nullptr; |
7392 | BaseUsingDecl *ConstructedBaseIntroducer = nullptr; |
7393 | |
7394 | // Find the set of such base class subobjects and check that there's a |
7395 | // unique constructed subobject. |
7396 | for (auto *D : Shadow->redecls()) { |
7397 | auto *DShadow = cast<ConstructorUsingShadowDecl>(D); |
7398 | auto *DNominatedBase = DShadow->getNominatedBaseClass(); |
7399 | auto *DConstructedBase = DShadow->getConstructedBaseClass(); |
7400 | |
7401 | InheritedFromBases.insert( |
7402 | std::make_pair(DNominatedBase->getCanonicalDecl(), |
7403 | DShadow->getNominatedBaseClassShadowDecl())); |
7404 | if (DShadow->constructsVirtualBase()) |
7405 | InheritedFromBases.insert( |
7406 | std::make_pair(DConstructedBase->getCanonicalDecl(), |
7407 | DShadow->getConstructedBaseClassShadowDecl())); |
7408 | else |
7409 | assert(DNominatedBase == DConstructedBase); |
7410 | |
7411 | // [class.inhctor.init]p2: |
7412 | // If the constructor was inherited from multiple base class subobjects |
7413 | // of type B, the program is ill-formed. |
7414 | if (!ConstructedBase) { |
7415 | ConstructedBase = DConstructedBase; |
7416 | ConstructedBaseIntroducer = D->getIntroducer(); |
7417 | } else if (ConstructedBase != DConstructedBase && |
7418 | !Shadow->isInvalidDecl()) { |
7419 | if (!DiagnosedMultipleConstructedBases) { |
7420 | S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) |
7421 | << Shadow->getTargetDecl(); |
7422 | S.Diag(ConstructedBaseIntroducer->getLocation(), |
7423 | diag::note_ambiguous_inherited_constructor_using) |
7424 | << ConstructedBase; |
7425 | DiagnosedMultipleConstructedBases = true; |
7426 | } |
7427 | S.Diag(D->getIntroducer()->getLocation(), |
7428 | diag::note_ambiguous_inherited_constructor_using) |
7429 | << DConstructedBase; |
7430 | } |
7431 | } |
7432 | |
7433 | if (DiagnosedMultipleConstructedBases) |
7434 | Shadow->setInvalidDecl(); |
7435 | } |
7436 | |
7437 | /// Find the constructor to use for inherited construction of a base class, |
7438 | /// and whether that base class constructor inherits the constructor from a |
7439 | /// virtual base class (in which case it won't actually invoke it). |
7440 | std::pair<CXXConstructorDecl *, bool> |
7441 | findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { |
7442 | auto It = InheritedFromBases.find(Val: Base->getCanonicalDecl()); |
7443 | if (It == InheritedFromBases.end()) |
7444 | return std::make_pair(x: nullptr, y: false); |
7445 | |
7446 | // This is an intermediary class. |
7447 | if (It->second) |
7448 | return std::make_pair( |
7449 | x: S.findInheritingConstructor(Loc: UseLoc, BaseCtor: Ctor, DerivedShadow: It->second), |
7450 | y: It->second->constructsVirtualBase()); |
7451 | |
7452 | // This is the base class from which the constructor was inherited. |
7453 | return std::make_pair(x&: Ctor, y: false); |
7454 | } |
7455 | }; |
7456 | |
7457 | /// Is the special member function which would be selected to perform the |
7458 | /// specified operation on the specified class type a constexpr constructor? |
7459 | static bool specialMemberIsConstexpr( |
7460 | Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals, |
7461 | bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr, |
7462 | Sema::InheritedConstructorInfo *Inherited = nullptr) { |
7463 | // Suppress duplicate constraint checking here, in case a constraint check |
7464 | // caused us to decide to do this. Any truely recursive checks will get |
7465 | // caught during these checks anyway. |
7466 | Sema::SatisfactionStackResetRAII SSRAII{S}; |
7467 | |
7468 | // If we're inheriting a constructor, see if we need to call it for this base |
7469 | // class. |
7470 | if (InheritedCtor) { |
7471 | assert(CSM == CXXSpecialMemberKind::DefaultConstructor); |
7472 | auto BaseCtor = |
7473 | Inherited->findConstructorForBase(Base: ClassDecl, Ctor: InheritedCtor).first; |
7474 | if (BaseCtor) |
7475 | return BaseCtor->isConstexpr(); |
7476 | } |
7477 | |
7478 | if (CSM == CXXSpecialMemberKind::DefaultConstructor) |
7479 | return ClassDecl->hasConstexprDefaultConstructor(); |
7480 | if (CSM == CXXSpecialMemberKind::Destructor) |
7481 | return ClassDecl->hasConstexprDestructor(); |
7482 | |
7483 | Sema::SpecialMemberOverloadResult SMOR = |
7484 | lookupCallFromSpecialMember(S, Class: ClassDecl, CSM, FieldQuals: Quals, ConstRHS); |
7485 | if (!SMOR.getMethod()) |
7486 | // A constructor we wouldn't select can't be "involved in initializing" |
7487 | // anything. |
7488 | return true; |
7489 | return SMOR.getMethod()->isConstexpr(); |
7490 | } |
7491 | |
7492 | /// Determine whether the specified special member function would be constexpr |
7493 | /// if it were implicitly defined. |
7494 | static bool defaultedSpecialMemberIsConstexpr( |
7495 | Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg, |
7496 | CXXConstructorDecl *InheritedCtor = nullptr, |
7497 | Sema::InheritedConstructorInfo *Inherited = nullptr) { |
7498 | if (!S.getLangOpts().CPlusPlus11) |
7499 | return false; |
7500 | |
7501 | // C++11 [dcl.constexpr]p4: |
7502 | // In the definition of a constexpr constructor [...] |
7503 | bool Ctor = true; |
7504 | switch (CSM) { |
7505 | case CXXSpecialMemberKind::DefaultConstructor: |
7506 | if (Inherited) |
7507 | break; |
7508 | // Since default constructor lookup is essentially trivial (and cannot |
7509 | // involve, for instance, template instantiation), we compute whether a |
7510 | // defaulted default constructor is constexpr directly within CXXRecordDecl. |
7511 | // |
7512 | // This is important for performance; we need to know whether the default |
7513 | // constructor is constexpr to determine whether the type is a literal type. |
7514 | return ClassDecl->defaultedDefaultConstructorIsConstexpr(); |
7515 | |
7516 | case CXXSpecialMemberKind::CopyConstructor: |
7517 | case CXXSpecialMemberKind::MoveConstructor: |
7518 | // For copy or move constructors, we need to perform overload resolution. |
7519 | break; |
7520 | |
7521 | case CXXSpecialMemberKind::CopyAssignment: |
7522 | case CXXSpecialMemberKind::MoveAssignment: |
7523 | if (!S.getLangOpts().CPlusPlus14) |
7524 | return false; |
7525 | // In C++1y, we need to perform overload resolution. |
7526 | Ctor = false; |
7527 | break; |
7528 | |
7529 | case CXXSpecialMemberKind::Destructor: |
7530 | return ClassDecl->defaultedDestructorIsConstexpr(); |
7531 | |
7532 | case CXXSpecialMemberKind::Invalid: |
7533 | return false; |
7534 | } |
7535 | |
7536 | // -- if the class is a non-empty union, or for each non-empty anonymous |
7537 | // union member of a non-union class, exactly one non-static data member |
7538 | // shall be initialized; [DR1359] |
7539 | // |
7540 | // If we squint, this is guaranteed, since exactly one non-static data member |
7541 | // will be initialized (if the constructor isn't deleted), we just don't know |
7542 | // which one. |
7543 | if (Ctor && ClassDecl->isUnion()) |
7544 | return CSM == CXXSpecialMemberKind::DefaultConstructor |
7545 | ? ClassDecl->hasInClassInitializer() || |
7546 | !ClassDecl->hasVariantMembers() |
7547 | : true; |
7548 | |
7549 | // -- the class shall not have any virtual base classes; |
7550 | if (Ctor && ClassDecl->getNumVBases()) |
7551 | return false; |
7552 | |
7553 | // C++1y [class.copy]p26: |
7554 | // -- [the class] is a literal type, and |
7555 | if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23) |
7556 | return false; |
7557 | |
7558 | // -- every constructor involved in initializing [...] base class |
7559 | // sub-objects shall be a constexpr constructor; |
7560 | // -- the assignment operator selected to copy/move each direct base |
7561 | // class is a constexpr function, and |
7562 | if (!S.getLangOpts().CPlusPlus23) { |
7563 | for (const auto &B : ClassDecl->bases()) { |
7564 | const RecordType *BaseType = B.getType()->getAs<RecordType>(); |
7565 | if (!BaseType) |
7566 | continue; |
7567 | CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(Val: BaseType->getDecl()); |
7568 | if (!specialMemberIsConstexpr(S, ClassDecl: BaseClassDecl, CSM, Quals: 0, ConstRHS: ConstArg, |
7569 | InheritedCtor, Inherited)) |
7570 | return false; |
7571 | } |
7572 | } |
7573 | |
7574 | // -- every constructor involved in initializing non-static data members |
7575 | // [...] shall be a constexpr constructor; |
7576 | // -- every non-static data member and base class sub-object shall be |
7577 | // initialized |
7578 | // -- for each non-static data member of X that is of class type (or array |
7579 | // thereof), the assignment operator selected to copy/move that member is |
7580 | // a constexpr function |
7581 | if (!S.getLangOpts().CPlusPlus23) { |
7582 | for (const auto *F : ClassDecl->fields()) { |
7583 | if (F->isInvalidDecl()) |
7584 | continue; |
7585 | if (CSM == CXXSpecialMemberKind::DefaultConstructor && |
7586 | F->hasInClassInitializer()) |
7587 | continue; |
7588 | QualType BaseType = S.Context.getBaseElementType(F->getType()); |
7589 | if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { |
7590 | CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); |
7591 | if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, |
7592 | BaseType.getCVRQualifiers(), |
7593 | ConstArg && !F->isMutable())) |
7594 | return false; |
7595 | } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) { |
7596 | return false; |
7597 | } |
7598 | } |
7599 | } |
7600 | |
7601 | // All OK, it's constexpr! |
7602 | return true; |
7603 | } |
7604 | |
7605 | namespace { |
7606 | /// RAII object to register a defaulted function as having its exception |
7607 | /// specification computed. |
7608 | struct ComputingExceptionSpec { |
7609 | Sema &S; |
7610 | |
7611 | ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) |
7612 | : S(S) { |
7613 | Sema::CodeSynthesisContext Ctx; |
7614 | Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; |
7615 | Ctx.PointOfInstantiation = Loc; |
7616 | Ctx.Entity = FD; |
7617 | S.pushCodeSynthesisContext(Ctx); |
7618 | } |
7619 | ~ComputingExceptionSpec() { |
7620 | S.popCodeSynthesisContext(); |
7621 | } |
7622 | }; |
7623 | } |
7624 | |
7625 | static Sema::ImplicitExceptionSpecification |
7626 | ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc, |
7627 | CXXMethodDecl *MD, |
7628 | CXXSpecialMemberKind CSM, |
7629 | Sema::InheritedConstructorInfo *ICI); |
7630 | |
7631 | static Sema::ImplicitExceptionSpecification |
7632 | ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, |
7633 | FunctionDecl *FD, |
7634 | Sema::DefaultedComparisonKind DCK); |
7635 | |
7636 | static Sema::ImplicitExceptionSpecification |
7637 | computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { |
7638 | auto DFK = S.getDefaultedFunctionKind(FD); |
7639 | if (DFK.isSpecialMember()) |
7640 | return ComputeDefaultedSpecialMemberExceptionSpec( |
7641 | S, Loc, MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(), ICI: nullptr); |
7642 | if (DFK.isComparison()) |
7643 | return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, |
7644 | DCK: DFK.asComparison()); |
7645 | |
7646 | auto *CD = cast<CXXConstructorDecl>(Val: FD); |
7647 | assert(CD->getInheritedConstructor() && |
7648 | "only defaulted functions and inherited constructors have implicit " |
7649 | "exception specs" ); |
7650 | Sema::InheritedConstructorInfo ICI( |
7651 | S, Loc, CD->getInheritedConstructor().getShadowDecl()); |
7652 | return ComputeDefaultedSpecialMemberExceptionSpec( |
7653 | S, Loc, CD, CXXSpecialMemberKind::DefaultConstructor, &ICI); |
7654 | } |
7655 | |
7656 | static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, |
7657 | CXXMethodDecl *MD) { |
7658 | FunctionProtoType::ExtProtoInfo EPI; |
7659 | |
7660 | // Build an exception specification pointing back at this member. |
7661 | EPI.ExceptionSpec.Type = EST_Unevaluated; |
7662 | EPI.ExceptionSpec.SourceDecl = MD; |
7663 | |
7664 | // Set the calling convention to the default for C++ instance methods. |
7665 | EPI.ExtInfo = EPI.ExtInfo.withCallingConv( |
7666 | cc: S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, |
7667 | /*IsCXXMethod=*/true)); |
7668 | return EPI; |
7669 | } |
7670 | |
7671 | void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { |
7672 | const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); |
7673 | if (FPT->getExceptionSpecType() != EST_Unevaluated) |
7674 | return; |
7675 | |
7676 | // Evaluate the exception specification. |
7677 | auto IES = computeImplicitExceptionSpec(S&: *this, Loc, FD); |
7678 | auto ESI = IES.getExceptionSpec(); |
7679 | |
7680 | // Update the type of the special member to use it. |
7681 | UpdateExceptionSpec(FD, ESI); |
7682 | } |
7683 | |
7684 | void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { |
7685 | assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted" ); |
7686 | |
7687 | DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); |
7688 | if (!DefKind) { |
7689 | assert(FD->getDeclContext()->isDependentContext()); |
7690 | return; |
7691 | } |
7692 | |
7693 | if (DefKind.isComparison()) |
7694 | UnusedPrivateFields.clear(); |
7695 | |
7696 | if (DefKind.isSpecialMember() |
7697 | ? CheckExplicitlyDefaultedSpecialMember(MD: cast<CXXMethodDecl>(Val: FD), |
7698 | CSM: DefKind.asSpecialMember(), |
7699 | DefaultLoc: FD->getDefaultLoc()) |
7700 | : CheckExplicitlyDefaultedComparison(S, MD: FD, DCK: DefKind.asComparison())) |
7701 | FD->setInvalidDecl(); |
7702 | } |
7703 | |
7704 | bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, |
7705 | CXXSpecialMemberKind CSM, |
7706 | SourceLocation DefaultLoc) { |
7707 | CXXRecordDecl *RD = MD->getParent(); |
7708 | |
7709 | assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid && |
7710 | "not an explicitly-defaulted special member" ); |
7711 | |
7712 | // Defer all checking for special members of a dependent type. |
7713 | if (RD->isDependentType()) |
7714 | return false; |
7715 | |
7716 | // Whether this was the first-declared instance of the constructor. |
7717 | // This affects whether we implicitly add an exception spec and constexpr. |
7718 | bool First = MD == MD->getCanonicalDecl(); |
7719 | |
7720 | bool HadError = false; |
7721 | |
7722 | // C++11 [dcl.fct.def.default]p1: |
7723 | // A function that is explicitly defaulted shall |
7724 | // -- be a special member function [...] (checked elsewhere), |
7725 | // -- have the same type (except for ref-qualifiers, and except that a |
7726 | // copy operation can take a non-const reference) as an implicit |
7727 | // declaration, and |
7728 | // -- not have default arguments. |
7729 | // C++2a changes the second bullet to instead delete the function if it's |
7730 | // defaulted on its first declaration, unless it's "an assignment operator, |
7731 | // and its return type differs or its parameter type is not a reference". |
7732 | bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; |
7733 | bool ShouldDeleteForTypeMismatch = false; |
7734 | unsigned ExpectedParams = 1; |
7735 | if (CSM == CXXSpecialMemberKind::DefaultConstructor || |
7736 | CSM == CXXSpecialMemberKind::Destructor) |
7737 | ExpectedParams = 0; |
7738 | if (MD->getNumExplicitParams() != ExpectedParams) { |
7739 | // This checks for default arguments: a copy or move constructor with a |
7740 | // default argument is classified as a default constructor, and assignment |
7741 | // operations and destructors can't have default arguments. |
7742 | Diag(MD->getLocation(), diag::err_defaulted_special_member_params) |
7743 | << llvm::to_underlying(CSM) << MD->getSourceRange(); |
7744 | HadError = true; |
7745 | } else if (MD->isVariadic()) { |
7746 | if (DeleteOnTypeMismatch) |
7747 | ShouldDeleteForTypeMismatch = true; |
7748 | else { |
7749 | Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) |
7750 | << llvm::to_underlying(CSM) << MD->getSourceRange(); |
7751 | HadError = true; |
7752 | } |
7753 | } |
7754 | |
7755 | const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>(); |
7756 | |
7757 | bool CanHaveConstParam = false; |
7758 | if (CSM == CXXSpecialMemberKind::CopyConstructor) |
7759 | CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); |
7760 | else if (CSM == CXXSpecialMemberKind::CopyAssignment) |
7761 | CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); |
7762 | |
7763 | QualType ReturnType = Context.VoidTy; |
7764 | if (CSM == CXXSpecialMemberKind::CopyAssignment || |
7765 | CSM == CXXSpecialMemberKind::MoveAssignment) { |
7766 | // Check for return type matching. |
7767 | ReturnType = Type->getReturnType(); |
7768 | QualType ThisType = MD->getFunctionObjectParameterType(); |
7769 | |
7770 | QualType DeclType = Context.getTypeDeclType(RD); |
7771 | DeclType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr, |
7772 | NamedType: DeclType, OwnedTagDecl: nullptr); |
7773 | DeclType = Context.getAddrSpaceQualType( |
7774 | T: DeclType, AddressSpace: ThisType.getQualifiers().getAddressSpace()); |
7775 | QualType ExpectedReturnType = Context.getLValueReferenceType(T: DeclType); |
7776 | |
7777 | if (!Context.hasSameType(T1: ReturnType, T2: ExpectedReturnType)) { |
7778 | Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) |
7779 | << (CSM == CXXSpecialMemberKind::MoveAssignment) |
7780 | << ExpectedReturnType; |
7781 | HadError = true; |
7782 | } |
7783 | |
7784 | // A defaulted special member cannot have cv-qualifiers. |
7785 | if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) { |
7786 | if (DeleteOnTypeMismatch) |
7787 | ShouldDeleteForTypeMismatch = true; |
7788 | else { |
7789 | Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) |
7790 | << (CSM == CXXSpecialMemberKind::MoveAssignment) |
7791 | << getLangOpts().CPlusPlus14; |
7792 | HadError = true; |
7793 | } |
7794 | } |
7795 | // [C++23][dcl.fct.def.default]/p2.2 |
7796 | // if F2 has an implicit object parameter of type “reference to C”, |
7797 | // F1 may be an explicit object member function whose explicit object |
7798 | // parameter is of (possibly different) type “reference to C”, |
7799 | // in which case the type of F1 would differ from the type of F2 |
7800 | // in that the type of F1 has an additional parameter; |
7801 | if (!Context.hasSameType( |
7802 | T1: ThisType.getNonReferenceType().getUnqualifiedType(), |
7803 | T2: Context.getRecordType(RD))) { |
7804 | if (DeleteOnTypeMismatch) |
7805 | ShouldDeleteForTypeMismatch = true; |
7806 | else { |
7807 | Diag(MD->getLocation(), |
7808 | diag::err_defaulted_special_member_explicit_object_mismatch) |
7809 | << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD |
7810 | << MD->getSourceRange(); |
7811 | HadError = true; |
7812 | } |
7813 | } |
7814 | } |
7815 | |
7816 | // Check for parameter type matching. |
7817 | QualType ArgType = |
7818 | ExpectedParams |
7819 | ? Type->getParamType(i: MD->isExplicitObjectMemberFunction() ? 1 : 0) |
7820 | : QualType(); |
7821 | bool HasConstParam = false; |
7822 | if (ExpectedParams && ArgType->isReferenceType()) { |
7823 | // Argument must be reference to possibly-const T. |
7824 | QualType ReferentType = ArgType->getPointeeType(); |
7825 | HasConstParam = ReferentType.isConstQualified(); |
7826 | |
7827 | if (ReferentType.isVolatileQualified()) { |
7828 | if (DeleteOnTypeMismatch) |
7829 | ShouldDeleteForTypeMismatch = true; |
7830 | else { |
7831 | Diag(MD->getLocation(), |
7832 | diag::err_defaulted_special_member_volatile_param) |
7833 | << llvm::to_underlying(CSM); |
7834 | HadError = true; |
7835 | } |
7836 | } |
7837 | |
7838 | if (HasConstParam && !CanHaveConstParam) { |
7839 | if (DeleteOnTypeMismatch) |
7840 | ShouldDeleteForTypeMismatch = true; |
7841 | else if (CSM == CXXSpecialMemberKind::CopyConstructor || |
7842 | CSM == CXXSpecialMemberKind::CopyAssignment) { |
7843 | Diag(MD->getLocation(), |
7844 | diag::err_defaulted_special_member_copy_const_param) |
7845 | << (CSM == CXXSpecialMemberKind::CopyAssignment); |
7846 | // FIXME: Explain why this special member can't be const. |
7847 | HadError = true; |
7848 | } else { |
7849 | Diag(MD->getLocation(), |
7850 | diag::err_defaulted_special_member_move_const_param) |
7851 | << (CSM == CXXSpecialMemberKind::MoveAssignment); |
7852 | HadError = true; |
7853 | } |
7854 | } |
7855 | } else if (ExpectedParams) { |
7856 | // A copy assignment operator can take its argument by value, but a |
7857 | // defaulted one cannot. |
7858 | assert(CSM == CXXSpecialMemberKind::CopyAssignment && |
7859 | "unexpected non-ref argument" ); |
7860 | Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); |
7861 | HadError = true; |
7862 | } |
7863 | |
7864 | // C++11 [dcl.fct.def.default]p2: |
7865 | // An explicitly-defaulted function may be declared constexpr only if it |
7866 | // would have been implicitly declared as constexpr, |
7867 | // Do not apply this rule to members of class templates, since core issue 1358 |
7868 | // makes such functions always instantiate to constexpr functions. For |
7869 | // functions which cannot be constexpr (for non-constructors in C++11 and for |
7870 | // destructors in C++14 and C++17), this is checked elsewhere. |
7871 | // |
7872 | // FIXME: This should not apply if the member is deleted. |
7873 | bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl: RD, CSM, |
7874 | ConstArg: HasConstParam); |
7875 | |
7876 | // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358): |
7877 | // If the instantiated template specialization of a constexpr function |
7878 | // template or member function of a class template would fail to satisfy |
7879 | // the requirements for a constexpr function or constexpr constructor, that |
7880 | // specialization is still a constexpr function or constexpr constructor, |
7881 | // even though a call to such a function cannot appear in a constant |
7882 | // expression. |
7883 | if (MD->isTemplateInstantiation() && MD->isConstexpr()) |
7884 | Constexpr = true; |
7885 | |
7886 | if ((getLangOpts().CPlusPlus20 || |
7887 | (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(Val: MD) |
7888 | : isa<CXXConstructorDecl>(Val: MD))) && |
7889 | MD->isConstexpr() && !Constexpr && |
7890 | MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { |
7891 | if (!MD->isConsteval() && RD->getNumVBases()) { |
7892 | Diag(MD->getBeginLoc(), |
7893 | diag::err_incorrect_defaulted_constexpr_with_vb) |
7894 | << llvm::to_underlying(CSM); |
7895 | for (const auto &I : RD->vbases()) |
7896 | Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here); |
7897 | } else { |
7898 | Diag(MD->getBeginLoc(), diag::err_incorrect_defaulted_constexpr) |
7899 | << llvm::to_underlying(CSM) << MD->isConsteval(); |
7900 | } |
7901 | HadError = true; |
7902 | // FIXME: Explain why the special member can't be constexpr. |
7903 | } |
7904 | |
7905 | if (First) { |
7906 | // C++2a [dcl.fct.def.default]p3: |
7907 | // If a function is explicitly defaulted on its first declaration, it is |
7908 | // implicitly considered to be constexpr if the implicit declaration |
7909 | // would be. |
7910 | MD->setConstexprKind(Constexpr ? (MD->isConsteval() |
7911 | ? ConstexprSpecKind::Consteval |
7912 | : ConstexprSpecKind::Constexpr) |
7913 | : ConstexprSpecKind::Unspecified); |
7914 | |
7915 | if (!Type->hasExceptionSpec()) { |
7916 | // C++2a [except.spec]p3: |
7917 | // If a declaration of a function does not have a noexcept-specifier |
7918 | // [and] is defaulted on its first declaration, [...] the exception |
7919 | // specification is as specified below |
7920 | FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); |
7921 | EPI.ExceptionSpec.Type = EST_Unevaluated; |
7922 | EPI.ExceptionSpec.SourceDecl = MD; |
7923 | MD->setType( |
7924 | Context.getFunctionType(ResultTy: ReturnType, Args: Type->getParamTypes(), EPI)); |
7925 | } |
7926 | } |
7927 | |
7928 | if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { |
7929 | if (First) { |
7930 | SetDeclDeleted(dcl: MD, DelLoc: MD->getLocation()); |
7931 | if (!inTemplateInstantiation() && !HadError) { |
7932 | Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) |
7933 | << llvm::to_underlying(CSM); |
7934 | if (ShouldDeleteForTypeMismatch) { |
7935 | Diag(MD->getLocation(), diag::note_deleted_type_mismatch) |
7936 | << llvm::to_underlying(CSM); |
7937 | } else if (ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr, |
7938 | /*Diagnose*/ true) && |
7939 | DefaultLoc.isValid()) { |
7940 | Diag(DefaultLoc, diag::note_replace_equals_default_to_delete) |
7941 | << FixItHint::CreateReplacement(DefaultLoc, "delete" ); |
7942 | } |
7943 | } |
7944 | if (ShouldDeleteForTypeMismatch && !HadError) { |
7945 | Diag(MD->getLocation(), |
7946 | diag::warn_cxx17_compat_defaulted_method_type_mismatch) |
7947 | << llvm::to_underlying(CSM); |
7948 | } |
7949 | } else { |
7950 | // C++11 [dcl.fct.def.default]p4: |
7951 | // [For a] user-provided explicitly-defaulted function [...] if such a |
7952 | // function is implicitly defined as deleted, the program is ill-formed. |
7953 | Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) |
7954 | << llvm::to_underlying(CSM); |
7955 | assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl" ); |
7956 | ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr, /*Diagnose*/true); |
7957 | HadError = true; |
7958 | } |
7959 | } |
7960 | |
7961 | return HadError; |
7962 | } |
7963 | |
7964 | namespace { |
7965 | /// Helper class for building and checking a defaulted comparison. |
7966 | /// |
7967 | /// Defaulted functions are built in two phases: |
7968 | /// |
7969 | /// * First, the set of operations that the function will perform are |
7970 | /// identified, and some of them are checked. If any of the checked |
7971 | /// operations is invalid in certain ways, the comparison function is |
7972 | /// defined as deleted and no body is built. |
7973 | /// * Then, if the function is not defined as deleted, the body is built. |
7974 | /// |
7975 | /// This is accomplished by performing two visitation steps over the eventual |
7976 | /// body of the function. |
7977 | template<typename Derived, typename ResultList, typename Result, |
7978 | typename Subobject> |
7979 | class DefaultedComparisonVisitor { |
7980 | public: |
7981 | using DefaultedComparisonKind = Sema::DefaultedComparisonKind; |
7982 | |
7983 | DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, |
7984 | DefaultedComparisonKind DCK) |
7985 | : S(S), RD(RD), FD(FD), DCK(DCK) { |
7986 | if (auto *Info = FD->getDefalutedOrDeletedInfo()) { |
7987 | // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an |
7988 | // UnresolvedSet to avoid this copy. |
7989 | Fns.assign(I: Info->getUnqualifiedLookups().begin(), |
7990 | E: Info->getUnqualifiedLookups().end()); |
7991 | } |
7992 | } |
7993 | |
7994 | ResultList visit() { |
7995 | // The type of an lvalue naming a parameter of this function. |
7996 | QualType ParamLvalType = |
7997 | FD->getParamDecl(i: 0)->getType().getNonReferenceType(); |
7998 | |
7999 | ResultList Results; |
8000 | |
8001 | switch (DCK) { |
8002 | case DefaultedComparisonKind::None: |
8003 | llvm_unreachable("not a defaulted comparison" ); |
8004 | |
8005 | case DefaultedComparisonKind::Equal: |
8006 | case DefaultedComparisonKind::ThreeWay: |
8007 | getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); |
8008 | return Results; |
8009 | |
8010 | case DefaultedComparisonKind::NotEqual: |
8011 | case DefaultedComparisonKind::Relational: |
8012 | Results.add(getDerived().visitExpandedSubobject( |
8013 | ParamLvalType, getDerived().getCompleteObject())); |
8014 | return Results; |
8015 | } |
8016 | llvm_unreachable("" ); |
8017 | } |
8018 | |
8019 | protected: |
8020 | Derived &getDerived() { return static_cast<Derived&>(*this); } |
8021 | |
8022 | /// Visit the expanded list of subobjects of the given type, as specified in |
8023 | /// C++2a [class.compare.default]. |
8024 | /// |
8025 | /// \return \c true if the ResultList object said we're done, \c false if not. |
8026 | bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, |
8027 | Qualifiers Quals) { |
8028 | // C++2a [class.compare.default]p4: |
8029 | // The direct base class subobjects of C |
8030 | for (CXXBaseSpecifier &Base : Record->bases()) |
8031 | if (Results.add(getDerived().visitSubobject( |
8032 | S.Context.getQualifiedType(T: Base.getType(), Qs: Quals), |
8033 | getDerived().getBase(&Base)))) |
8034 | return true; |
8035 | |
8036 | // followed by the non-static data members of C |
8037 | for (FieldDecl *Field : Record->fields()) { |
8038 | // C++23 [class.bit]p2: |
8039 | // Unnamed bit-fields are not members ... |
8040 | if (Field->isUnnamedBitField()) |
8041 | continue; |
8042 | // Recursively expand anonymous structs. |
8043 | if (Field->isAnonymousStructOrUnion()) { |
8044 | if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), |
8045 | Quals)) |
8046 | return true; |
8047 | continue; |
8048 | } |
8049 | |
8050 | // Figure out the type of an lvalue denoting this field. |
8051 | Qualifiers FieldQuals = Quals; |
8052 | if (Field->isMutable()) |
8053 | FieldQuals.removeConst(); |
8054 | QualType FieldType = |
8055 | S.Context.getQualifiedType(Field->getType(), FieldQuals); |
8056 | |
8057 | if (Results.add(getDerived().visitSubobject( |
8058 | FieldType, getDerived().getField(Field)))) |
8059 | return true; |
8060 | } |
8061 | |
8062 | // form a list of subobjects. |
8063 | return false; |
8064 | } |
8065 | |
8066 | Result visitSubobject(QualType Type, Subobject Subobj) { |
8067 | // In that list, any subobject of array type is recursively expanded |
8068 | const ArrayType *AT = S.Context.getAsArrayType(T: Type); |
8069 | if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(Val: AT)) |
8070 | return getDerived().visitSubobjectArray(CAT->getElementType(), |
8071 | CAT->getSize(), Subobj); |
8072 | return getDerived().visitExpandedSubobject(Type, Subobj); |
8073 | } |
8074 | |
8075 | Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, |
8076 | Subobject Subobj) { |
8077 | return getDerived().visitSubobject(Type, Subobj); |
8078 | } |
8079 | |
8080 | protected: |
8081 | Sema &S; |
8082 | CXXRecordDecl *RD; |
8083 | FunctionDecl *FD; |
8084 | DefaultedComparisonKind DCK; |
8085 | UnresolvedSet<16> Fns; |
8086 | }; |
8087 | |
8088 | /// Information about a defaulted comparison, as determined by |
8089 | /// DefaultedComparisonAnalyzer. |
8090 | struct DefaultedComparisonInfo { |
8091 | bool Deleted = false; |
8092 | bool Constexpr = true; |
8093 | ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; |
8094 | |
8095 | static DefaultedComparisonInfo deleted() { |
8096 | DefaultedComparisonInfo Deleted; |
8097 | Deleted.Deleted = true; |
8098 | return Deleted; |
8099 | } |
8100 | |
8101 | bool add(const DefaultedComparisonInfo &R) { |
8102 | Deleted |= R.Deleted; |
8103 | Constexpr &= R.Constexpr; |
8104 | Category = commonComparisonType(A: Category, B: R.Category); |
8105 | return Deleted; |
8106 | } |
8107 | }; |
8108 | |
8109 | /// An element in the expanded list of subobjects of a defaulted comparison, as |
8110 | /// specified in C++2a [class.compare.default]p4. |
8111 | struct DefaultedComparisonSubobject { |
8112 | enum { CompleteObject, Member, Base } Kind; |
8113 | NamedDecl *Decl; |
8114 | SourceLocation Loc; |
8115 | }; |
8116 | |
8117 | /// A visitor over the notional body of a defaulted comparison that determines |
8118 | /// whether that body would be deleted or constexpr. |
8119 | class DefaultedComparisonAnalyzer |
8120 | : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, |
8121 | DefaultedComparisonInfo, |
8122 | DefaultedComparisonInfo, |
8123 | DefaultedComparisonSubobject> { |
8124 | public: |
8125 | enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; |
8126 | |
8127 | private: |
8128 | DiagnosticKind Diagnose; |
8129 | |
8130 | public: |
8131 | using Base = DefaultedComparisonVisitor; |
8132 | using Result = DefaultedComparisonInfo; |
8133 | using Subobject = DefaultedComparisonSubobject; |
8134 | |
8135 | friend Base; |
8136 | |
8137 | DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, |
8138 | DefaultedComparisonKind DCK, |
8139 | DiagnosticKind Diagnose = NoDiagnostics) |
8140 | : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} |
8141 | |
8142 | Result visit() { |
8143 | if ((DCK == DefaultedComparisonKind::Equal || |
8144 | DCK == DefaultedComparisonKind::ThreeWay) && |
8145 | RD->hasVariantMembers()) { |
8146 | // C++2a [class.compare.default]p2 [P2002R0]: |
8147 | // A defaulted comparison operator function for class C is defined as |
8148 | // deleted if [...] C has variant members. |
8149 | if (Diagnose == ExplainDeleted) { |
8150 | S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) |
8151 | << FD << RD->isUnion() << RD; |
8152 | } |
8153 | return Result::deleted(); |
8154 | } |
8155 | |
8156 | return Base::visit(); |
8157 | } |
8158 | |
8159 | private: |
8160 | Subobject getCompleteObject() { |
8161 | return Subobject{Subobject::CompleteObject, RD, FD->getLocation()}; |
8162 | } |
8163 | |
8164 | Subobject getBase(CXXBaseSpecifier *Base) { |
8165 | return Subobject{.Kind: Subobject::Base, Base->getType()->getAsCXXRecordDecl(), |
8166 | .Loc: Base->getBaseTypeLoc()}; |
8167 | } |
8168 | |
8169 | Subobject getField(FieldDecl *Field) { |
8170 | return Subobject{Subobject::Member, Field, Field->getLocation()}; |
8171 | } |
8172 | |
8173 | Result visitExpandedSubobject(QualType Type, Subobject Subobj) { |
8174 | // C++2a [class.compare.default]p2 [P2002R0]: |
8175 | // A defaulted <=> or == operator function for class C is defined as |
8176 | // deleted if any non-static data member of C is of reference type |
8177 | if (Type->isReferenceType()) { |
8178 | if (Diagnose == ExplainDeleted) { |
8179 | S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) |
8180 | << FD << RD; |
8181 | } |
8182 | return Result::deleted(); |
8183 | } |
8184 | |
8185 | // [...] Let xi be an lvalue denoting the ith element [...] |
8186 | OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); |
8187 | Expr *Args[] = {&Xi, &Xi}; |
8188 | |
8189 | // All operators start by trying to apply that same operator recursively. |
8190 | OverloadedOperatorKind OO = FD->getOverloadedOperator(); |
8191 | assert(OO != OO_None && "not an overloaded operator!" ); |
8192 | return visitBinaryOperator(OO, Args, Subobj); |
8193 | } |
8194 | |
8195 | Result |
8196 | visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, |
8197 | Subobject Subobj, |
8198 | OverloadCandidateSet *SpaceshipCandidates = nullptr) { |
8199 | // Note that there is no need to consider rewritten candidates here if |
8200 | // we've already found there is no viable 'operator<=>' candidate (and are |
8201 | // considering synthesizing a '<=>' from '==' and '<'). |
8202 | OverloadCandidateSet CandidateSet( |
8203 | FD->getLocation(), OverloadCandidateSet::CSK_Operator, |
8204 | OverloadCandidateSet::OperatorRewriteInfo( |
8205 | OO, FD->getLocation(), |
8206 | /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); |
8207 | |
8208 | /// C++2a [class.compare.default]p1 [P2002R0]: |
8209 | /// [...] the defaulted function itself is never a candidate for overload |
8210 | /// resolution [...] |
8211 | CandidateSet.exclude(FD); |
8212 | |
8213 | if (Args[0]->getType()->isOverloadableType()) |
8214 | S.LookupOverloadedBinOp(CandidateSet, Op: OO, Fns, Args); |
8215 | else |
8216 | // FIXME: We determine whether this is a valid expression by checking to |
8217 | // see if there's a viable builtin operator candidate for it. That isn't |
8218 | // really what the rules ask us to do, but should give the right results. |
8219 | S.AddBuiltinOperatorCandidates(Op: OO, OpLoc: FD->getLocation(), Args, CandidateSet); |
8220 | |
8221 | Result R; |
8222 | |
8223 | OverloadCandidateSet::iterator Best; |
8224 | switch (CandidateSet.BestViableFunction(S, Loc: FD->getLocation(), Best)) { |
8225 | case OR_Success: { |
8226 | // C++2a [class.compare.secondary]p2 [P2002R0]: |
8227 | // The operator function [...] is defined as deleted if [...] the |
8228 | // candidate selected by overload resolution is not a rewritten |
8229 | // candidate. |
8230 | if ((DCK == DefaultedComparisonKind::NotEqual || |
8231 | DCK == DefaultedComparisonKind::Relational) && |
8232 | !Best->RewriteKind) { |
8233 | if (Diagnose == ExplainDeleted) { |
8234 | if (Best->Function) { |
8235 | S.Diag(Best->Function->getLocation(), |
8236 | diag::note_defaulted_comparison_not_rewritten_callee) |
8237 | << FD; |
8238 | } else { |
8239 | assert(Best->Conversions.size() == 2 && |
8240 | Best->Conversions[0].isUserDefined() && |
8241 | "non-user-defined conversion from class to built-in " |
8242 | "comparison" ); |
8243 | S.Diag(Best->Conversions[0] |
8244 | .UserDefined.FoundConversionFunction.getDecl() |
8245 | ->getLocation(), |
8246 | diag::note_defaulted_comparison_not_rewritten_conversion) |
8247 | << FD; |
8248 | } |
8249 | } |
8250 | return Result::deleted(); |
8251 | } |
8252 | |
8253 | // Throughout C++2a [class.compare]: if overload resolution does not |
8254 | // result in a usable function, the candidate function is defined as |
8255 | // deleted. This requires that we selected an accessible function. |
8256 | // |
8257 | // Note that this only considers the access of the function when named |
8258 | // within the type of the subobject, and not the access path for any |
8259 | // derived-to-base conversion. |
8260 | CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); |
8261 | if (ArgClass && Best->FoundDecl.getDecl() && |
8262 | Best->FoundDecl.getDecl()->isCXXClassMember()) { |
8263 | QualType ObjectType = Subobj.Kind == Subobject::Member |
8264 | ? Args[0]->getType() |
8265 | : S.Context.getRecordType(RD); |
8266 | if (!S.isMemberAccessibleForDeletion( |
8267 | ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, |
8268 | Diagnose == ExplainDeleted |
8269 | ? S.PDiag(diag::note_defaulted_comparison_inaccessible) |
8270 | << FD << Subobj.Kind << Subobj.Decl |
8271 | : S.PDiag())) |
8272 | return Result::deleted(); |
8273 | } |
8274 | |
8275 | bool NeedsDeducing = |
8276 | OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType(); |
8277 | |
8278 | if (FunctionDecl *BestFD = Best->Function) { |
8279 | // C++2a [class.compare.default]p3 [P2002R0]: |
8280 | // A defaulted comparison function is constexpr-compatible if |
8281 | // [...] no overlod resolution performed [...] results in a |
8282 | // non-constexpr function. |
8283 | assert(!BestFD->isDeleted() && "wrong overload resolution result" ); |
8284 | // If it's not constexpr, explain why not. |
8285 | if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { |
8286 | if (Subobj.Kind != Subobject::CompleteObject) |
8287 | S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) |
8288 | << Subobj.Kind << Subobj.Decl; |
8289 | S.Diag(BestFD->getLocation(), |
8290 | diag::note_defaulted_comparison_not_constexpr_here); |
8291 | // Bail out after explaining; we don't want any more notes. |
8292 | return Result::deleted(); |
8293 | } |
8294 | R.Constexpr &= BestFD->isConstexpr(); |
8295 | |
8296 | if (NeedsDeducing) { |
8297 | // If any callee has an undeduced return type, deduce it now. |
8298 | // FIXME: It's not clear how a failure here should be handled. For |
8299 | // now, we produce an eager diagnostic, because that is forward |
8300 | // compatible with most (all?) other reasonable options. |
8301 | if (BestFD->getReturnType()->isUndeducedType() && |
8302 | S.DeduceReturnType(FD: BestFD, Loc: FD->getLocation(), |
8303 | /*Diagnose=*/false)) { |
8304 | // Don't produce a duplicate error when asked to explain why the |
8305 | // comparison is deleted: we diagnosed that when initially checking |
8306 | // the defaulted operator. |
8307 | if (Diagnose == NoDiagnostics) { |
8308 | S.Diag( |
8309 | FD->getLocation(), |
8310 | diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) |
8311 | << Subobj.Kind << Subobj.Decl; |
8312 | S.Diag( |
8313 | Subobj.Loc, |
8314 | diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) |
8315 | << Subobj.Kind << Subobj.Decl; |
8316 | S.Diag(BestFD->getLocation(), |
8317 | diag::note_defaulted_comparison_cannot_deduce_callee) |
8318 | << Subobj.Kind << Subobj.Decl; |
8319 | } |
8320 | return Result::deleted(); |
8321 | } |
8322 | auto *Info = S.Context.CompCategories.lookupInfoForType( |
8323 | Ty: BestFD->getCallResultType()); |
8324 | if (!Info) { |
8325 | if (Diagnose == ExplainDeleted) { |
8326 | S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) |
8327 | << Subobj.Kind << Subobj.Decl |
8328 | << BestFD->getCallResultType().withoutLocalFastQualifiers(); |
8329 | S.Diag(BestFD->getLocation(), |
8330 | diag::note_defaulted_comparison_cannot_deduce_callee) |
8331 | << Subobj.Kind << Subobj.Decl; |
8332 | } |
8333 | return Result::deleted(); |
8334 | } |
8335 | R.Category = Info->Kind; |
8336 | } |
8337 | } else { |
8338 | QualType T = Best->BuiltinParamTypes[0]; |
8339 | assert(T == Best->BuiltinParamTypes[1] && |
8340 | "builtin comparison for different types?" ); |
8341 | assert(Best->BuiltinParamTypes[2].isNull() && |
8342 | "invalid builtin comparison" ); |
8343 | |
8344 | if (NeedsDeducing) { |
8345 | std::optional<ComparisonCategoryType> Cat = |
8346 | getComparisonCategoryForBuiltinCmp(T); |
8347 | assert(Cat && "no category for builtin comparison?" ); |
8348 | R.Category = *Cat; |
8349 | } |
8350 | } |
8351 | |
8352 | // Note that we might be rewriting to a different operator. That call is |
8353 | // not considered until we come to actually build the comparison function. |
8354 | break; |
8355 | } |
8356 | |
8357 | case OR_Ambiguous: |
8358 | if (Diagnose == ExplainDeleted) { |
8359 | unsigned Kind = 0; |
8360 | if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) |
8361 | Kind = OO == OO_EqualEqual ? 1 : 2; |
8362 | CandidateSet.NoteCandidates( |
8363 | PartialDiagnosticAt( |
8364 | Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) |
8365 | << FD << Kind << Subobj.Kind << Subobj.Decl), |
8366 | S, OCD_AmbiguousCandidates, Args); |
8367 | } |
8368 | R = Result::deleted(); |
8369 | break; |
8370 | |
8371 | case OR_Deleted: |
8372 | if (Diagnose == ExplainDeleted) { |
8373 | if ((DCK == DefaultedComparisonKind::NotEqual || |
8374 | DCK == DefaultedComparisonKind::Relational) && |
8375 | !Best->RewriteKind) { |
8376 | S.Diag(Best->Function->getLocation(), |
8377 | diag::note_defaulted_comparison_not_rewritten_callee) |
8378 | << FD; |
8379 | } else { |
8380 | S.Diag(Subobj.Loc, |
8381 | diag::note_defaulted_comparison_calls_deleted) |
8382 | << FD << Subobj.Kind << Subobj.Decl; |
8383 | S.NoteDeletedFunction(FD: Best->Function); |
8384 | } |
8385 | } |
8386 | R = Result::deleted(); |
8387 | break; |
8388 | |
8389 | case OR_No_Viable_Function: |
8390 | // If there's no usable candidate, we're done unless we can rewrite a |
8391 | // '<=>' in terms of '==' and '<'. |
8392 | if (OO == OO_Spaceship && |
8393 | S.Context.CompCategories.lookupInfoForType(Ty: FD->getReturnType())) { |
8394 | // For any kind of comparison category return type, we need a usable |
8395 | // '==' and a usable '<'. |
8396 | if (!R.add(R: visitBinaryOperator(OO: OO_EqualEqual, Args, Subobj, |
8397 | SpaceshipCandidates: &CandidateSet))) |
8398 | R.add(R: visitBinaryOperator(OO: OO_Less, Args, Subobj, SpaceshipCandidates: &CandidateSet)); |
8399 | break; |
8400 | } |
8401 | |
8402 | if (Diagnose == ExplainDeleted) { |
8403 | S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) |
8404 | << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual) |
8405 | << Subobj.Kind << Subobj.Decl; |
8406 | |
8407 | // For a three-way comparison, list both the candidates for the |
8408 | // original operator and the candidates for the synthesized operator. |
8409 | if (SpaceshipCandidates) { |
8410 | SpaceshipCandidates->NoteCandidates( |
8411 | S, Args, |
8412 | SpaceshipCandidates->CompleteCandidates(S, OCD: OCD_AllCandidates, |
8413 | Args, OpLoc: FD->getLocation())); |
8414 | S.Diag(Subobj.Loc, |
8415 | diag::note_defaulted_comparison_no_viable_function_synthesized) |
8416 | << (OO == OO_EqualEqual ? 0 : 1); |
8417 | } |
8418 | |
8419 | CandidateSet.NoteCandidates( |
8420 | S, Args, |
8421 | CandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args, |
8422 | OpLoc: FD->getLocation())); |
8423 | } |
8424 | R = Result::deleted(); |
8425 | break; |
8426 | } |
8427 | |
8428 | return R; |
8429 | } |
8430 | }; |
8431 | |
8432 | /// A list of statements. |
8433 | struct StmtListResult { |
8434 | bool IsInvalid = false; |
8435 | llvm::SmallVector<Stmt*, 16> Stmts; |
8436 | |
8437 | bool add(const StmtResult &S) { |
8438 | IsInvalid |= S.isInvalid(); |
8439 | if (IsInvalid) |
8440 | return true; |
8441 | Stmts.push_back(Elt: S.get()); |
8442 | return false; |
8443 | } |
8444 | }; |
8445 | |
8446 | /// A visitor over the notional body of a defaulted comparison that synthesizes |
8447 | /// the actual body. |
8448 | class DefaultedComparisonSynthesizer |
8449 | : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, |
8450 | StmtListResult, StmtResult, |
8451 | std::pair<ExprResult, ExprResult>> { |
8452 | SourceLocation Loc; |
8453 | unsigned ArrayDepth = 0; |
8454 | |
8455 | public: |
8456 | using Base = DefaultedComparisonVisitor; |
8457 | using ExprPair = std::pair<ExprResult, ExprResult>; |
8458 | |
8459 | friend Base; |
8460 | |
8461 | DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, |
8462 | DefaultedComparisonKind DCK, |
8463 | SourceLocation BodyLoc) |
8464 | : Base(S, RD, FD, DCK), Loc(BodyLoc) {} |
8465 | |
8466 | /// Build a suitable function body for this defaulted comparison operator. |
8467 | StmtResult build() { |
8468 | Sema::CompoundScopeRAII CompoundScope(S); |
8469 | |
8470 | StmtListResult Stmts = visit(); |
8471 | if (Stmts.IsInvalid) |
8472 | return StmtError(); |
8473 | |
8474 | ExprResult RetVal; |
8475 | switch (DCK) { |
8476 | case DefaultedComparisonKind::None: |
8477 | llvm_unreachable("not a defaulted comparison" ); |
8478 | |
8479 | case DefaultedComparisonKind::Equal: { |
8480 | // C++2a [class.eq]p3: |
8481 | // [...] compar[e] the corresponding elements [...] until the first |
8482 | // index i where xi == yi yields [...] false. If no such index exists, |
8483 | // V is true. Otherwise, V is false. |
8484 | // |
8485 | // Join the comparisons with '&&'s and return the result. Use a right |
8486 | // fold (traversing the conditions right-to-left), because that |
8487 | // short-circuits more naturally. |
8488 | auto OldStmts = std::move(Stmts.Stmts); |
8489 | Stmts.Stmts.clear(); |
8490 | ExprResult CmpSoFar; |
8491 | // Finish a particular comparison chain. |
8492 | auto FinishCmp = [&] { |
8493 | if (Expr *Prior = CmpSoFar.get()) { |
8494 | // Convert the last expression to 'return ...;' |
8495 | if (RetVal.isUnset() && Stmts.Stmts.empty()) |
8496 | RetVal = CmpSoFar; |
8497 | // Convert any prior comparison to 'if (!(...)) return false;' |
8498 | else if (Stmts.add(S: buildIfNotCondReturnFalse(Cond: Prior))) |
8499 | return true; |
8500 | CmpSoFar = ExprResult(); |
8501 | } |
8502 | return false; |
8503 | }; |
8504 | for (Stmt *EAsStmt : llvm::reverse(C&: OldStmts)) { |
8505 | Expr *E = dyn_cast<Expr>(Val: EAsStmt); |
8506 | if (!E) { |
8507 | // Found an array comparison. |
8508 | if (FinishCmp() || Stmts.add(S: EAsStmt)) |
8509 | return StmtError(); |
8510 | continue; |
8511 | } |
8512 | |
8513 | if (CmpSoFar.isUnset()) { |
8514 | CmpSoFar = E; |
8515 | continue; |
8516 | } |
8517 | CmpSoFar = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_LAnd, LHSExpr: E, RHSExpr: CmpSoFar.get()); |
8518 | if (CmpSoFar.isInvalid()) |
8519 | return StmtError(); |
8520 | } |
8521 | if (FinishCmp()) |
8522 | return StmtError(); |
8523 | std::reverse(first: Stmts.Stmts.begin(), last: Stmts.Stmts.end()); |
8524 | // If no such index exists, V is true. |
8525 | if (RetVal.isUnset()) |
8526 | RetVal = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_true); |
8527 | break; |
8528 | } |
8529 | |
8530 | case DefaultedComparisonKind::ThreeWay: { |
8531 | // Per C++2a [class.spaceship]p3, as a fallback add: |
8532 | // return static_cast<R>(std::strong_ordering::equal); |
8533 | QualType StrongOrdering = S.CheckComparisonCategoryType( |
8534 | Kind: ComparisonCategoryType::StrongOrdering, Loc, |
8535 | Usage: Sema::ComparisonCategoryUsage::DefaultedOperator); |
8536 | if (StrongOrdering.isNull()) |
8537 | return StmtError(); |
8538 | VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(Ty: StrongOrdering) |
8539 | .getValueInfo(ValueKind: ComparisonCategoryResult::Equal) |
8540 | ->VD; |
8541 | RetVal = getDecl(EqualVD); |
8542 | if (RetVal.isInvalid()) |
8543 | return StmtError(); |
8544 | RetVal = buildStaticCastToR(E: RetVal.get()); |
8545 | break; |
8546 | } |
8547 | |
8548 | case DefaultedComparisonKind::NotEqual: |
8549 | case DefaultedComparisonKind::Relational: |
8550 | RetVal = cast<Expr>(Val: Stmts.Stmts.pop_back_val()); |
8551 | break; |
8552 | } |
8553 | |
8554 | // Build the final return statement. |
8555 | if (RetVal.isInvalid()) |
8556 | return StmtError(); |
8557 | StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: RetVal.get()); |
8558 | if (ReturnStmt.isInvalid()) |
8559 | return StmtError(); |
8560 | Stmts.Stmts.push_back(Elt: ReturnStmt.get()); |
8561 | |
8562 | return S.ActOnCompoundStmt(L: Loc, R: Loc, Elts: Stmts.Stmts, /*IsStmtExpr=*/isStmtExpr: false); |
8563 | } |
8564 | |
8565 | private: |
8566 | ExprResult getDecl(ValueDecl *VD) { |
8567 | return S.BuildDeclarationNameExpr( |
8568 | CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); |
8569 | } |
8570 | |
8571 | ExprResult getParam(unsigned I) { |
8572 | ParmVarDecl *PD = FD->getParamDecl(i: I); |
8573 | return getDecl(PD); |
8574 | } |
8575 | |
8576 | ExprPair getCompleteObject() { |
8577 | unsigned Param = 0; |
8578 | ExprResult LHS; |
8579 | if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD); |
8580 | MD && MD->isImplicitObjectMemberFunction()) { |
8581 | // LHS is '*this'. |
8582 | LHS = S.ActOnCXXThis(Loc); |
8583 | if (!LHS.isInvalid()) |
8584 | LHS = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: LHS.get()); |
8585 | } else { |
8586 | LHS = getParam(I: Param++); |
8587 | } |
8588 | ExprResult RHS = getParam(I: Param++); |
8589 | assert(Param == FD->getNumParams()); |
8590 | return {LHS, RHS}; |
8591 | } |
8592 | |
8593 | ExprPair getBase(CXXBaseSpecifier *Base) { |
8594 | ExprPair Obj = getCompleteObject(); |
8595 | if (Obj.first.isInvalid() || Obj.second.isInvalid()) |
8596 | return {ExprError(), ExprError()}; |
8597 | CXXCastPath Path = {Base}; |
8598 | return {S.ImpCastExprToType(E: Obj.first.get(), Type: Base->getType(), |
8599 | CK: CK_DerivedToBase, VK: VK_LValue, BasePath: &Path), |
8600 | S.ImpCastExprToType(E: Obj.second.get(), Type: Base->getType(), |
8601 | CK: CK_DerivedToBase, VK: VK_LValue, BasePath: &Path)}; |
8602 | } |
8603 | |
8604 | ExprPair getField(FieldDecl *Field) { |
8605 | ExprPair Obj = getCompleteObject(); |
8606 | if (Obj.first.isInvalid() || Obj.second.isInvalid()) |
8607 | return {ExprError(), ExprError()}; |
8608 | |
8609 | DeclAccessPair Found = DeclAccessPair::make(D: Field, AS: Field->getAccess()); |
8610 | DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); |
8611 | return {S.BuildFieldReferenceExpr(BaseExpr: Obj.first.get(), /*IsArrow=*/false, OpLoc: Loc, |
8612 | SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo), |
8613 | S.BuildFieldReferenceExpr(BaseExpr: Obj.second.get(), /*IsArrow=*/false, OpLoc: Loc, |
8614 | SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo)}; |
8615 | } |
8616 | |
8617 | // FIXME: When expanding a subobject, register a note in the code synthesis |
8618 | // stack to say which subobject we're comparing. |
8619 | |
8620 | StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { |
8621 | if (Cond.isInvalid()) |
8622 | return StmtError(); |
8623 | |
8624 | ExprResult NotCond = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_LNot, InputExpr: Cond.get()); |
8625 | if (NotCond.isInvalid()) |
8626 | return StmtError(); |
8627 | |
8628 | ExprResult False = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_false); |
8629 | assert(!False.isInvalid() && "should never fail" ); |
8630 | StmtResult ReturnFalse = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: False.get()); |
8631 | if (ReturnFalse.isInvalid()) |
8632 | return StmtError(); |
8633 | |
8634 | return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt: nullptr, |
8635 | Cond: S.ActOnCondition(S: nullptr, Loc, SubExpr: NotCond.get(), |
8636 | CK: Sema::ConditionKind::Boolean), |
8637 | RParenLoc: Loc, ThenVal: ReturnFalse.get(), ElseLoc: SourceLocation(), ElseVal: nullptr); |
8638 | } |
8639 | |
8640 | StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, |
8641 | ExprPair Subobj) { |
8642 | QualType SizeType = S.Context.getSizeType(); |
8643 | Size = Size.zextOrTrunc(width: S.Context.getTypeSize(T: SizeType)); |
8644 | |
8645 | // Build 'size_t i$n = 0'. |
8646 | IdentifierInfo *IterationVarName = nullptr; |
8647 | { |
8648 | SmallString<8> Str; |
8649 | llvm::raw_svector_ostream OS(Str); |
8650 | OS << "i" << ArrayDepth; |
8651 | IterationVarName = &S.Context.Idents.get(Name: OS.str()); |
8652 | } |
8653 | VarDecl *IterationVar = VarDecl::Create( |
8654 | C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: IterationVarName, T: SizeType, |
8655 | TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc), S: SC_None); |
8656 | llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0); |
8657 | IterationVar->setInit( |
8658 | IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc)); |
8659 | Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); |
8660 | |
8661 | auto IterRef = [&] { |
8662 | ExprResult Ref = S.BuildDeclarationNameExpr( |
8663 | CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), |
8664 | IterationVar); |
8665 | assert(!Ref.isInvalid() && "can't reference our own variable?" ); |
8666 | return Ref.get(); |
8667 | }; |
8668 | |
8669 | // Build 'i$n != Size'. |
8670 | ExprResult Cond = S.CreateBuiltinBinOp( |
8671 | OpLoc: Loc, Opc: BO_NE, LHSExpr: IterRef(), |
8672 | RHSExpr: IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc)); |
8673 | assert(!Cond.isInvalid() && "should never fail" ); |
8674 | |
8675 | // Build '++i$n'. |
8676 | ExprResult Inc = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_PreInc, InputExpr: IterRef()); |
8677 | assert(!Inc.isInvalid() && "should never fail" ); |
8678 | |
8679 | // Build 'a[i$n]' and 'b[i$n]'. |
8680 | auto Index = [&](ExprResult E) { |
8681 | if (E.isInvalid()) |
8682 | return ExprError(); |
8683 | return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); |
8684 | }; |
8685 | Subobj.first = Index(Subobj.first); |
8686 | Subobj.second = Index(Subobj.second); |
8687 | |
8688 | // Compare the array elements. |
8689 | ++ArrayDepth; |
8690 | StmtResult Substmt = visitSubobject(Type, Subobj); |
8691 | --ArrayDepth; |
8692 | |
8693 | if (Substmt.isInvalid()) |
8694 | return StmtError(); |
8695 | |
8696 | // For the inner level of an 'operator==', build 'if (!cmp) return false;'. |
8697 | // For outer levels or for an 'operator<=>' we already have a suitable |
8698 | // statement that returns as necessary. |
8699 | if (Expr *ElemCmp = dyn_cast<Expr>(Val: Substmt.get())) { |
8700 | assert(DCK == DefaultedComparisonKind::Equal && |
8701 | "should have non-expression statement" ); |
8702 | Substmt = buildIfNotCondReturnFalse(Cond: ElemCmp); |
8703 | if (Substmt.isInvalid()) |
8704 | return StmtError(); |
8705 | } |
8706 | |
8707 | // Build 'for (...) ...' |
8708 | return S.ActOnForStmt(ForLoc: Loc, LParenLoc: Loc, First: Init, |
8709 | Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Cond.get(), |
8710 | CK: Sema::ConditionKind::Boolean), |
8711 | Third: S.MakeFullDiscardedValueExpr(Arg: Inc.get()), RParenLoc: Loc, |
8712 | Body: Substmt.get()); |
8713 | } |
8714 | |
8715 | StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { |
8716 | if (Obj.first.isInvalid() || Obj.second.isInvalid()) |
8717 | return StmtError(); |
8718 | |
8719 | OverloadedOperatorKind OO = FD->getOverloadedOperator(); |
8720 | BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); |
8721 | ExprResult Op; |
8722 | if (Type->isOverloadableType()) |
8723 | Op = S.CreateOverloadedBinOp(OpLoc: Loc, Opc, Fns, LHS: Obj.first.get(), |
8724 | RHS: Obj.second.get(), /*PerformADL=*/RequiresADL: true, |
8725 | /*AllowRewrittenCandidates=*/true, DefaultedFn: FD); |
8726 | else |
8727 | Op = S.CreateBuiltinBinOp(OpLoc: Loc, Opc, LHSExpr: Obj.first.get(), RHSExpr: Obj.second.get()); |
8728 | if (Op.isInvalid()) |
8729 | return StmtError(); |
8730 | |
8731 | switch (DCK) { |
8732 | case DefaultedComparisonKind::None: |
8733 | llvm_unreachable("not a defaulted comparison" ); |
8734 | |
8735 | case DefaultedComparisonKind::Equal: |
8736 | // Per C++2a [class.eq]p2, each comparison is individually contextually |
8737 | // converted to bool. |
8738 | Op = S.PerformContextuallyConvertToBool(From: Op.get()); |
8739 | if (Op.isInvalid()) |
8740 | return StmtError(); |
8741 | return Op.get(); |
8742 | |
8743 | case DefaultedComparisonKind::ThreeWay: { |
8744 | // Per C++2a [class.spaceship]p3, form: |
8745 | // if (R cmp = static_cast<R>(op); cmp != 0) |
8746 | // return cmp; |
8747 | QualType R = FD->getReturnType(); |
8748 | Op = buildStaticCastToR(E: Op.get()); |
8749 | if (Op.isInvalid()) |
8750 | return StmtError(); |
8751 | |
8752 | // R cmp = ...; |
8753 | IdentifierInfo *Name = &S.Context.Idents.get(Name: "cmp" ); |
8754 | VarDecl *VD = |
8755 | VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: Name, T: R, |
8756 | TInfo: S.Context.getTrivialTypeSourceInfo(T: R, Loc), S: SC_None); |
8757 | S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); |
8758 | Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); |
8759 | |
8760 | // cmp != 0 |
8761 | ExprResult VDRef = getDecl(VD); |
8762 | if (VDRef.isInvalid()) |
8763 | return StmtError(); |
8764 | llvm::APInt ZeroVal(S.Context.getIntWidth(T: S.Context.IntTy), 0); |
8765 | Expr *Zero = |
8766 | IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); |
8767 | ExprResult Comp; |
8768 | if (VDRef.get()->getType()->isOverloadableType()) |
8769 | Comp = S.CreateOverloadedBinOp(OpLoc: Loc, Opc: BO_NE, Fns, LHS: VDRef.get(), RHS: Zero, RequiresADL: true, |
8770 | AllowRewrittenCandidates: true, DefaultedFn: FD); |
8771 | else |
8772 | Comp = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_NE, LHSExpr: VDRef.get(), RHSExpr: Zero); |
8773 | if (Comp.isInvalid()) |
8774 | return StmtError(); |
8775 | Sema::ConditionResult Cond = S.ActOnCondition( |
8776 | S: nullptr, Loc, SubExpr: Comp.get(), CK: Sema::ConditionKind::Boolean); |
8777 | if (Cond.isInvalid()) |
8778 | return StmtError(); |
8779 | |
8780 | // return cmp; |
8781 | VDRef = getDecl(VD); |
8782 | if (VDRef.isInvalid()) |
8783 | return StmtError(); |
8784 | StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: VDRef.get()); |
8785 | if (ReturnStmt.isInvalid()) |
8786 | return StmtError(); |
8787 | |
8788 | // if (...) |
8789 | return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt, Cond, |
8790 | RParenLoc: Loc, ThenVal: ReturnStmt.get(), |
8791 | /*ElseLoc=*/SourceLocation(), /*Else=*/ElseVal: nullptr); |
8792 | } |
8793 | |
8794 | case DefaultedComparisonKind::NotEqual: |
8795 | case DefaultedComparisonKind::Relational: |
8796 | // C++2a [class.compare.secondary]p2: |
8797 | // Otherwise, the operator function yields x @ y. |
8798 | return Op.get(); |
8799 | } |
8800 | llvm_unreachable("" ); |
8801 | } |
8802 | |
8803 | /// Build "static_cast<R>(E)". |
8804 | ExprResult buildStaticCastToR(Expr *E) { |
8805 | QualType R = FD->getReturnType(); |
8806 | assert(!R->isUndeducedType() && "type should have been deduced already" ); |
8807 | |
8808 | // Don't bother forming a no-op cast in the common case. |
8809 | if (E->isPRValue() && S.Context.hasSameType(T1: E->getType(), T2: R)) |
8810 | return E; |
8811 | return S.BuildCXXNamedCast(OpLoc: Loc, Kind: tok::kw_static_cast, |
8812 | Ty: S.Context.getTrivialTypeSourceInfo(T: R, Loc), E, |
8813 | AngleBrackets: SourceRange(Loc, Loc), Parens: SourceRange(Loc, Loc)); |
8814 | } |
8815 | }; |
8816 | } |
8817 | |
8818 | /// Perform the unqualified lookups that might be needed to form a defaulted |
8819 | /// comparison function for the given operator. |
8820 | static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, |
8821 | UnresolvedSetImpl &Operators, |
8822 | OverloadedOperatorKind Op) { |
8823 | auto Lookup = [&](OverloadedOperatorKind OO) { |
8824 | Self.LookupOverloadedOperatorName(Op: OO, S, Functions&: Operators); |
8825 | }; |
8826 | |
8827 | // Every defaulted operator looks up itself. |
8828 | Lookup(Op); |
8829 | // ... and the rewritten form of itself, if any. |
8830 | if (OverloadedOperatorKind = getRewrittenOverloadedOperator(Kind: Op)) |
8831 | Lookup(ExtraOp); |
8832 | |
8833 | // For 'operator<=>', we also form a 'cmp != 0' expression, and might |
8834 | // synthesize a three-way comparison from '<' and '=='. In a dependent |
8835 | // context, we also need to look up '==' in case we implicitly declare a |
8836 | // defaulted 'operator=='. |
8837 | if (Op == OO_Spaceship) { |
8838 | Lookup(OO_ExclaimEqual); |
8839 | Lookup(OO_Less); |
8840 | Lookup(OO_EqualEqual); |
8841 | } |
8842 | } |
8843 | |
8844 | bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, |
8845 | DefaultedComparisonKind DCK) { |
8846 | assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison" ); |
8847 | |
8848 | // Perform any unqualified lookups we're going to need to default this |
8849 | // function. |
8850 | if (S) { |
8851 | UnresolvedSet<32> Operators; |
8852 | lookupOperatorsForDefaultedComparison(Self&: *this, S, Operators, |
8853 | Op: FD->getOverloadedOperator()); |
8854 | FD->setDefaultedOrDeletedInfo( |
8855 | FunctionDecl::DefaultedOrDeletedFunctionInfo::Create( |
8856 | Context, Lookups: Operators.pairs())); |
8857 | } |
8858 | |
8859 | // C++2a [class.compare.default]p1: |
8860 | // A defaulted comparison operator function for some class C shall be a |
8861 | // non-template function declared in the member-specification of C that is |
8862 | // -- a non-static const non-volatile member of C having one parameter of |
8863 | // type const C& and either no ref-qualifier or the ref-qualifier &, or |
8864 | // -- a friend of C having two parameters of type const C& or two |
8865 | // parameters of type C. |
8866 | |
8867 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); |
8868 | bool IsMethod = isa<CXXMethodDecl>(Val: FD); |
8869 | if (IsMethod) { |
8870 | auto *MD = cast<CXXMethodDecl>(Val: FD); |
8871 | assert(!MD->isStatic() && "comparison function cannot be a static member" ); |
8872 | |
8873 | if (MD->getRefQualifier() == RQ_RValue) { |
8874 | Diag(MD->getLocation(), diag::err_ref_qualifier_comparison_operator); |
8875 | |
8876 | // Remove the ref qualifier to recover. |
8877 | const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); |
8878 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); |
8879 | EPI.RefQualifier = RQ_None; |
8880 | MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(), |
8881 | Args: FPT->getParamTypes(), EPI)); |
8882 | } |
8883 | |
8884 | // If we're out-of-class, this is the class we're comparing. |
8885 | if (!RD) |
8886 | RD = MD->getParent(); |
8887 | QualType T = MD->getFunctionObjectParameterType(); |
8888 | if (!T.isConstQualified()) { |
8889 | SourceLocation Loc, InsertLoc; |
8890 | if (MD->isExplicitObjectMemberFunction()) { |
8891 | Loc = MD->getParamDecl(0)->getBeginLoc(); |
8892 | InsertLoc = getLocForEndOfToken( |
8893 | Loc: MD->getParamDecl(0)->getExplicitObjectParamThisLoc()); |
8894 | } else { |
8895 | Loc = MD->getLocation(); |
8896 | if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) |
8897 | InsertLoc = Loc.getRParenLoc(); |
8898 | } |
8899 | // Don't diagnose an implicit 'operator=='; we will have diagnosed the |
8900 | // corresponding defaulted 'operator<=>' already. |
8901 | if (!MD->isImplicit()) { |
8902 | Diag(Loc, diag::err_defaulted_comparison_non_const) |
8903 | << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const" ); |
8904 | } |
8905 | |
8906 | // Add the 'const' to the type to recover. |
8907 | const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); |
8908 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); |
8909 | EPI.TypeQuals.addConst(); |
8910 | MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(), |
8911 | Args: FPT->getParamTypes(), EPI)); |
8912 | } |
8913 | |
8914 | if (MD->isVolatile()) { |
8915 | Diag(MD->getLocation(), diag::err_volatile_comparison_operator); |
8916 | |
8917 | // Remove the 'volatile' from the type to recover. |
8918 | const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); |
8919 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); |
8920 | EPI.TypeQuals.removeVolatile(); |
8921 | MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(), |
8922 | Args: FPT->getParamTypes(), EPI)); |
8923 | } |
8924 | } |
8925 | |
8926 | if ((FD->getNumParams() - |
8927 | (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) != |
8928 | (IsMethod ? 1 : 2)) { |
8929 | // Let's not worry about using a variadic template pack here -- who would do |
8930 | // such a thing? |
8931 | Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args) |
8932 | << int(IsMethod) << int(DCK); |
8933 | return true; |
8934 | } |
8935 | |
8936 | const ParmVarDecl *KnownParm = nullptr; |
8937 | for (const ParmVarDecl *Param : FD->parameters()) { |
8938 | if (Param->isExplicitObjectParameter()) |
8939 | continue; |
8940 | QualType ParmTy = Param->getType(); |
8941 | |
8942 | if (!KnownParm) { |
8943 | auto CTy = ParmTy; |
8944 | // Is it `T const &`? |
8945 | bool Ok = !IsMethod; |
8946 | QualType ExpectedTy; |
8947 | if (RD) |
8948 | ExpectedTy = Context.getRecordType(RD); |
8949 | if (auto *Ref = CTy->getAs<ReferenceType>()) { |
8950 | CTy = Ref->getPointeeType(); |
8951 | if (RD) |
8952 | ExpectedTy.addConst(); |
8953 | Ok = true; |
8954 | } |
8955 | |
8956 | // Is T a class? |
8957 | if (!Ok) { |
8958 | } else if (RD) { |
8959 | if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy)) |
8960 | Ok = false; |
8961 | } else if (auto *CRD = CTy->getAsRecordDecl()) { |
8962 | RD = cast<CXXRecordDecl>(CRD); |
8963 | } else { |
8964 | Ok = false; |
8965 | } |
8966 | |
8967 | if (Ok) { |
8968 | KnownParm = Param; |
8969 | } else { |
8970 | // Don't diagnose an implicit 'operator=='; we will have diagnosed the |
8971 | // corresponding defaulted 'operator<=>' already. |
8972 | if (!FD->isImplicit()) { |
8973 | if (RD) { |
8974 | QualType PlainTy = Context.getRecordType(RD); |
8975 | QualType RefTy = |
8976 | Context.getLValueReferenceType(T: PlainTy.withConst()); |
8977 | Diag(FD->getLocation(), diag::err_defaulted_comparison_param) |
8978 | << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy |
8979 | << Param->getSourceRange(); |
8980 | } else { |
8981 | assert(!IsMethod && "should know expected type for method" ); |
8982 | Diag(FD->getLocation(), |
8983 | diag::err_defaulted_comparison_param_unknown) |
8984 | << int(DCK) << ParmTy << Param->getSourceRange(); |
8985 | } |
8986 | } |
8987 | return true; |
8988 | } |
8989 | } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) { |
8990 | Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) |
8991 | << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange() |
8992 | << ParmTy << Param->getSourceRange(); |
8993 | return true; |
8994 | } |
8995 | } |
8996 | |
8997 | assert(RD && "must have determined class" ); |
8998 | if (IsMethod) { |
8999 | } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { |
9000 | // In-class, must be a friend decl. |
9001 | assert(FD->getFriendObjectKind() && "expected a friend declaration" ); |
9002 | } else { |
9003 | // Out of class, require the defaulted comparison to be a friend (of a |
9004 | // complete type). |
9005 | if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD), |
9006 | diag::err_defaulted_comparison_not_friend, int(DCK), |
9007 | int(1))) |
9008 | return true; |
9009 | |
9010 | if (llvm::none_of(Range: RD->friends(), P: [&](const FriendDecl *F) { |
9011 | return FD->getCanonicalDecl() == |
9012 | F->getFriendDecl()->getCanonicalDecl(); |
9013 | })) { |
9014 | Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend) |
9015 | << int(DCK) << int(0) << RD; |
9016 | Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at); |
9017 | return true; |
9018 | } |
9019 | } |
9020 | |
9021 | // C++2a [class.eq]p1, [class.rel]p1: |
9022 | // A [defaulted comparison other than <=>] shall have a declared return |
9023 | // type bool. |
9024 | if (DCK != DefaultedComparisonKind::ThreeWay && |
9025 | !FD->getDeclaredReturnType()->isDependentType() && |
9026 | !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { |
9027 | Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) |
9028 | << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy |
9029 | << FD->getReturnTypeSourceRange(); |
9030 | return true; |
9031 | } |
9032 | // C++2a [class.spaceship]p2 [P2002R0]: |
9033 | // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, |
9034 | // R shall not contain a placeholder type. |
9035 | if (QualType RT = FD->getDeclaredReturnType(); |
9036 | DCK == DefaultedComparisonKind::ThreeWay && |
9037 | RT->getContainedDeducedType() && |
9038 | (!Context.hasSameType(T1: RT, T2: Context.getAutoDeductType()) || |
9039 | RT->getContainedAutoType()->isConstrained())) { |
9040 | Diag(FD->getLocation(), |
9041 | diag::err_defaulted_comparison_deduced_return_type_not_auto) |
9042 | << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy |
9043 | << FD->getReturnTypeSourceRange(); |
9044 | return true; |
9045 | } |
9046 | |
9047 | // For a defaulted function in a dependent class, defer all remaining checks |
9048 | // until instantiation. |
9049 | if (RD->isDependentType()) |
9050 | return false; |
9051 | |
9052 | // Determine whether the function should be defined as deleted. |
9053 | DefaultedComparisonInfo Info = |
9054 | DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); |
9055 | |
9056 | bool First = FD == FD->getCanonicalDecl(); |
9057 | |
9058 | if (!First) { |
9059 | if (Info.Deleted) { |
9060 | // C++11 [dcl.fct.def.default]p4: |
9061 | // [For a] user-provided explicitly-defaulted function [...] if such a |
9062 | // function is implicitly defined as deleted, the program is ill-formed. |
9063 | // |
9064 | // This is really just a consequence of the general rule that you can |
9065 | // only delete a function on its first declaration. |
9066 | Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) |
9067 | << FD->isImplicit() << (int)DCK; |
9068 | DefaultedComparisonAnalyzer(*this, RD, FD, DCK, |
9069 | DefaultedComparisonAnalyzer::ExplainDeleted) |
9070 | .visit(); |
9071 | return true; |
9072 | } |
9073 | if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { |
9074 | // C++20 [class.compare.default]p1: |
9075 | // [...] A definition of a comparison operator as defaulted that appears |
9076 | // in a class shall be the first declaration of that function. |
9077 | Diag(FD->getLocation(), diag::err_non_first_default_compare_in_class) |
9078 | << (int)DCK; |
9079 | Diag(FD->getCanonicalDecl()->getLocation(), |
9080 | diag::note_previous_declaration); |
9081 | return true; |
9082 | } |
9083 | } |
9084 | |
9085 | // If we want to delete the function, then do so; there's nothing else to |
9086 | // check in that case. |
9087 | if (Info.Deleted) { |
9088 | SetDeclDeleted(dcl: FD, DelLoc: FD->getLocation()); |
9089 | if (!inTemplateInstantiation() && !FD->isImplicit()) { |
9090 | Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) |
9091 | << (int)DCK; |
9092 | DefaultedComparisonAnalyzer(*this, RD, FD, DCK, |
9093 | DefaultedComparisonAnalyzer::ExplainDeleted) |
9094 | .visit(); |
9095 | if (FD->getDefaultLoc().isValid()) |
9096 | Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete) |
9097 | << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete" ); |
9098 | } |
9099 | return false; |
9100 | } |
9101 | |
9102 | // C++2a [class.spaceship]p2: |
9103 | // The return type is deduced as the common comparison type of R0, R1, ... |
9104 | if (DCK == DefaultedComparisonKind::ThreeWay && |
9105 | FD->getDeclaredReturnType()->isUndeducedAutoType()) { |
9106 | SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); |
9107 | if (RetLoc.isInvalid()) |
9108 | RetLoc = FD->getBeginLoc(); |
9109 | // FIXME: Should we really care whether we have the complete type and the |
9110 | // 'enumerator' constants here? A forward declaration seems sufficient. |
9111 | QualType Cat = CheckComparisonCategoryType( |
9112 | Kind: Info.Category, Loc: RetLoc, Usage: ComparisonCategoryUsage::DefaultedOperator); |
9113 | if (Cat.isNull()) |
9114 | return true; |
9115 | Context.adjustDeducedFunctionResultType( |
9116 | FD, ResultType: SubstAutoType(TypeWithAuto: FD->getDeclaredReturnType(), Replacement: Cat)); |
9117 | } |
9118 | |
9119 | // C++2a [dcl.fct.def.default]p3 [P2002R0]: |
9120 | // An explicitly-defaulted function that is not defined as deleted may be |
9121 | // declared constexpr or consteval only if it is constexpr-compatible. |
9122 | // C++2a [class.compare.default]p3 [P2002R0]: |
9123 | // A defaulted comparison function is constexpr-compatible if it satisfies |
9124 | // the requirements for a constexpr function [...] |
9125 | // The only relevant requirements are that the parameter and return types are |
9126 | // literal types. The remaining conditions are checked by the analyzer. |
9127 | // |
9128 | // We support P2448R2 in language modes earlier than C++23 as an extension. |
9129 | // The concept of constexpr-compatible was removed. |
9130 | // C++23 [dcl.fct.def.default]p3 [P2448R2] |
9131 | // A function explicitly defaulted on its first declaration is implicitly |
9132 | // inline, and is implicitly constexpr if it is constexpr-suitable. |
9133 | // C++23 [dcl.constexpr]p3 |
9134 | // A function is constexpr-suitable if |
9135 | // - it is not a coroutine, and |
9136 | // - if the function is a constructor or destructor, its class does not |
9137 | // have any virtual base classes. |
9138 | if (FD->isConstexpr()) { |
9139 | if (!getLangOpts().CPlusPlus23 && |
9140 | CheckConstexprReturnType(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) && |
9141 | CheckConstexprParameterTypes(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) && |
9142 | !Info.Constexpr) { |
9143 | Diag(FD->getBeginLoc(), diag::err_defaulted_comparison_constexpr_mismatch) |
9144 | << FD->isImplicit() << (int)DCK << FD->isConsteval(); |
9145 | DefaultedComparisonAnalyzer(*this, RD, FD, DCK, |
9146 | DefaultedComparisonAnalyzer::ExplainConstexpr) |
9147 | .visit(); |
9148 | } |
9149 | } |
9150 | |
9151 | // C++2a [dcl.fct.def.default]p3 [P2002R0]: |
9152 | // If a constexpr-compatible function is explicitly defaulted on its first |
9153 | // declaration, it is implicitly considered to be constexpr. |
9154 | // FIXME: Only applying this to the first declaration seems problematic, as |
9155 | // simple reorderings can affect the meaning of the program. |
9156 | if (First && !FD->isConstexpr() && Info.Constexpr) |
9157 | FD->setConstexprKind(ConstexprSpecKind::Constexpr); |
9158 | |
9159 | // C++2a [except.spec]p3: |
9160 | // If a declaration of a function does not have a noexcept-specifier |
9161 | // [and] is defaulted on its first declaration, [...] the exception |
9162 | // specification is as specified below |
9163 | if (FD->getExceptionSpecType() == EST_None) { |
9164 | auto *FPT = FD->getType()->castAs<FunctionProtoType>(); |
9165 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); |
9166 | EPI.ExceptionSpec.Type = EST_Unevaluated; |
9167 | EPI.ExceptionSpec.SourceDecl = FD; |
9168 | FD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(), |
9169 | Args: FPT->getParamTypes(), EPI)); |
9170 | } |
9171 | |
9172 | return false; |
9173 | } |
9174 | |
9175 | void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, |
9176 | FunctionDecl *Spaceship) { |
9177 | Sema::CodeSynthesisContext Ctx; |
9178 | Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; |
9179 | Ctx.PointOfInstantiation = Spaceship->getEndLoc(); |
9180 | Ctx.Entity = Spaceship; |
9181 | pushCodeSynthesisContext(Ctx); |
9182 | |
9183 | if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) |
9184 | EqualEqual->setImplicit(); |
9185 | |
9186 | popCodeSynthesisContext(); |
9187 | } |
9188 | |
9189 | void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, |
9190 | DefaultedComparisonKind DCK) { |
9191 | assert(FD->isDefaulted() && !FD->isDeleted() && |
9192 | !FD->doesThisDeclarationHaveABody()); |
9193 | if (FD->willHaveBody() || FD->isInvalidDecl()) |
9194 | return; |
9195 | |
9196 | SynthesizedFunctionScope Scope(*this, FD); |
9197 | |
9198 | // Add a context note for diagnostics produced after this point. |
9199 | Scope.addContextNote(UseLoc); |
9200 | |
9201 | { |
9202 | // Build and set up the function body. |
9203 | // The first parameter has type maybe-ref-to maybe-const T, use that to get |
9204 | // the type of the class being compared. |
9205 | auto PT = FD->getParamDecl(i: 0)->getType(); |
9206 | CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl(); |
9207 | SourceLocation BodyLoc = |
9208 | FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); |
9209 | StmtResult Body = |
9210 | DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); |
9211 | if (Body.isInvalid()) { |
9212 | FD->setInvalidDecl(); |
9213 | return; |
9214 | } |
9215 | FD->setBody(Body.get()); |
9216 | FD->markUsed(Context); |
9217 | } |
9218 | |
9219 | // The exception specification is needed because we are defining the |
9220 | // function. Note that this will reuse the body we just built. |
9221 | ResolveExceptionSpec(Loc: UseLoc, FPT: FD->getType()->castAs<FunctionProtoType>()); |
9222 | |
9223 | if (ASTMutationListener *L = getASTMutationListener()) |
9224 | L->CompletedImplicitDefinition(D: FD); |
9225 | } |
9226 | |
9227 | static Sema::ImplicitExceptionSpecification |
9228 | ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, |
9229 | FunctionDecl *FD, |
9230 | Sema::DefaultedComparisonKind DCK) { |
9231 | ComputingExceptionSpec CES(S, FD, Loc); |
9232 | Sema::ImplicitExceptionSpecification ExceptSpec(S); |
9233 | |
9234 | if (FD->isInvalidDecl()) |
9235 | return ExceptSpec; |
9236 | |
9237 | // The common case is that we just defined the comparison function. In that |
9238 | // case, just look at whether the body can throw. |
9239 | if (FD->hasBody()) { |
9240 | ExceptSpec.CalledStmt(S: FD->getBody()); |
9241 | } else { |
9242 | // Otherwise, build a body so we can check it. This should ideally only |
9243 | // happen when we're not actually marking the function referenced. (This is |
9244 | // only really important for efficiency: we don't want to build and throw |
9245 | // away bodies for comparison functions more than we strictly need to.) |
9246 | |
9247 | // Pretend to synthesize the function body in an unevaluated context. |
9248 | // Note that we can't actually just go ahead and define the function here: |
9249 | // we are not permitted to mark its callees as referenced. |
9250 | Sema::SynthesizedFunctionScope Scope(S, FD); |
9251 | EnterExpressionEvaluationContext Context( |
9252 | S, Sema::ExpressionEvaluationContext::Unevaluated); |
9253 | |
9254 | CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); |
9255 | SourceLocation BodyLoc = |
9256 | FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); |
9257 | StmtResult Body = |
9258 | DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); |
9259 | if (!Body.isInvalid()) |
9260 | ExceptSpec.CalledStmt(S: Body.get()); |
9261 | |
9262 | // FIXME: Can we hold onto this body and just transform it to potentially |
9263 | // evaluated when we're asked to define the function rather than rebuilding |
9264 | // it? Either that, or we should only build the bits of the body that we |
9265 | // need (the expressions, not the statements). |
9266 | } |
9267 | |
9268 | return ExceptSpec; |
9269 | } |
9270 | |
9271 | void Sema::CheckDelayedMemberExceptionSpecs() { |
9272 | decltype(DelayedOverridingExceptionSpecChecks) Overriding; |
9273 | decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; |
9274 | |
9275 | std::swap(LHS&: Overriding, RHS&: DelayedOverridingExceptionSpecChecks); |
9276 | std::swap(LHS&: Equivalent, RHS&: DelayedEquivalentExceptionSpecChecks); |
9277 | |
9278 | // Perform any deferred checking of exception specifications for virtual |
9279 | // destructors. |
9280 | for (auto &Check : Overriding) |
9281 | CheckOverridingFunctionExceptionSpec(New: Check.first, Old: Check.second); |
9282 | |
9283 | // Perform any deferred checking of exception specifications for befriended |
9284 | // special members. |
9285 | for (auto &Check : Equivalent) |
9286 | CheckEquivalentExceptionSpec(Old: Check.second, New: Check.first); |
9287 | } |
9288 | |
9289 | namespace { |
9290 | /// CRTP base class for visiting operations performed by a special member |
9291 | /// function (or inherited constructor). |
9292 | template<typename Derived> |
9293 | struct SpecialMemberVisitor { |
9294 | Sema &S; |
9295 | CXXMethodDecl *MD; |
9296 | CXXSpecialMemberKind CSM; |
9297 | Sema::InheritedConstructorInfo *ICI; |
9298 | |
9299 | // Properties of the special member, computed for convenience. |
9300 | bool IsConstructor = false, IsAssignment = false, ConstArg = false; |
9301 | |
9302 | SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM, |
9303 | Sema::InheritedConstructorInfo *ICI) |
9304 | : S(S), MD(MD), CSM(CSM), ICI(ICI) { |
9305 | switch (CSM) { |
9306 | case CXXSpecialMemberKind::DefaultConstructor: |
9307 | case CXXSpecialMemberKind::CopyConstructor: |
9308 | case CXXSpecialMemberKind::MoveConstructor: |
9309 | IsConstructor = true; |
9310 | break; |
9311 | case CXXSpecialMemberKind::CopyAssignment: |
9312 | case CXXSpecialMemberKind::MoveAssignment: |
9313 | IsAssignment = true; |
9314 | break; |
9315 | case CXXSpecialMemberKind::Destructor: |
9316 | break; |
9317 | case CXXSpecialMemberKind::Invalid: |
9318 | llvm_unreachable("invalid special member kind" ); |
9319 | } |
9320 | |
9321 | if (MD->getNumExplicitParams()) { |
9322 | if (const ReferenceType *RT = |
9323 | MD->getNonObjectParameter(0)->getType()->getAs<ReferenceType>()) |
9324 | ConstArg = RT->getPointeeType().isConstQualified(); |
9325 | } |
9326 | } |
9327 | |
9328 | Derived &getDerived() { return static_cast<Derived&>(*this); } |
9329 | |
9330 | /// Is this a "move" special member? |
9331 | bool isMove() const { |
9332 | return CSM == CXXSpecialMemberKind::MoveConstructor || |
9333 | CSM == CXXSpecialMemberKind::MoveAssignment; |
9334 | } |
9335 | |
9336 | /// Look up the corresponding special member in the given class. |
9337 | Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, |
9338 | unsigned Quals, bool IsMutable) { |
9339 | return lookupCallFromSpecialMember(S, Class, CSM, FieldQuals: Quals, |
9340 | ConstRHS: ConstArg && !IsMutable); |
9341 | } |
9342 | |
9343 | /// Look up the constructor for the specified base class to see if it's |
9344 | /// overridden due to this being an inherited constructor. |
9345 | Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { |
9346 | if (!ICI) |
9347 | return {}; |
9348 | assert(CSM == CXXSpecialMemberKind::DefaultConstructor); |
9349 | auto *BaseCtor = |
9350 | cast<CXXConstructorDecl>(Val: MD)->getInheritedConstructor().getConstructor(); |
9351 | if (auto *MD = ICI->findConstructorForBase(Base: Class, Ctor: BaseCtor).first) |
9352 | return MD; |
9353 | return {}; |
9354 | } |
9355 | |
9356 | /// A base or member subobject. |
9357 | typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; |
9358 | |
9359 | /// Get the location to use for a subobject in diagnostics. |
9360 | static SourceLocation getSubobjectLoc(Subobject Subobj) { |
9361 | // FIXME: For an indirect virtual base, the direct base leading to |
9362 | // the indirect virtual base would be a more useful choice. |
9363 | if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) |
9364 | return B->getBaseTypeLoc(); |
9365 | else |
9366 | return Subobj.get<FieldDecl*>()->getLocation(); |
9367 | } |
9368 | |
9369 | enum BasesToVisit { |
9370 | /// Visit all non-virtual (direct) bases. |
9371 | VisitNonVirtualBases, |
9372 | /// Visit all direct bases, virtual or not. |
9373 | VisitDirectBases, |
9374 | /// Visit all non-virtual bases, and all virtual bases if the class |
9375 | /// is not abstract. |
9376 | VisitPotentiallyConstructedBases, |
9377 | /// Visit all direct or virtual bases. |
9378 | VisitAllBases |
9379 | }; |
9380 | |
9381 | // Visit the bases and members of the class. |
9382 | bool visit(BasesToVisit Bases) { |
9383 | CXXRecordDecl *RD = MD->getParent(); |
9384 | |
9385 | if (Bases == VisitPotentiallyConstructedBases) |
9386 | Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; |
9387 | |
9388 | for (auto &B : RD->bases()) |
9389 | if ((Bases == VisitDirectBases || !B.isVirtual()) && |
9390 | getDerived().visitBase(&B)) |
9391 | return true; |
9392 | |
9393 | if (Bases == VisitAllBases) |
9394 | for (auto &B : RD->vbases()) |
9395 | if (getDerived().visitBase(&B)) |
9396 | return true; |
9397 | |
9398 | for (auto *F : RD->fields()) |
9399 | if (!F->isInvalidDecl() && !F->isUnnamedBitField() && |
9400 | getDerived().visitField(F)) |
9401 | return true; |
9402 | |
9403 | return false; |
9404 | } |
9405 | }; |
9406 | } |
9407 | |
9408 | namespace { |
9409 | struct SpecialMemberDeletionInfo |
9410 | : SpecialMemberVisitor<SpecialMemberDeletionInfo> { |
9411 | bool Diagnose; |
9412 | |
9413 | SourceLocation Loc; |
9414 | |
9415 | bool AllFieldsAreConst; |
9416 | |
9417 | SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, |
9418 | CXXSpecialMemberKind CSM, |
9419 | Sema::InheritedConstructorInfo *ICI, bool Diagnose) |
9420 | : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), |
9421 | Loc(MD->getLocation()), AllFieldsAreConst(true) {} |
9422 | |
9423 | bool inUnion() const { return MD->getParent()->isUnion(); } |
9424 | |
9425 | CXXSpecialMemberKind getEffectiveCSM() { |
9426 | return ICI ? CXXSpecialMemberKind::Invalid : CSM; |
9427 | } |
9428 | |
9429 | bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); |
9430 | |
9431 | bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } |
9432 | bool visitField(FieldDecl *Field) { return shouldDeleteForField(FD: Field); } |
9433 | |
9434 | bool shouldDeleteForBase(CXXBaseSpecifier *Base); |
9435 | bool shouldDeleteForField(FieldDecl *FD); |
9436 | bool shouldDeleteForAllConstMembers(); |
9437 | |
9438 | bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, |
9439 | unsigned Quals); |
9440 | bool shouldDeleteForSubobjectCall(Subobject Subobj, |
9441 | Sema::SpecialMemberOverloadResult SMOR, |
9442 | bool IsDtorCallInCtor); |
9443 | |
9444 | bool isAccessible(Subobject Subobj, CXXMethodDecl *D); |
9445 | }; |
9446 | } |
9447 | |
9448 | /// Is the given special member inaccessible when used on the given |
9449 | /// sub-object. |
9450 | bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, |
9451 | CXXMethodDecl *target) { |
9452 | /// If we're operating on a base class, the object type is the |
9453 | /// type of this special member. |
9454 | QualType objectTy; |
9455 | AccessSpecifier access = target->getAccess(); |
9456 | if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { |
9457 | objectTy = S.Context.getTypeDeclType(MD->getParent()); |
9458 | access = CXXRecordDecl::MergeAccess(PathAccess: base->getAccessSpecifier(), DeclAccess: access); |
9459 | |
9460 | // If we're operating on a field, the object type is the type of the field. |
9461 | } else { |
9462 | objectTy = S.Context.getTypeDeclType(target->getParent()); |
9463 | } |
9464 | |
9465 | return S.isMemberAccessibleForDeletion( |
9466 | target->getParent(), DeclAccessPair::make(target, access), objectTy); |
9467 | } |
9468 | |
9469 | /// Check whether we should delete a special member due to the implicit |
9470 | /// definition containing a call to a special member of a subobject. |
9471 | bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( |
9472 | Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, |
9473 | bool IsDtorCallInCtor) { |
9474 | CXXMethodDecl *Decl = SMOR.getMethod(); |
9475 | FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); |
9476 | |
9477 | int DiagKind = -1; |
9478 | |
9479 | if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) |
9480 | DiagKind = !Decl ? 0 : 1; |
9481 | else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) |
9482 | DiagKind = 2; |
9483 | else if (!isAccessible(Subobj, target: Decl)) |
9484 | DiagKind = 3; |
9485 | else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && |
9486 | !Decl->isTrivial()) { |
9487 | // A member of a union must have a trivial corresponding special member. |
9488 | // As a weird special case, a destructor call from a union's constructor |
9489 | // must be accessible and non-deleted, but need not be trivial. Such a |
9490 | // destructor is never actually called, but is semantically checked as |
9491 | // if it were. |
9492 | if (CSM == CXXSpecialMemberKind::DefaultConstructor) { |
9493 | // [class.default.ctor]p2: |
9494 | // A defaulted default constructor for class X is defined as deleted if |
9495 | // - X is a union that has a variant member with a non-trivial default |
9496 | // constructor and no variant member of X has a default member |
9497 | // initializer |
9498 | const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent()); |
9499 | if (!RD->hasInClassInitializer()) |
9500 | DiagKind = 4; |
9501 | } else { |
9502 | DiagKind = 4; |
9503 | } |
9504 | } |
9505 | |
9506 | if (DiagKind == -1) |
9507 | return false; |
9508 | |
9509 | if (Diagnose) { |
9510 | if (Field) { |
9511 | S.Diag(Field->getLocation(), |
9512 | diag::note_deleted_special_member_class_subobject) |
9513 | << llvm::to_underlying(getEffectiveCSM()) << MD->getParent() |
9514 | << /*IsField*/ true << Field << DiagKind << IsDtorCallInCtor |
9515 | << /*IsObjCPtr*/ false; |
9516 | } else { |
9517 | CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); |
9518 | S.Diag(Base->getBeginLoc(), |
9519 | diag::note_deleted_special_member_class_subobject) |
9520 | << llvm::to_underlying(getEffectiveCSM()) << MD->getParent() |
9521 | << /*IsField*/ false << Base->getType() << DiagKind |
9522 | << IsDtorCallInCtor << /*IsObjCPtr*/ false; |
9523 | } |
9524 | |
9525 | if (DiagKind == 1) |
9526 | S.NoteDeletedFunction(Decl); |
9527 | // FIXME: Explain inaccessibility if DiagKind == 3. |
9528 | } |
9529 | |
9530 | return true; |
9531 | } |
9532 | |
9533 | /// Check whether we should delete a special member function due to having a |
9534 | /// direct or virtual base class or non-static data member of class type M. |
9535 | bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( |
9536 | CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { |
9537 | FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); |
9538 | bool IsMutable = Field && Field->isMutable(); |
9539 | |
9540 | // C++11 [class.ctor]p5: |
9541 | // -- any direct or virtual base class, or non-static data member with no |
9542 | // brace-or-equal-initializer, has class type M (or array thereof) and |
9543 | // either M has no default constructor or overload resolution as applied |
9544 | // to M's default constructor results in an ambiguity or in a function |
9545 | // that is deleted or inaccessible |
9546 | // C++11 [class.copy]p11, C++11 [class.copy]p23: |
9547 | // -- a direct or virtual base class B that cannot be copied/moved because |
9548 | // overload resolution, as applied to B's corresponding special member, |
9549 | // results in an ambiguity or a function that is deleted or inaccessible |
9550 | // from the defaulted special member |
9551 | // C++11 [class.dtor]p5: |
9552 | // -- any direct or virtual base class [...] has a type with a destructor |
9553 | // that is deleted or inaccessible |
9554 | if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field && |
9555 | Field->hasInClassInitializer()) && |
9556 | shouldDeleteForSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable), |
9557 | IsDtorCallInCtor: false)) |
9558 | return true; |
9559 | |
9560 | // C++11 [class.ctor]p5, C++11 [class.copy]p11: |
9561 | // -- any direct or virtual base class or non-static data member has a |
9562 | // type with a destructor that is deleted or inaccessible |
9563 | if (IsConstructor) { |
9564 | Sema::SpecialMemberOverloadResult SMOR = |
9565 | S.LookupSpecialMember(D: Class, SM: CXXSpecialMemberKind::Destructor, ConstArg: false, |
9566 | VolatileArg: false, RValueThis: false, ConstThis: false, VolatileThis: false); |
9567 | if (shouldDeleteForSubobjectCall(Subobj, SMOR, IsDtorCallInCtor: true)) |
9568 | return true; |
9569 | } |
9570 | |
9571 | return false; |
9572 | } |
9573 | |
9574 | bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( |
9575 | FieldDecl *FD, QualType FieldType) { |
9576 | // The defaulted special functions are defined as deleted if this is a variant |
9577 | // member with a non-trivial ownership type, e.g., ObjC __strong or __weak |
9578 | // type under ARC. |
9579 | if (!FieldType.hasNonTrivialObjCLifetime()) |
9580 | return false; |
9581 | |
9582 | // Don't make the defaulted default constructor defined as deleted if the |
9583 | // member has an in-class initializer. |
9584 | if (CSM == CXXSpecialMemberKind::DefaultConstructor && |
9585 | FD->hasInClassInitializer()) |
9586 | return false; |
9587 | |
9588 | if (Diagnose) { |
9589 | auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent()); |
9590 | S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject) |
9591 | << llvm::to_underlying(getEffectiveCSM()) << ParentClass |
9592 | << /*IsField*/ true << FD << 4 << /*IsDtorCallInCtor*/ false |
9593 | << /*IsObjCPtr*/ true; |
9594 | } |
9595 | |
9596 | return true; |
9597 | } |
9598 | |
9599 | /// Check whether we should delete a special member function due to the class |
9600 | /// having a particular direct or virtual base class. |
9601 | bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { |
9602 | CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); |
9603 | // If program is correct, BaseClass cannot be null, but if it is, the error |
9604 | // must be reported elsewhere. |
9605 | if (!BaseClass) |
9606 | return false; |
9607 | // If we have an inheriting constructor, check whether we're calling an |
9608 | // inherited constructor instead of a default constructor. |
9609 | Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass); |
9610 | if (auto *BaseCtor = SMOR.getMethod()) { |
9611 | // Note that we do not check access along this path; other than that, |
9612 | // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); |
9613 | // FIXME: Check that the base has a usable destructor! Sink this into |
9614 | // shouldDeleteForClassSubobject. |
9615 | if (BaseCtor->isDeleted() && Diagnose) { |
9616 | S.Diag(Base->getBeginLoc(), |
9617 | diag::note_deleted_special_member_class_subobject) |
9618 | << llvm::to_underlying(getEffectiveCSM()) << MD->getParent() |
9619 | << /*IsField*/ false << Base->getType() << /*Deleted*/ 1 |
9620 | << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ false; |
9621 | S.NoteDeletedFunction(BaseCtor); |
9622 | } |
9623 | return BaseCtor->isDeleted(); |
9624 | } |
9625 | return shouldDeleteForClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0); |
9626 | } |
9627 | |
9628 | /// Check whether we should delete a special member function due to the class |
9629 | /// having a particular non-static data member. |
9630 | bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { |
9631 | QualType FieldType = S.Context.getBaseElementType(FD->getType()); |
9632 | CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); |
9633 | |
9634 | if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) |
9635 | return true; |
9636 | |
9637 | if (CSM == CXXSpecialMemberKind::DefaultConstructor) { |
9638 | // For a default constructor, all references must be initialized in-class |
9639 | // and, if a union, it must have a non-const member. |
9640 | if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { |
9641 | if (Diagnose) |
9642 | S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) |
9643 | << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; |
9644 | return true; |
9645 | } |
9646 | // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static |
9647 | // data member of const-qualified type (or array thereof) with no |
9648 | // brace-or-equal-initializer is not const-default-constructible. |
9649 | if (!inUnion() && FieldType.isConstQualified() && |
9650 | !FD->hasInClassInitializer() && |
9651 | (!FieldRecord || !FieldRecord->allowConstDefaultInit())) { |
9652 | if (Diagnose) |
9653 | S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) |
9654 | << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; |
9655 | return true; |
9656 | } |
9657 | |
9658 | if (inUnion() && !FieldType.isConstQualified()) |
9659 | AllFieldsAreConst = false; |
9660 | } else if (CSM == CXXSpecialMemberKind::CopyConstructor) { |
9661 | // For a copy constructor, data members must not be of rvalue reference |
9662 | // type. |
9663 | if (FieldType->isRValueReferenceType()) { |
9664 | if (Diagnose) |
9665 | S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) |
9666 | << MD->getParent() << FD << FieldType; |
9667 | return true; |
9668 | } |
9669 | } else if (IsAssignment) { |
9670 | // For an assignment operator, data members must not be of reference type. |
9671 | if (FieldType->isReferenceType()) { |
9672 | if (Diagnose) |
9673 | S.Diag(FD->getLocation(), diag::note_deleted_assign_field) |
9674 | << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; |
9675 | return true; |
9676 | } |
9677 | if (!FieldRecord && FieldType.isConstQualified()) { |
9678 | // C++11 [class.copy]p23: |
9679 | // -- a non-static data member of const non-class type (or array thereof) |
9680 | if (Diagnose) |
9681 | S.Diag(FD->getLocation(), diag::note_deleted_assign_field) |
9682 | << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; |
9683 | return true; |
9684 | } |
9685 | } |
9686 | |
9687 | if (FieldRecord) { |
9688 | // Some additional restrictions exist on the variant members. |
9689 | if (!inUnion() && FieldRecord->isUnion() && |
9690 | FieldRecord->isAnonymousStructOrUnion()) { |
9691 | bool AllVariantFieldsAreConst = true; |
9692 | |
9693 | // FIXME: Handle anonymous unions declared within anonymous unions. |
9694 | for (auto *UI : FieldRecord->fields()) { |
9695 | QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); |
9696 | |
9697 | if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) |
9698 | return true; |
9699 | |
9700 | if (!UnionFieldType.isConstQualified()) |
9701 | AllVariantFieldsAreConst = false; |
9702 | |
9703 | CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); |
9704 | if (UnionFieldRecord && |
9705 | shouldDeleteForClassSubobject(UnionFieldRecord, UI, |
9706 | UnionFieldType.getCVRQualifiers())) |
9707 | return true; |
9708 | } |
9709 | |
9710 | // At least one member in each anonymous union must be non-const |
9711 | if (CSM == CXXSpecialMemberKind::DefaultConstructor && |
9712 | AllVariantFieldsAreConst && !FieldRecord->field_empty()) { |
9713 | if (Diagnose) |
9714 | S.Diag(FieldRecord->getLocation(), |
9715 | diag::note_deleted_default_ctor_all_const) |
9716 | << !!ICI << MD->getParent() << /*anonymous union*/1; |
9717 | return true; |
9718 | } |
9719 | |
9720 | // Don't check the implicit member of the anonymous union type. |
9721 | // This is technically non-conformant but supported, and we have a |
9722 | // diagnostic for this elsewhere. |
9723 | return false; |
9724 | } |
9725 | |
9726 | if (shouldDeleteForClassSubobject(Class: FieldRecord, Subobj: FD, |
9727 | Quals: FieldType.getCVRQualifiers())) |
9728 | return true; |
9729 | } |
9730 | |
9731 | return false; |
9732 | } |
9733 | |
9734 | /// C++11 [class.ctor] p5: |
9735 | /// A defaulted default constructor for a class X is defined as deleted if |
9736 | /// X is a union and all of its variant members are of const-qualified type. |
9737 | bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { |
9738 | // This is a silly definition, because it gives an empty union a deleted |
9739 | // default constructor. Don't do that. |
9740 | if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() && |
9741 | AllFieldsAreConst) { |
9742 | bool AnyFields = false; |
9743 | for (auto *F : MD->getParent()->fields()) |
9744 | if ((AnyFields = !F->isUnnamedBitField())) |
9745 | break; |
9746 | if (!AnyFields) |
9747 | return false; |
9748 | if (Diagnose) |
9749 | S.Diag(MD->getParent()->getLocation(), |
9750 | diag::note_deleted_default_ctor_all_const) |
9751 | << !!ICI << MD->getParent() << /*not anonymous union*/0; |
9752 | return true; |
9753 | } |
9754 | return false; |
9755 | } |
9756 | |
9757 | /// Determine whether a defaulted special member function should be defined as |
9758 | /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, |
9759 | /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. |
9760 | bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, |
9761 | CXXSpecialMemberKind CSM, |
9762 | InheritedConstructorInfo *ICI, |
9763 | bool Diagnose) { |
9764 | if (MD->isInvalidDecl()) |
9765 | return false; |
9766 | CXXRecordDecl *RD = MD->getParent(); |
9767 | assert(!RD->isDependentType() && "do deletion after instantiation" ); |
9768 | if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) || |
9769 | RD->isInvalidDecl()) |
9770 | return false; |
9771 | |
9772 | // C++11 [expr.lambda.prim]p19: |
9773 | // The closure type associated with a lambda-expression has a |
9774 | // deleted (8.4.3) default constructor and a deleted copy |
9775 | // assignment operator. |
9776 | // C++2a adds back these operators if the lambda has no lambda-capture. |
9777 | if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && |
9778 | (CSM == CXXSpecialMemberKind::DefaultConstructor || |
9779 | CSM == CXXSpecialMemberKind::CopyAssignment)) { |
9780 | if (Diagnose) |
9781 | Diag(RD->getLocation(), diag::note_lambda_decl); |
9782 | return true; |
9783 | } |
9784 | |
9785 | // For an anonymous struct or union, the copy and assignment special members |
9786 | // will never be used, so skip the check. For an anonymous union declared at |
9787 | // namespace scope, the constructor and destructor are used. |
9788 | if (CSM != CXXSpecialMemberKind::DefaultConstructor && |
9789 | CSM != CXXSpecialMemberKind::Destructor && RD->isAnonymousStructOrUnion()) |
9790 | return false; |
9791 | |
9792 | // C++11 [class.copy]p7, p18: |
9793 | // If the class definition declares a move constructor or move assignment |
9794 | // operator, an implicitly declared copy constructor or copy assignment |
9795 | // operator is defined as deleted. |
9796 | if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor || |
9797 | CSM == CXXSpecialMemberKind::CopyAssignment)) { |
9798 | CXXMethodDecl *UserDeclaredMove = nullptr; |
9799 | |
9800 | // In Microsoft mode up to MSVC 2013, a user-declared move only causes the |
9801 | // deletion of the corresponding copy operation, not both copy operations. |
9802 | // MSVC 2015 has adopted the standards conforming behavior. |
9803 | bool DeletesOnlyMatchingCopy = |
9804 | getLangOpts().MSVCCompat && |
9805 | !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015); |
9806 | |
9807 | if (RD->hasUserDeclaredMoveConstructor() && |
9808 | (!DeletesOnlyMatchingCopy || |
9809 | CSM == CXXSpecialMemberKind::CopyConstructor)) { |
9810 | if (!Diagnose) return true; |
9811 | |
9812 | // Find any user-declared move constructor. |
9813 | for (auto *I : RD->ctors()) { |
9814 | if (I->isMoveConstructor()) { |
9815 | UserDeclaredMove = I; |
9816 | break; |
9817 | } |
9818 | } |
9819 | assert(UserDeclaredMove); |
9820 | } else if (RD->hasUserDeclaredMoveAssignment() && |
9821 | (!DeletesOnlyMatchingCopy || |
9822 | CSM == CXXSpecialMemberKind::CopyAssignment)) { |
9823 | if (!Diagnose) return true; |
9824 | |
9825 | // Find any user-declared move assignment operator. |
9826 | for (auto *I : RD->methods()) { |
9827 | if (I->isMoveAssignmentOperator()) { |
9828 | UserDeclaredMove = I; |
9829 | break; |
9830 | } |
9831 | } |
9832 | assert(UserDeclaredMove); |
9833 | } |
9834 | |
9835 | if (UserDeclaredMove) { |
9836 | Diag(UserDeclaredMove->getLocation(), |
9837 | diag::note_deleted_copy_user_declared_move) |
9838 | << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD |
9839 | << UserDeclaredMove->isMoveAssignmentOperator(); |
9840 | return true; |
9841 | } |
9842 | } |
9843 | |
9844 | // Do access control from the special member function |
9845 | ContextRAII MethodContext(*this, MD); |
9846 | |
9847 | // C++11 [class.dtor]p5: |
9848 | // -- for a virtual destructor, lookup of the non-array deallocation function |
9849 | // results in an ambiguity or in a function that is deleted or inaccessible |
9850 | if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) { |
9851 | FunctionDecl *OperatorDelete = nullptr; |
9852 | DeclarationName Name = |
9853 | Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete); |
9854 | if (FindDeallocationFunction(StartLoc: MD->getLocation(), RD: MD->getParent(), Name, |
9855 | Operator&: OperatorDelete, /*Diagnose*/false)) { |
9856 | if (Diagnose) |
9857 | Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); |
9858 | return true; |
9859 | } |
9860 | } |
9861 | |
9862 | SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); |
9863 | |
9864 | // Per DR1611, do not consider virtual bases of constructors of abstract |
9865 | // classes, since we are not going to construct them. |
9866 | // Per DR1658, do not consider virtual bases of destructors of abstract |
9867 | // classes either. |
9868 | // Per DR2180, for assignment operators we only assign (and thus only |
9869 | // consider) direct bases. |
9870 | if (SMI.visit(Bases: SMI.IsAssignment ? SMI.VisitDirectBases |
9871 | : SMI.VisitPotentiallyConstructedBases)) |
9872 | return true; |
9873 | |
9874 | if (SMI.shouldDeleteForAllConstMembers()) |
9875 | return true; |
9876 | |
9877 | if (getLangOpts().CUDA) { |
9878 | // We should delete the special member in CUDA mode if target inference |
9879 | // failed. |
9880 | // For inherited constructors (non-null ICI), CSM may be passed so that MD |
9881 | // is treated as certain special member, which may not reflect what special |
9882 | // member MD really is. However inferTargetForImplicitSpecialMember |
9883 | // expects CSM to match MD, therefore recalculate CSM. |
9884 | assert(ICI || CSM == getSpecialMember(MD)); |
9885 | auto RealCSM = CSM; |
9886 | if (ICI) |
9887 | RealCSM = getSpecialMember(MD); |
9888 | |
9889 | return CUDA().inferTargetForImplicitSpecialMember(ClassDecl: RD, CSM: RealCSM, MemberDecl: MD, |
9890 | ConstRHS: SMI.ConstArg, Diagnose); |
9891 | } |
9892 | |
9893 | return false; |
9894 | } |
9895 | |
9896 | void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { |
9897 | DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); |
9898 | assert(DFK && "not a defaultable function" ); |
9899 | assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted" ); |
9900 | |
9901 | if (DFK.isSpecialMember()) { |
9902 | ShouldDeleteSpecialMember(MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(), |
9903 | ICI: nullptr, /*Diagnose=*/true); |
9904 | } else { |
9905 | DefaultedComparisonAnalyzer( |
9906 | *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, |
9907 | DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) |
9908 | .visit(); |
9909 | } |
9910 | } |
9911 | |
9912 | /// Perform lookup for a special member of the specified kind, and determine |
9913 | /// whether it is trivial. If the triviality can be determined without the |
9914 | /// lookup, skip it. This is intended for use when determining whether a |
9915 | /// special member of a containing object is trivial, and thus does not ever |
9916 | /// perform overload resolution for default constructors. |
9917 | /// |
9918 | /// If \p Selected is not \c NULL, \c *Selected will be filled in with the |
9919 | /// member that was most likely to be intended to be trivial, if any. |
9920 | /// |
9921 | /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to |
9922 | /// determine whether the special member is trivial. |
9923 | static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, |
9924 | CXXSpecialMemberKind CSM, unsigned Quals, |
9925 | bool ConstRHS, |
9926 | Sema::TrivialABIHandling TAH, |
9927 | CXXMethodDecl **Selected) { |
9928 | if (Selected) |
9929 | *Selected = nullptr; |
9930 | |
9931 | switch (CSM) { |
9932 | case CXXSpecialMemberKind::Invalid: |
9933 | llvm_unreachable("not a special member" ); |
9934 | |
9935 | case CXXSpecialMemberKind::DefaultConstructor: |
9936 | // C++11 [class.ctor]p5: |
9937 | // A default constructor is trivial if: |
9938 | // - all the [direct subobjects] have trivial default constructors |
9939 | // |
9940 | // Note, no overload resolution is performed in this case. |
9941 | if (RD->hasTrivialDefaultConstructor()) |
9942 | return true; |
9943 | |
9944 | if (Selected) { |
9945 | // If there's a default constructor which could have been trivial, dig it |
9946 | // out. Otherwise, if there's any user-provided default constructor, point |
9947 | // to that as an example of why there's not a trivial one. |
9948 | CXXConstructorDecl *DefCtor = nullptr; |
9949 | if (RD->needsImplicitDefaultConstructor()) |
9950 | S.DeclareImplicitDefaultConstructor(ClassDecl: RD); |
9951 | for (auto *CI : RD->ctors()) { |
9952 | if (!CI->isDefaultConstructor()) |
9953 | continue; |
9954 | DefCtor = CI; |
9955 | if (!DefCtor->isUserProvided()) |
9956 | break; |
9957 | } |
9958 | |
9959 | *Selected = DefCtor; |
9960 | } |
9961 | |
9962 | return false; |
9963 | |
9964 | case CXXSpecialMemberKind::Destructor: |
9965 | // C++11 [class.dtor]p5: |
9966 | // A destructor is trivial if: |
9967 | // - all the direct [subobjects] have trivial destructors |
9968 | if (RD->hasTrivialDestructor() || |
9969 | (TAH == Sema::TAH_ConsiderTrivialABI && |
9970 | RD->hasTrivialDestructorForCall())) |
9971 | return true; |
9972 | |
9973 | if (Selected) { |
9974 | if (RD->needsImplicitDestructor()) |
9975 | S.DeclareImplicitDestructor(ClassDecl: RD); |
9976 | *Selected = RD->getDestructor(); |
9977 | } |
9978 | |
9979 | return false; |
9980 | |
9981 | case CXXSpecialMemberKind::CopyConstructor: |
9982 | // C++11 [class.copy]p12: |
9983 | // A copy constructor is trivial if: |
9984 | // - the constructor selected to copy each direct [subobject] is trivial |
9985 | if (RD->hasTrivialCopyConstructor() || |
9986 | (TAH == Sema::TAH_ConsiderTrivialABI && |
9987 | RD->hasTrivialCopyConstructorForCall())) { |
9988 | if (Quals == Qualifiers::Const) |
9989 | // We must either select the trivial copy constructor or reach an |
9990 | // ambiguity; no need to actually perform overload resolution. |
9991 | return true; |
9992 | } else if (!Selected) { |
9993 | return false; |
9994 | } |
9995 | // In C++98, we are not supposed to perform overload resolution here, but we |
9996 | // treat that as a language defect, as suggested on cxx-abi-dev, to treat |
9997 | // cases like B as having a non-trivial copy constructor: |
9998 | // struct A { template<typename T> A(T&); }; |
9999 | // struct B { mutable A a; }; |
10000 | goto NeedOverloadResolution; |
10001 | |
10002 | case CXXSpecialMemberKind::CopyAssignment: |
10003 | // C++11 [class.copy]p25: |
10004 | // A copy assignment operator is trivial if: |
10005 | // - the assignment operator selected to copy each direct [subobject] is |
10006 | // trivial |
10007 | if (RD->hasTrivialCopyAssignment()) { |
10008 | if (Quals == Qualifiers::Const) |
10009 | return true; |
10010 | } else if (!Selected) { |
10011 | return false; |
10012 | } |
10013 | // In C++98, we are not supposed to perform overload resolution here, but we |
10014 | // treat that as a language defect. |
10015 | goto NeedOverloadResolution; |
10016 | |
10017 | case CXXSpecialMemberKind::MoveConstructor: |
10018 | case CXXSpecialMemberKind::MoveAssignment: |
10019 | NeedOverloadResolution: |
10020 | Sema::SpecialMemberOverloadResult SMOR = |
10021 | lookupCallFromSpecialMember(S, Class: RD, CSM, FieldQuals: Quals, ConstRHS); |
10022 | |
10023 | // The standard doesn't describe how to behave if the lookup is ambiguous. |
10024 | // We treat it as not making the member non-trivial, just like the standard |
10025 | // mandates for the default constructor. This should rarely matter, because |
10026 | // the member will also be deleted. |
10027 | if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) |
10028 | return true; |
10029 | |
10030 | if (!SMOR.getMethod()) { |
10031 | assert(SMOR.getKind() == |
10032 | Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); |
10033 | return false; |
10034 | } |
10035 | |
10036 | // We deliberately don't check if we found a deleted special member. We're |
10037 | // not supposed to! |
10038 | if (Selected) |
10039 | *Selected = SMOR.getMethod(); |
10040 | |
10041 | if (TAH == Sema::TAH_ConsiderTrivialABI && |
10042 | (CSM == CXXSpecialMemberKind::CopyConstructor || |
10043 | CSM == CXXSpecialMemberKind::MoveConstructor)) |
10044 | return SMOR.getMethod()->isTrivialForCall(); |
10045 | return SMOR.getMethod()->isTrivial(); |
10046 | } |
10047 | |
10048 | llvm_unreachable("unknown special method kind" ); |
10049 | } |
10050 | |
10051 | static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { |
10052 | for (auto *CI : RD->ctors()) |
10053 | if (!CI->isImplicit()) |
10054 | return CI; |
10055 | |
10056 | // Look for constructor templates. |
10057 | typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; |
10058 | for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { |
10059 | if (CXXConstructorDecl *CD = |
10060 | dyn_cast<CXXConstructorDecl>(Val: TI->getTemplatedDecl())) |
10061 | return CD; |
10062 | } |
10063 | |
10064 | return nullptr; |
10065 | } |
10066 | |
10067 | /// The kind of subobject we are checking for triviality. The values of this |
10068 | /// enumeration are used in diagnostics. |
10069 | enum TrivialSubobjectKind { |
10070 | /// The subobject is a base class. |
10071 | TSK_BaseClass, |
10072 | /// The subobject is a non-static data member. |
10073 | TSK_Field, |
10074 | /// The object is actually the complete object. |
10075 | TSK_CompleteObject |
10076 | }; |
10077 | |
10078 | /// Check whether the special member selected for a given type would be trivial. |
10079 | static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, |
10080 | QualType SubType, bool ConstRHS, |
10081 | CXXSpecialMemberKind CSM, |
10082 | TrivialSubobjectKind Kind, |
10083 | Sema::TrivialABIHandling TAH, |
10084 | bool Diagnose) { |
10085 | CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); |
10086 | if (!SubRD) |
10087 | return true; |
10088 | |
10089 | CXXMethodDecl *Selected; |
10090 | if (findTrivialSpecialMember(S, RD: SubRD, CSM, Quals: SubType.getCVRQualifiers(), |
10091 | ConstRHS, TAH, Selected: Diagnose ? &Selected : nullptr)) |
10092 | return true; |
10093 | |
10094 | if (Diagnose) { |
10095 | if (ConstRHS) |
10096 | SubType.addConst(); |
10097 | |
10098 | if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) { |
10099 | S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) |
10100 | << Kind << SubType.getUnqualifiedType(); |
10101 | if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) |
10102 | S.Diag(CD->getLocation(), diag::note_user_declared_ctor); |
10103 | } else if (!Selected) |
10104 | S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) |
10105 | << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM) |
10106 | << SubType; |
10107 | else if (Selected->isUserProvided()) { |
10108 | if (Kind == TSK_CompleteObject) |
10109 | S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) |
10110 | << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM); |
10111 | else { |
10112 | S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) |
10113 | << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM); |
10114 | S.Diag(Selected->getLocation(), diag::note_declared_at); |
10115 | } |
10116 | } else { |
10117 | if (Kind != TSK_CompleteObject) |
10118 | S.Diag(SubobjLoc, diag::note_nontrivial_subobject) |
10119 | << Kind << SubType.getUnqualifiedType() << llvm::to_underlying(CSM); |
10120 | |
10121 | // Explain why the defaulted or deleted special member isn't trivial. |
10122 | S.SpecialMemberIsTrivial(MD: Selected, CSM, TAH: Sema::TAH_IgnoreTrivialABI, |
10123 | Diagnose); |
10124 | } |
10125 | } |
10126 | |
10127 | return false; |
10128 | } |
10129 | |
10130 | /// Check whether the members of a class type allow a special member to be |
10131 | /// trivial. |
10132 | static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, |
10133 | CXXSpecialMemberKind CSM, bool ConstArg, |
10134 | Sema::TrivialABIHandling TAH, |
10135 | bool Diagnose) { |
10136 | for (const auto *FI : RD->fields()) { |
10137 | if (FI->isInvalidDecl() || FI->isUnnamedBitField()) |
10138 | continue; |
10139 | |
10140 | QualType FieldType = S.Context.getBaseElementType(FI->getType()); |
10141 | |
10142 | // Pretend anonymous struct or union members are members of this class. |
10143 | if (FI->isAnonymousStructOrUnion()) { |
10144 | if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), |
10145 | CSM, ConstArg, TAH, Diagnose)) |
10146 | return false; |
10147 | continue; |
10148 | } |
10149 | |
10150 | // C++11 [class.ctor]p5: |
10151 | // A default constructor is trivial if [...] |
10152 | // -- no non-static data member of its class has a |
10153 | // brace-or-equal-initializer |
10154 | if (CSM == CXXSpecialMemberKind::DefaultConstructor && |
10155 | FI->hasInClassInitializer()) { |
10156 | if (Diagnose) |
10157 | S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) |
10158 | << FI; |
10159 | return false; |
10160 | } |
10161 | |
10162 | // Objective C ARC 4.3.5: |
10163 | // [...] nontrivally ownership-qualified types are [...] not trivially |
10164 | // default constructible, copy constructible, move constructible, copy |
10165 | // assignable, move assignable, or destructible [...] |
10166 | if (FieldType.hasNonTrivialObjCLifetime()) { |
10167 | if (Diagnose) |
10168 | S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) |
10169 | << RD << FieldType.getObjCLifetime(); |
10170 | return false; |
10171 | } |
10172 | |
10173 | bool ConstRHS = ConstArg && !FI->isMutable(); |
10174 | if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, |
10175 | CSM, TSK_Field, TAH, Diagnose)) |
10176 | return false; |
10177 | } |
10178 | |
10179 | return true; |
10180 | } |
10181 | |
10182 | /// Diagnose why the specified class does not have a trivial special member of |
10183 | /// the given kind. |
10184 | void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, |
10185 | CXXSpecialMemberKind CSM) { |
10186 | QualType Ty = Context.getRecordType(RD); |
10187 | |
10188 | bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor || |
10189 | CSM == CXXSpecialMemberKind::CopyAssignment); |
10190 | checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, |
10191 | TSK_CompleteObject, TAH_IgnoreTrivialABI, |
10192 | /*Diagnose*/true); |
10193 | } |
10194 | |
10195 | /// Determine whether a defaulted or deleted special member function is trivial, |
10196 | /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, |
10197 | /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. |
10198 | bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, |
10199 | TrivialABIHandling TAH, bool Diagnose) { |
10200 | assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid && |
10201 | "not special enough" ); |
10202 | |
10203 | CXXRecordDecl *RD = MD->getParent(); |
10204 | |
10205 | bool ConstArg = false; |
10206 | |
10207 | // C++11 [class.copy]p12, p25: [DR1593] |
10208 | // A [special member] is trivial if [...] its parameter-type-list is |
10209 | // equivalent to the parameter-type-list of an implicit declaration [...] |
10210 | switch (CSM) { |
10211 | case CXXSpecialMemberKind::DefaultConstructor: |
10212 | case CXXSpecialMemberKind::Destructor: |
10213 | // Trivial default constructors and destructors cannot have parameters. |
10214 | break; |
10215 | |
10216 | case CXXSpecialMemberKind::CopyConstructor: |
10217 | case CXXSpecialMemberKind::CopyAssignment: { |
10218 | const ParmVarDecl *Param0 = MD->getNonObjectParameter(0); |
10219 | const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); |
10220 | |
10221 | // When ClangABICompat14 is true, CXX copy constructors will only be trivial |
10222 | // if they are not user-provided and their parameter-type-list is equivalent |
10223 | // to the parameter-type-list of an implicit declaration. This maintains the |
10224 | // behavior before dr2171 was implemented. |
10225 | // |
10226 | // Otherwise, if ClangABICompat14 is false, All copy constructors can be |
10227 | // trivial, if they are not user-provided, regardless of the qualifiers on |
10228 | // the reference type. |
10229 | const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <= |
10230 | LangOptions::ClangABI::Ver14; |
10231 | if (!RT || |
10232 | ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) && |
10233 | ClangABICompat14)) { |
10234 | if (Diagnose) |
10235 | Diag(Param0->getLocation(), diag::note_nontrivial_param_type) |
10236 | << Param0->getSourceRange() << Param0->getType() |
10237 | << Context.getLValueReferenceType( |
10238 | Context.getRecordType(RD).withConst()); |
10239 | return false; |
10240 | } |
10241 | |
10242 | ConstArg = RT->getPointeeType().isConstQualified(); |
10243 | break; |
10244 | } |
10245 | |
10246 | case CXXSpecialMemberKind::MoveConstructor: |
10247 | case CXXSpecialMemberKind::MoveAssignment: { |
10248 | // Trivial move operations always have non-cv-qualified parameters. |
10249 | const ParmVarDecl *Param0 = MD->getNonObjectParameter(0); |
10250 | const RValueReferenceType *RT = |
10251 | Param0->getType()->getAs<RValueReferenceType>(); |
10252 | if (!RT || RT->getPointeeType().getCVRQualifiers()) { |
10253 | if (Diagnose) |
10254 | Diag(Param0->getLocation(), diag::note_nontrivial_param_type) |
10255 | << Param0->getSourceRange() << Param0->getType() |
10256 | << Context.getRValueReferenceType(Context.getRecordType(RD)); |
10257 | return false; |
10258 | } |
10259 | break; |
10260 | } |
10261 | |
10262 | case CXXSpecialMemberKind::Invalid: |
10263 | llvm_unreachable("not a special member" ); |
10264 | } |
10265 | |
10266 | if (MD->getMinRequiredArguments() < MD->getNumParams()) { |
10267 | if (Diagnose) |
10268 | Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), |
10269 | diag::note_nontrivial_default_arg) |
10270 | << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); |
10271 | return false; |
10272 | } |
10273 | if (MD->isVariadic()) { |
10274 | if (Diagnose) |
10275 | Diag(MD->getLocation(), diag::note_nontrivial_variadic); |
10276 | return false; |
10277 | } |
10278 | |
10279 | // C++11 [class.ctor]p5, C++11 [class.dtor]p5: |
10280 | // A copy/move [constructor or assignment operator] is trivial if |
10281 | // -- the [member] selected to copy/move each direct base class subobject |
10282 | // is trivial |
10283 | // |
10284 | // C++11 [class.copy]p12, C++11 [class.copy]p25: |
10285 | // A [default constructor or destructor] is trivial if |
10286 | // -- all the direct base classes have trivial [default constructors or |
10287 | // destructors] |
10288 | for (const auto &BI : RD->bases()) |
10289 | if (!checkTrivialSubobjectCall(S&: *this, SubobjLoc: BI.getBeginLoc(), SubType: BI.getType(), |
10290 | ConstRHS: ConstArg, CSM, Kind: TSK_BaseClass, TAH, Diagnose)) |
10291 | return false; |
10292 | |
10293 | // C++11 [class.ctor]p5, C++11 [class.dtor]p5: |
10294 | // A copy/move [constructor or assignment operator] for a class X is |
10295 | // trivial if |
10296 | // -- for each non-static data member of X that is of class type (or array |
10297 | // thereof), the constructor selected to copy/move that member is |
10298 | // trivial |
10299 | // |
10300 | // C++11 [class.copy]p12, C++11 [class.copy]p25: |
10301 | // A [default constructor or destructor] is trivial if |
10302 | // -- for all of the non-static data members of its class that are of class |
10303 | // type (or array thereof), each such class has a trivial [default |
10304 | // constructor or destructor] |
10305 | if (!checkTrivialClassMembers(S&: *this, RD, CSM, ConstArg, TAH, Diagnose)) |
10306 | return false; |
10307 | |
10308 | // C++11 [class.dtor]p5: |
10309 | // A destructor is trivial if [...] |
10310 | // -- the destructor is not virtual |
10311 | if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) { |
10312 | if (Diagnose) |
10313 | Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; |
10314 | return false; |
10315 | } |
10316 | |
10317 | // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: |
10318 | // A [special member] for class X is trivial if [...] |
10319 | // -- class X has no virtual functions and no virtual base classes |
10320 | if (CSM != CXXSpecialMemberKind::Destructor && |
10321 | MD->getParent()->isDynamicClass()) { |
10322 | if (!Diagnose) |
10323 | return false; |
10324 | |
10325 | if (RD->getNumVBases()) { |
10326 | // Check for virtual bases. We already know that the corresponding |
10327 | // member in all bases is trivial, so vbases must all be direct. |
10328 | CXXBaseSpecifier &BS = *RD->vbases_begin(); |
10329 | assert(BS.isVirtual()); |
10330 | Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; |
10331 | return false; |
10332 | } |
10333 | |
10334 | // Must have a virtual method. |
10335 | for (const auto *MI : RD->methods()) { |
10336 | if (MI->isVirtual()) { |
10337 | SourceLocation MLoc = MI->getBeginLoc(); |
10338 | Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; |
10339 | return false; |
10340 | } |
10341 | } |
10342 | |
10343 | llvm_unreachable("dynamic class with no vbases and no virtual functions" ); |
10344 | } |
10345 | |
10346 | // Looks like it's trivial! |
10347 | return true; |
10348 | } |
10349 | |
10350 | namespace { |
10351 | struct FindHiddenVirtualMethod { |
10352 | Sema *S; |
10353 | CXXMethodDecl *Method; |
10354 | llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; |
10355 | SmallVector<CXXMethodDecl *, 8> OverloadedMethods; |
10356 | |
10357 | private: |
10358 | /// Check whether any most overridden method from MD in Methods |
10359 | static bool CheckMostOverridenMethods( |
10360 | const CXXMethodDecl *MD, |
10361 | const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { |
10362 | if (MD->size_overridden_methods() == 0) |
10363 | return Methods.count(Ptr: MD->getCanonicalDecl()); |
10364 | for (const CXXMethodDecl *O : MD->overridden_methods()) |
10365 | if (CheckMostOverridenMethods(MD: O, Methods)) |
10366 | return true; |
10367 | return false; |
10368 | } |
10369 | |
10370 | public: |
10371 | /// Member lookup function that determines whether a given C++ |
10372 | /// method overloads virtual methods in a base class without overriding any, |
10373 | /// to be used with CXXRecordDecl::lookupInBases(). |
10374 | bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { |
10375 | RecordDecl *BaseRecord = |
10376 | Specifier->getType()->castAs<RecordType>()->getDecl(); |
10377 | |
10378 | DeclarationName Name = Method->getDeclName(); |
10379 | assert(Name.getNameKind() == DeclarationName::Identifier); |
10380 | |
10381 | bool foundSameNameMethod = false; |
10382 | SmallVector<CXXMethodDecl *, 8> overloadedMethods; |
10383 | for (Path.Decls = BaseRecord->lookup(Name).begin(); |
10384 | Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) { |
10385 | NamedDecl *D = *Path.Decls; |
10386 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) { |
10387 | MD = MD->getCanonicalDecl(); |
10388 | foundSameNameMethod = true; |
10389 | // Interested only in hidden virtual methods. |
10390 | if (!MD->isVirtual()) |
10391 | continue; |
10392 | // If the method we are checking overrides a method from its base |
10393 | // don't warn about the other overloaded methods. Clang deviates from |
10394 | // GCC by only diagnosing overloads of inherited virtual functions that |
10395 | // do not override any other virtual functions in the base. GCC's |
10396 | // -Woverloaded-virtual diagnoses any derived function hiding a virtual |
10397 | // function from a base class. These cases may be better served by a |
10398 | // warning (not specific to virtual functions) on call sites when the |
10399 | // call would select a different function from the base class, were it |
10400 | // visible. |
10401 | // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. |
10402 | if (!S->IsOverload(Method, MD, false)) |
10403 | return true; |
10404 | // Collect the overload only if its hidden. |
10405 | if (!CheckMostOverridenMethods(MD, Methods: OverridenAndUsingBaseMethods)) |
10406 | overloadedMethods.push_back(Elt: MD); |
10407 | } |
10408 | } |
10409 | |
10410 | if (foundSameNameMethod) |
10411 | OverloadedMethods.append(in_start: overloadedMethods.begin(), |
10412 | in_end: overloadedMethods.end()); |
10413 | return foundSameNameMethod; |
10414 | } |
10415 | }; |
10416 | } // end anonymous namespace |
10417 | |
10418 | /// Add the most overridden methods from MD to Methods |
10419 | static void AddMostOverridenMethods(const CXXMethodDecl *MD, |
10420 | llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { |
10421 | if (MD->size_overridden_methods() == 0) |
10422 | Methods.insert(Ptr: MD->getCanonicalDecl()); |
10423 | else |
10424 | for (const CXXMethodDecl *O : MD->overridden_methods()) |
10425 | AddMostOverridenMethods(MD: O, Methods); |
10426 | } |
10427 | |
10428 | /// Check if a method overloads virtual methods in a base class without |
10429 | /// overriding any. |
10430 | void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, |
10431 | SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { |
10432 | if (!MD->getDeclName().isIdentifier()) |
10433 | return; |
10434 | |
10435 | CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. |
10436 | /*bool RecordPaths=*/false, |
10437 | /*bool DetectVirtual=*/false); |
10438 | FindHiddenVirtualMethod FHVM; |
10439 | FHVM.Method = MD; |
10440 | FHVM.S = this; |
10441 | |
10442 | // Keep the base methods that were overridden or introduced in the subclass |
10443 | // by 'using' in a set. A base method not in this set is hidden. |
10444 | CXXRecordDecl *DC = MD->getParent(); |
10445 | DeclContext::lookup_result R = DC->lookup(Name: MD->getDeclName()); |
10446 | for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { |
10447 | NamedDecl *ND = *I; |
10448 | if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(Val: *I)) |
10449 | ND = shad->getTargetDecl(); |
10450 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ND)) |
10451 | AddMostOverridenMethods(MD, Methods&: FHVM.OverridenAndUsingBaseMethods); |
10452 | } |
10453 | |
10454 | if (DC->lookupInBases(BaseMatches: FHVM, Paths)) |
10455 | OverloadedMethods = FHVM.OverloadedMethods; |
10456 | } |
10457 | |
10458 | void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, |
10459 | SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { |
10460 | for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { |
10461 | CXXMethodDecl *overloadedMD = OverloadedMethods[i]; |
10462 | PartialDiagnostic PD = PDiag( |
10463 | diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; |
10464 | HandleFunctionTypeMismatch(PDiag&: PD, FromType: MD->getType(), ToType: overloadedMD->getType()); |
10465 | Diag(overloadedMD->getLocation(), PD); |
10466 | } |
10467 | } |
10468 | |
10469 | /// Diagnose methods which overload virtual methods in a base class |
10470 | /// without overriding any. |
10471 | void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { |
10472 | if (MD->isInvalidDecl()) |
10473 | return; |
10474 | |
10475 | if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) |
10476 | return; |
10477 | |
10478 | SmallVector<CXXMethodDecl *, 8> OverloadedMethods; |
10479 | FindHiddenVirtualMethods(MD, OverloadedMethods); |
10480 | if (!OverloadedMethods.empty()) { |
10481 | Diag(MD->getLocation(), diag::warn_overloaded_virtual) |
10482 | << MD << (OverloadedMethods.size() > 1); |
10483 | |
10484 | NoteHiddenVirtualMethods(MD, OverloadedMethods); |
10485 | } |
10486 | } |
10487 | |
10488 | void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { |
10489 | auto PrintDiagAndRemoveAttr = [&](unsigned N) { |
10490 | // No diagnostics if this is a template instantiation. |
10491 | if (!isTemplateInstantiation(Kind: RD.getTemplateSpecializationKind())) { |
10492 | Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), |
10493 | diag::ext_cannot_use_trivial_abi) << &RD; |
10494 | Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), |
10495 | diag::note_cannot_use_trivial_abi_reason) << &RD << N; |
10496 | } |
10497 | RD.dropAttr<TrivialABIAttr>(); |
10498 | }; |
10499 | |
10500 | // Ill-formed if the copy and move constructors are deleted. |
10501 | auto HasNonDeletedCopyOrMoveConstructor = [&]() { |
10502 | // If the type is dependent, then assume it might have |
10503 | // implicit copy or move ctor because we won't know yet at this point. |
10504 | if (RD.isDependentType()) |
10505 | return true; |
10506 | if (RD.needsImplicitCopyConstructor() && |
10507 | !RD.defaultedCopyConstructorIsDeleted()) |
10508 | return true; |
10509 | if (RD.needsImplicitMoveConstructor() && |
10510 | !RD.defaultedMoveConstructorIsDeleted()) |
10511 | return true; |
10512 | for (const CXXConstructorDecl *CD : RD.ctors()) |
10513 | if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) |
10514 | return true; |
10515 | return false; |
10516 | }; |
10517 | |
10518 | if (!HasNonDeletedCopyOrMoveConstructor()) { |
10519 | PrintDiagAndRemoveAttr(0); |
10520 | return; |
10521 | } |
10522 | |
10523 | // Ill-formed if the struct has virtual functions. |
10524 | if (RD.isPolymorphic()) { |
10525 | PrintDiagAndRemoveAttr(1); |
10526 | return; |
10527 | } |
10528 | |
10529 | for (const auto &B : RD.bases()) { |
10530 | // Ill-formed if the base class is non-trivial for the purpose of calls or a |
10531 | // virtual base. |
10532 | if (!B.getType()->isDependentType() && |
10533 | !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { |
10534 | PrintDiagAndRemoveAttr(2); |
10535 | return; |
10536 | } |
10537 | |
10538 | if (B.isVirtual()) { |
10539 | PrintDiagAndRemoveAttr(3); |
10540 | return; |
10541 | } |
10542 | } |
10543 | |
10544 | for (const auto *FD : RD.fields()) { |
10545 | // Ill-formed if the field is an ObjectiveC pointer or of a type that is |
10546 | // non-trivial for the purpose of calls. |
10547 | QualType FT = FD->getType(); |
10548 | if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { |
10549 | PrintDiagAndRemoveAttr(4); |
10550 | return; |
10551 | } |
10552 | |
10553 | if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) |
10554 | if (!RT->isDependentType() && |
10555 | !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { |
10556 | PrintDiagAndRemoveAttr(5); |
10557 | return; |
10558 | } |
10559 | } |
10560 | } |
10561 | |
10562 | void Sema::ActOnFinishCXXMemberSpecification( |
10563 | Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, |
10564 | SourceLocation RBrac, const ParsedAttributesView &AttrList) { |
10565 | if (!TagDecl) |
10566 | return; |
10567 | |
10568 | AdjustDeclIfTemplate(Decl&: TagDecl); |
10569 | |
10570 | for (const ParsedAttr &AL : AttrList) { |
10571 | if (AL.getKind() != ParsedAttr::AT_Visibility) |
10572 | continue; |
10573 | AL.setInvalid(); |
10574 | Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; |
10575 | } |
10576 | |
10577 | ActOnFields(S, RecLoc: RLoc, TagDecl, |
10578 | Fields: llvm::ArrayRef( |
10579 | // strict aliasing violation! |
10580 | reinterpret_cast<Decl **>(FieldCollector->getCurFields()), |
10581 | FieldCollector->getCurNumFields()), |
10582 | LBrac, RBrac, AttrList); |
10583 | |
10584 | CheckCompletedCXXClass(S, Record: cast<CXXRecordDecl>(Val: TagDecl)); |
10585 | } |
10586 | |
10587 | /// Find the equality comparison functions that should be implicitly declared |
10588 | /// in a given class definition, per C++2a [class.compare.default]p3. |
10589 | static void findImplicitlyDeclaredEqualityComparisons( |
10590 | ASTContext &Ctx, CXXRecordDecl *RD, |
10591 | llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { |
10592 | DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_EqualEqual); |
10593 | if (!RD->lookup(EqEq).empty()) |
10594 | // Member operator== explicitly declared: no implicit operator==s. |
10595 | return; |
10596 | |
10597 | // Traverse friends looking for an '==' or a '<=>'. |
10598 | for (FriendDecl *Friend : RD->friends()) { |
10599 | FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: Friend->getFriendDecl()); |
10600 | if (!FD) continue; |
10601 | |
10602 | if (FD->getOverloadedOperator() == OO_EqualEqual) { |
10603 | // Friend operator== explicitly declared: no implicit operator==s. |
10604 | Spaceships.clear(); |
10605 | return; |
10606 | } |
10607 | |
10608 | if (FD->getOverloadedOperator() == OO_Spaceship && |
10609 | FD->isExplicitlyDefaulted()) |
10610 | Spaceships.push_back(Elt: FD); |
10611 | } |
10612 | |
10613 | // Look for members named 'operator<=>'. |
10614 | DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_Spaceship); |
10615 | for (NamedDecl *ND : RD->lookup(Cmp)) { |
10616 | // Note that we could find a non-function here (either a function template |
10617 | // or a using-declaration). Neither case results in an implicit |
10618 | // 'operator=='. |
10619 | if (auto *FD = dyn_cast<FunctionDecl>(ND)) |
10620 | if (FD->isExplicitlyDefaulted()) |
10621 | Spaceships.push_back(FD); |
10622 | } |
10623 | } |
10624 | |
10625 | /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared |
10626 | /// special functions, such as the default constructor, copy |
10627 | /// constructor, or destructor, to the given C++ class (C++ |
10628 | /// [special]p1). This routine can only be executed just before the |
10629 | /// definition of the class is complete. |
10630 | void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { |
10631 | // Don't add implicit special members to templated classes. |
10632 | // FIXME: This means unqualified lookups for 'operator=' within a class |
10633 | // template don't work properly. |
10634 | if (!ClassDecl->isDependentType()) { |
10635 | if (ClassDecl->needsImplicitDefaultConstructor()) { |
10636 | ++getASTContext().NumImplicitDefaultConstructors; |
10637 | |
10638 | if (ClassDecl->hasInheritedConstructor()) |
10639 | DeclareImplicitDefaultConstructor(ClassDecl); |
10640 | } |
10641 | |
10642 | if (ClassDecl->needsImplicitCopyConstructor()) { |
10643 | ++getASTContext().NumImplicitCopyConstructors; |
10644 | |
10645 | // If the properties or semantics of the copy constructor couldn't be |
10646 | // determined while the class was being declared, force a declaration |
10647 | // of it now. |
10648 | if (ClassDecl->needsOverloadResolutionForCopyConstructor() || |
10649 | ClassDecl->hasInheritedConstructor()) |
10650 | DeclareImplicitCopyConstructor(ClassDecl); |
10651 | // For the MS ABI we need to know whether the copy ctor is deleted. A |
10652 | // prerequisite for deleting the implicit copy ctor is that the class has |
10653 | // a move ctor or move assignment that is either user-declared or whose |
10654 | // semantics are inherited from a subobject. FIXME: We should provide a |
10655 | // more direct way for CodeGen to ask whether the constructor was deleted. |
10656 | else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && |
10657 | (ClassDecl->hasUserDeclaredMoveConstructor() || |
10658 | ClassDecl->needsOverloadResolutionForMoveConstructor() || |
10659 | ClassDecl->hasUserDeclaredMoveAssignment() || |
10660 | ClassDecl->needsOverloadResolutionForMoveAssignment())) |
10661 | DeclareImplicitCopyConstructor(ClassDecl); |
10662 | } |
10663 | |
10664 | if (getLangOpts().CPlusPlus11 && |
10665 | ClassDecl->needsImplicitMoveConstructor()) { |
10666 | ++getASTContext().NumImplicitMoveConstructors; |
10667 | |
10668 | if (ClassDecl->needsOverloadResolutionForMoveConstructor() || |
10669 | ClassDecl->hasInheritedConstructor()) |
10670 | DeclareImplicitMoveConstructor(ClassDecl); |
10671 | } |
10672 | |
10673 | if (ClassDecl->needsImplicitCopyAssignment()) { |
10674 | ++getASTContext().NumImplicitCopyAssignmentOperators; |
10675 | |
10676 | // If we have a dynamic class, then the copy assignment operator may be |
10677 | // virtual, so we have to declare it immediately. This ensures that, e.g., |
10678 | // it shows up in the right place in the vtable and that we diagnose |
10679 | // problems with the implicit exception specification. |
10680 | if (ClassDecl->isDynamicClass() || |
10681 | ClassDecl->needsOverloadResolutionForCopyAssignment() || |
10682 | ClassDecl->hasInheritedAssignment()) |
10683 | DeclareImplicitCopyAssignment(ClassDecl); |
10684 | } |
10685 | |
10686 | if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { |
10687 | ++getASTContext().NumImplicitMoveAssignmentOperators; |
10688 | |
10689 | // Likewise for the move assignment operator. |
10690 | if (ClassDecl->isDynamicClass() || |
10691 | ClassDecl->needsOverloadResolutionForMoveAssignment() || |
10692 | ClassDecl->hasInheritedAssignment()) |
10693 | DeclareImplicitMoveAssignment(ClassDecl); |
10694 | } |
10695 | |
10696 | if (ClassDecl->needsImplicitDestructor()) { |
10697 | ++getASTContext().NumImplicitDestructors; |
10698 | |
10699 | // If we have a dynamic class, then the destructor may be virtual, so we |
10700 | // have to declare the destructor immediately. This ensures that, e.g., it |
10701 | // shows up in the right place in the vtable and that we diagnose problems |
10702 | // with the implicit exception specification. |
10703 | if (ClassDecl->isDynamicClass() || |
10704 | ClassDecl->needsOverloadResolutionForDestructor()) |
10705 | DeclareImplicitDestructor(ClassDecl); |
10706 | } |
10707 | } |
10708 | |
10709 | // C++2a [class.compare.default]p3: |
10710 | // If the member-specification does not explicitly declare any member or |
10711 | // friend named operator==, an == operator function is declared implicitly |
10712 | // for each defaulted three-way comparison operator function defined in |
10713 | // the member-specification |
10714 | // FIXME: Consider doing this lazily. |
10715 | // We do this during the initial parse for a class template, not during |
10716 | // instantiation, so that we can handle unqualified lookups for 'operator==' |
10717 | // when parsing the template. |
10718 | if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { |
10719 | llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; |
10720 | findImplicitlyDeclaredEqualityComparisons(Ctx&: Context, RD: ClassDecl, |
10721 | Spaceships&: DefaultedSpaceships); |
10722 | for (auto *FD : DefaultedSpaceships) |
10723 | DeclareImplicitEqualityComparison(RD: ClassDecl, Spaceship: FD); |
10724 | } |
10725 | } |
10726 | |
10727 | unsigned |
10728 | Sema::ActOnReenterTemplateScope(Decl *D, |
10729 | llvm::function_ref<Scope *()> EnterScope) { |
10730 | if (!D) |
10731 | return 0; |
10732 | AdjustDeclIfTemplate(Decl&: D); |
10733 | |
10734 | // In order to get name lookup right, reenter template scopes in order from |
10735 | // outermost to innermost. |
10736 | SmallVector<TemplateParameterList *, 4> ParameterLists; |
10737 | DeclContext *LookupDC = dyn_cast<DeclContext>(Val: D); |
10738 | |
10739 | if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(Val: D)) { |
10740 | for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) |
10741 | ParameterLists.push_back(Elt: DD->getTemplateParameterList(index: i)); |
10742 | |
10743 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) { |
10744 | if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) |
10745 | ParameterLists.push_back(Elt: FTD->getTemplateParameters()); |
10746 | } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) { |
10747 | LookupDC = VD->getDeclContext(); |
10748 | |
10749 | if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) |
10750 | ParameterLists.push_back(Elt: VTD->getTemplateParameters()); |
10751 | else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: D)) |
10752 | ParameterLists.push_back(Elt: PSD->getTemplateParameters()); |
10753 | } |
10754 | } else if (TagDecl *TD = dyn_cast<TagDecl>(Val: D)) { |
10755 | for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) |
10756 | ParameterLists.push_back(Elt: TD->getTemplateParameterList(i)); |
10757 | |
10758 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TD)) { |
10759 | if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) |
10760 | ParameterLists.push_back(Elt: CTD->getTemplateParameters()); |
10761 | else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: D)) |
10762 | ParameterLists.push_back(Elt: PSD->getTemplateParameters()); |
10763 | } |
10764 | } |
10765 | // FIXME: Alias declarations and concepts. |
10766 | |
10767 | unsigned Count = 0; |
10768 | Scope *InnermostTemplateScope = nullptr; |
10769 | for (TemplateParameterList *Params : ParameterLists) { |
10770 | // Ignore explicit specializations; they don't contribute to the template |
10771 | // depth. |
10772 | if (Params->size() == 0) |
10773 | continue; |
10774 | |
10775 | InnermostTemplateScope = EnterScope(); |
10776 | for (NamedDecl *Param : *Params) { |
10777 | if (Param->getDeclName()) { |
10778 | InnermostTemplateScope->AddDecl(Param); |
10779 | IdResolver.AddDecl(D: Param); |
10780 | } |
10781 | } |
10782 | ++Count; |
10783 | } |
10784 | |
10785 | // Associate the new template scopes with the corresponding entities. |
10786 | if (InnermostTemplateScope) { |
10787 | assert(LookupDC && "no enclosing DeclContext for template lookup" ); |
10788 | EnterTemplatedContext(S: InnermostTemplateScope, DC: LookupDC); |
10789 | } |
10790 | |
10791 | return Count; |
10792 | } |
10793 | |
10794 | void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { |
10795 | if (!RecordD) return; |
10796 | AdjustDeclIfTemplate(Decl&: RecordD); |
10797 | CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: RecordD); |
10798 | PushDeclContext(S, Record); |
10799 | } |
10800 | |
10801 | void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { |
10802 | if (!RecordD) return; |
10803 | PopDeclContext(); |
10804 | } |
10805 | |
10806 | /// This is used to implement the constant expression evaluation part of the |
10807 | /// attribute enable_if extension. There is nothing in standard C++ which would |
10808 | /// require reentering parameters. |
10809 | void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { |
10810 | if (!Param) |
10811 | return; |
10812 | |
10813 | S->AddDecl(Param); |
10814 | if (Param->getDeclName()) |
10815 | IdResolver.AddDecl(Param); |
10816 | } |
10817 | |
10818 | /// ActOnStartDelayedCXXMethodDeclaration - We have completed |
10819 | /// parsing a top-level (non-nested) C++ class, and we are now |
10820 | /// parsing those parts of the given Method declaration that could |
10821 | /// not be parsed earlier (C++ [class.mem]p2), such as default |
10822 | /// arguments. This action should enter the scope of the given |
10823 | /// Method declaration as if we had just parsed the qualified method |
10824 | /// name. However, it should not bring the parameters into scope; |
10825 | /// that will be performed by ActOnDelayedCXXMethodParameter. |
10826 | void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { |
10827 | } |
10828 | |
10829 | /// ActOnDelayedCXXMethodParameter - We've already started a delayed |
10830 | /// C++ method declaration. We're (re-)introducing the given |
10831 | /// function parameter into scope for use in parsing later parts of |
10832 | /// the method declaration. For example, we could see an |
10833 | /// ActOnParamDefaultArgument event for this parameter. |
10834 | void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { |
10835 | if (!ParamD) |
10836 | return; |
10837 | |
10838 | ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamD); |
10839 | |
10840 | S->AddDecl(Param); |
10841 | if (Param->getDeclName()) |
10842 | IdResolver.AddDecl(Param); |
10843 | } |
10844 | |
10845 | /// ActOnFinishDelayedCXXMethodDeclaration - We have finished |
10846 | /// processing the delayed method declaration for Method. The method |
10847 | /// declaration is now considered finished. There may be a separate |
10848 | /// ActOnStartOfFunctionDef action later (not necessarily |
10849 | /// immediately!) for this method, if it was also defined inside the |
10850 | /// class body. |
10851 | void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { |
10852 | if (!MethodD) |
10853 | return; |
10854 | |
10855 | AdjustDeclIfTemplate(Decl&: MethodD); |
10856 | |
10857 | FunctionDecl *Method = cast<FunctionDecl>(Val: MethodD); |
10858 | |
10859 | // Now that we have our default arguments, check the constructor |
10860 | // again. It could produce additional diagnostics or affect whether |
10861 | // the class has implicitly-declared destructors, among other |
10862 | // things. |
10863 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Method)) |
10864 | CheckConstructor(Constructor); |
10865 | |
10866 | // Check the default arguments, which we may have added. |
10867 | if (!Method->isInvalidDecl()) |
10868 | CheckCXXDefaultArguments(FD: Method); |
10869 | } |
10870 | |
10871 | // Emit the given diagnostic for each non-address-space qualifier. |
10872 | // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. |
10873 | static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { |
10874 | const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); |
10875 | if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { |
10876 | bool DiagOccured = false; |
10877 | FTI.MethodQualifiers->forEachQualifier( |
10878 | Handle: [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, |
10879 | SourceLocation SL) { |
10880 | // This diagnostic should be emitted on any qualifier except an addr |
10881 | // space qualifier. However, forEachQualifier currently doesn't visit |
10882 | // addr space qualifiers, so there's no way to write this condition |
10883 | // right now; we just diagnose on everything. |
10884 | S.Diag(SL, DiagID) << QualName << SourceRange(SL); |
10885 | DiagOccured = true; |
10886 | }); |
10887 | if (DiagOccured) |
10888 | D.setInvalidType(); |
10889 | } |
10890 | } |
10891 | |
10892 | /// CheckConstructorDeclarator - Called by ActOnDeclarator to check |
10893 | /// the well-formedness of the constructor declarator @p D with type @p |
10894 | /// R. If there are any errors in the declarator, this routine will |
10895 | /// emit diagnostics and set the invalid bit to true. In any case, the type |
10896 | /// will be updated to reflect a well-formed type for the constructor and |
10897 | /// returned. |
10898 | QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, |
10899 | StorageClass &SC) { |
10900 | bool isVirtual = D.getDeclSpec().isVirtualSpecified(); |
10901 | |
10902 | // C++ [class.ctor]p3: |
10903 | // A constructor shall not be virtual (10.3) or static (9.4). A |
10904 | // constructor can be invoked for a const, volatile or const |
10905 | // volatile object. A constructor shall not be declared const, |
10906 | // volatile, or const volatile (9.3.2). |
10907 | if (isVirtual) { |
10908 | if (!D.isInvalidType()) |
10909 | Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) |
10910 | << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) |
10911 | << SourceRange(D.getIdentifierLoc()); |
10912 | D.setInvalidType(); |
10913 | } |
10914 | if (SC == SC_Static) { |
10915 | if (!D.isInvalidType()) |
10916 | Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) |
10917 | << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) |
10918 | << SourceRange(D.getIdentifierLoc()); |
10919 | D.setInvalidType(); |
10920 | SC = SC_None; |
10921 | } |
10922 | |
10923 | if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { |
10924 | diagnoseIgnoredQualifiers( |
10925 | diag::err_constructor_return_type, TypeQuals, SourceLocation(), |
10926 | D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), |
10927 | D.getDeclSpec().getRestrictSpecLoc(), |
10928 | D.getDeclSpec().getAtomicSpecLoc()); |
10929 | D.setInvalidType(); |
10930 | } |
10931 | |
10932 | checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); |
10933 | |
10934 | // C++0x [class.ctor]p4: |
10935 | // A constructor shall not be declared with a ref-qualifier. |
10936 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); |
10937 | if (FTI.hasRefQualifier()) { |
10938 | Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) |
10939 | << FTI.RefQualifierIsLValueRef |
10940 | << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); |
10941 | D.setInvalidType(); |
10942 | } |
10943 | |
10944 | // Rebuild the function type "R" without any type qualifiers (in |
10945 | // case any of the errors above fired) and with "void" as the |
10946 | // return type, since constructors don't have return types. |
10947 | const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); |
10948 | if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) |
10949 | return R; |
10950 | |
10951 | FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); |
10952 | EPI.TypeQuals = Qualifiers(); |
10953 | EPI.RefQualifier = RQ_None; |
10954 | |
10955 | return Context.getFunctionType(ResultTy: Context.VoidTy, Args: Proto->getParamTypes(), EPI); |
10956 | } |
10957 | |
10958 | /// CheckConstructor - Checks a fully-formed constructor for |
10959 | /// well-formedness, issuing any diagnostics required. Returns true if |
10960 | /// the constructor declarator is invalid. |
10961 | void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { |
10962 | CXXRecordDecl *ClassDecl |
10963 | = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); |
10964 | if (!ClassDecl) |
10965 | return Constructor->setInvalidDecl(); |
10966 | |
10967 | // C++ [class.copy]p3: |
10968 | // A declaration of a constructor for a class X is ill-formed if |
10969 | // its first parameter is of type (optionally cv-qualified) X and |
10970 | // either there are no other parameters or else all other |
10971 | // parameters have default arguments. |
10972 | if (!Constructor->isInvalidDecl() && |
10973 | Constructor->hasOneParamOrDefaultArgs() && |
10974 | Constructor->getTemplateSpecializationKind() != |
10975 | TSK_ImplicitInstantiation) { |
10976 | QualType ParamType = Constructor->getParamDecl(0)->getType(); |
10977 | QualType ClassTy = Context.getTagDeclType(ClassDecl); |
10978 | if (Context.getCanonicalType(T: ParamType).getUnqualifiedType() == ClassTy) { |
10979 | SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); |
10980 | const char *ConstRef |
10981 | = Constructor->getParamDecl(0)->getIdentifier() ? "const &" |
10982 | : " const &" ; |
10983 | Diag(ParamLoc, diag::err_constructor_byvalue_arg) |
10984 | << FixItHint::CreateInsertion(ParamLoc, ConstRef); |
10985 | |
10986 | // FIXME: Rather that making the constructor invalid, we should endeavor |
10987 | // to fix the type. |
10988 | Constructor->setInvalidDecl(); |
10989 | } |
10990 | } |
10991 | } |
10992 | |
10993 | /// CheckDestructor - Checks a fully-formed destructor definition for |
10994 | /// well-formedness, issuing any diagnostics required. Returns true |
10995 | /// on error. |
10996 | bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { |
10997 | CXXRecordDecl *RD = Destructor->getParent(); |
10998 | |
10999 | if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { |
11000 | SourceLocation Loc; |
11001 | |
11002 | if (!Destructor->isImplicit()) |
11003 | Loc = Destructor->getLocation(); |
11004 | else |
11005 | Loc = RD->getLocation(); |
11006 | |
11007 | // If we have a virtual destructor, look up the deallocation function |
11008 | if (FunctionDecl *OperatorDelete = |
11009 | FindDeallocationFunctionForDestructor(StartLoc: Loc, RD)) { |
11010 | Expr *ThisArg = nullptr; |
11011 | |
11012 | // If the notional 'delete this' expression requires a non-trivial |
11013 | // conversion from 'this' to the type of a destroying operator delete's |
11014 | // first parameter, perform that conversion now. |
11015 | if (OperatorDelete->isDestroyingOperatorDelete()) { |
11016 | QualType ParamType = OperatorDelete->getParamDecl(i: 0)->getType(); |
11017 | if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { |
11018 | // C++ [class.dtor]p13: |
11019 | // ... as if for the expression 'delete this' appearing in a |
11020 | // non-virtual destructor of the destructor's class. |
11021 | ContextRAII SwitchContext(*this, Destructor); |
11022 | ExprResult This = |
11023 | ActOnCXXThis(Loc: OperatorDelete->getParamDecl(i: 0)->getLocation()); |
11024 | assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?" ); |
11025 | This = PerformImplicitConversion(From: This.get(), ToType: ParamType, Action: AA_Passing); |
11026 | if (This.isInvalid()) { |
11027 | // FIXME: Register this as a context note so that it comes out |
11028 | // in the right order. |
11029 | Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); |
11030 | return true; |
11031 | } |
11032 | ThisArg = This.get(); |
11033 | } |
11034 | } |
11035 | |
11036 | DiagnoseUseOfDecl(OperatorDelete, Loc); |
11037 | MarkFunctionReferenced(Loc, Func: OperatorDelete); |
11038 | Destructor->setOperatorDelete(OD: OperatorDelete, ThisArg); |
11039 | } |
11040 | } |
11041 | |
11042 | return false; |
11043 | } |
11044 | |
11045 | /// CheckDestructorDeclarator - Called by ActOnDeclarator to check |
11046 | /// the well-formednes of the destructor declarator @p D with type @p |
11047 | /// R. If there are any errors in the declarator, this routine will |
11048 | /// emit diagnostics and set the declarator to invalid. Even if this happens, |
11049 | /// will be updated to reflect a well-formed type for the destructor and |
11050 | /// returned. |
11051 | QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, |
11052 | StorageClass& SC) { |
11053 | // C++ [class.dtor]p1: |
11054 | // [...] A typedef-name that names a class is a class-name |
11055 | // (7.1.3); however, a typedef-name that names a class shall not |
11056 | // be used as the identifier in the declarator for a destructor |
11057 | // declaration. |
11058 | QualType DeclaratorType = GetTypeFromParser(Ty: D.getName().DestructorName); |
11059 | if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) |
11060 | Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) |
11061 | << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); |
11062 | else if (const TemplateSpecializationType *TST = |
11063 | DeclaratorType->getAs<TemplateSpecializationType>()) |
11064 | if (TST->isTypeAlias()) |
11065 | Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) |
11066 | << DeclaratorType << 1; |
11067 | |
11068 | // C++ [class.dtor]p2: |
11069 | // A destructor is used to destroy objects of its class type. A |
11070 | // destructor takes no parameters, and no return type can be |
11071 | // specified for it (not even void). The address of a destructor |
11072 | // shall not be taken. A destructor shall not be static. A |
11073 | // destructor can be invoked for a const, volatile or const |
11074 | // volatile object. A destructor shall not be declared const, |
11075 | // volatile or const volatile (9.3.2). |
11076 | if (SC == SC_Static) { |
11077 | if (!D.isInvalidType()) |
11078 | Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) |
11079 | << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) |
11080 | << SourceRange(D.getIdentifierLoc()) |
11081 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); |
11082 | |
11083 | SC = SC_None; |
11084 | } |
11085 | if (!D.isInvalidType()) { |
11086 | // Destructors don't have return types, but the parser will |
11087 | // happily parse something like: |
11088 | // |
11089 | // class X { |
11090 | // float ~X(); |
11091 | // }; |
11092 | // |
11093 | // The return type will be eliminated later. |
11094 | if (D.getDeclSpec().hasTypeSpecifier()) |
11095 | Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) |
11096 | << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) |
11097 | << SourceRange(D.getIdentifierLoc()); |
11098 | else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { |
11099 | diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, |
11100 | SourceLocation(), |
11101 | D.getDeclSpec().getConstSpecLoc(), |
11102 | D.getDeclSpec().getVolatileSpecLoc(), |
11103 | D.getDeclSpec().getRestrictSpecLoc(), |
11104 | D.getDeclSpec().getAtomicSpecLoc()); |
11105 | D.setInvalidType(); |
11106 | } |
11107 | } |
11108 | |
11109 | checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); |
11110 | |
11111 | // C++0x [class.dtor]p2: |
11112 | // A destructor shall not be declared with a ref-qualifier. |
11113 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); |
11114 | if (FTI.hasRefQualifier()) { |
11115 | Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) |
11116 | << FTI.RefQualifierIsLValueRef |
11117 | << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); |
11118 | D.setInvalidType(); |
11119 | } |
11120 | |
11121 | // Make sure we don't have any parameters. |
11122 | if (FTIHasNonVoidParameters(FTI)) { |
11123 | Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); |
11124 | |
11125 | // Delete the parameters. |
11126 | FTI.freeParams(); |
11127 | D.setInvalidType(); |
11128 | } |
11129 | |
11130 | // Make sure the destructor isn't variadic. |
11131 | if (FTI.isVariadic) { |
11132 | Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); |
11133 | D.setInvalidType(); |
11134 | } |
11135 | |
11136 | // Rebuild the function type "R" without any type qualifiers or |
11137 | // parameters (in case any of the errors above fired) and with |
11138 | // "void" as the return type, since destructors don't have return |
11139 | // types. |
11140 | if (!D.isInvalidType()) |
11141 | return R; |
11142 | |
11143 | const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); |
11144 | FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); |
11145 | EPI.Variadic = false; |
11146 | EPI.TypeQuals = Qualifiers(); |
11147 | EPI.RefQualifier = RQ_None; |
11148 | return Context.getFunctionType(ResultTy: Context.VoidTy, Args: std::nullopt, EPI); |
11149 | } |
11150 | |
11151 | static void extendLeft(SourceRange &R, SourceRange Before) { |
11152 | if (Before.isInvalid()) |
11153 | return; |
11154 | R.setBegin(Before.getBegin()); |
11155 | if (R.getEnd().isInvalid()) |
11156 | R.setEnd(Before.getEnd()); |
11157 | } |
11158 | |
11159 | static void extendRight(SourceRange &R, SourceRange After) { |
11160 | if (After.isInvalid()) |
11161 | return; |
11162 | if (R.getBegin().isInvalid()) |
11163 | R.setBegin(After.getBegin()); |
11164 | R.setEnd(After.getEnd()); |
11165 | } |
11166 | |
11167 | /// CheckConversionDeclarator - Called by ActOnDeclarator to check the |
11168 | /// well-formednes of the conversion function declarator @p D with |
11169 | /// type @p R. If there are any errors in the declarator, this routine |
11170 | /// will emit diagnostics and return true. Otherwise, it will return |
11171 | /// false. Either way, the type @p R will be updated to reflect a |
11172 | /// well-formed type for the conversion operator. |
11173 | void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, |
11174 | StorageClass& SC) { |
11175 | // C++ [class.conv.fct]p1: |
11176 | // Neither parameter types nor return type can be specified. The |
11177 | // type of a conversion function (8.3.5) is "function taking no |
11178 | // parameter returning conversion-type-id." |
11179 | if (SC == SC_Static) { |
11180 | if (!D.isInvalidType()) |
11181 | Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) |
11182 | << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) |
11183 | << D.getName().getSourceRange(); |
11184 | D.setInvalidType(); |
11185 | SC = SC_None; |
11186 | } |
11187 | |
11188 | TypeSourceInfo *ConvTSI = nullptr; |
11189 | QualType ConvType = |
11190 | GetTypeFromParser(Ty: D.getName().ConversionFunctionId, TInfo: &ConvTSI); |
11191 | |
11192 | const DeclSpec &DS = D.getDeclSpec(); |
11193 | if (DS.hasTypeSpecifier() && !D.isInvalidType()) { |
11194 | // Conversion functions don't have return types, but the parser will |
11195 | // happily parse something like: |
11196 | // |
11197 | // class X { |
11198 | // float operator bool(); |
11199 | // }; |
11200 | // |
11201 | // The return type will be changed later anyway. |
11202 | Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) |
11203 | << SourceRange(DS.getTypeSpecTypeLoc()) |
11204 | << SourceRange(D.getIdentifierLoc()); |
11205 | D.setInvalidType(); |
11206 | } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { |
11207 | // It's also plausible that the user writes type qualifiers in the wrong |
11208 | // place, such as: |
11209 | // struct S { const operator int(); }; |
11210 | // FIXME: we could provide a fixit to move the qualifiers onto the |
11211 | // conversion type. |
11212 | Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) |
11213 | << SourceRange(D.getIdentifierLoc()) << 0; |
11214 | D.setInvalidType(); |
11215 | } |
11216 | const auto *Proto = R->castAs<FunctionProtoType>(); |
11217 | // Make sure we don't have any parameters. |
11218 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); |
11219 | unsigned NumParam = Proto->getNumParams(); |
11220 | |
11221 | // [C++2b] |
11222 | // A conversion function shall have no non-object parameters. |
11223 | if (NumParam == 1) { |
11224 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); |
11225 | if (const auto *First = |
11226 | dyn_cast_if_present<ParmVarDecl>(Val: FTI.Params[0].Param); |
11227 | First && First->isExplicitObjectParameter()) |
11228 | NumParam--; |
11229 | } |
11230 | |
11231 | if (NumParam != 0) { |
11232 | Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); |
11233 | // Delete the parameters. |
11234 | FTI.freeParams(); |
11235 | D.setInvalidType(); |
11236 | } else if (Proto->isVariadic()) { |
11237 | Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); |
11238 | D.setInvalidType(); |
11239 | } |
11240 | |
11241 | // Diagnose "&operator bool()" and other such nonsense. This |
11242 | // is actually a gcc extension which we don't support. |
11243 | if (Proto->getReturnType() != ConvType) { |
11244 | bool NeedsTypedef = false; |
11245 | SourceRange Before, After; |
11246 | |
11247 | // Walk the chunks and extract information on them for our diagnostic. |
11248 | bool PastFunctionChunk = false; |
11249 | for (auto &Chunk : D.type_objects()) { |
11250 | switch (Chunk.Kind) { |
11251 | case DeclaratorChunk::Function: |
11252 | if (!PastFunctionChunk) { |
11253 | if (Chunk.Fun.HasTrailingReturnType) { |
11254 | TypeSourceInfo *TRT = nullptr; |
11255 | GetTypeFromParser(Ty: Chunk.Fun.getTrailingReturnType(), TInfo: &TRT); |
11256 | if (TRT) extendRight(R&: After, After: TRT->getTypeLoc().getSourceRange()); |
11257 | } |
11258 | PastFunctionChunk = true; |
11259 | break; |
11260 | } |
11261 | [[fallthrough]]; |
11262 | case DeclaratorChunk::Array: |
11263 | NeedsTypedef = true; |
11264 | extendRight(R&: After, After: Chunk.getSourceRange()); |
11265 | break; |
11266 | |
11267 | case DeclaratorChunk::Pointer: |
11268 | case DeclaratorChunk::BlockPointer: |
11269 | case DeclaratorChunk::Reference: |
11270 | case DeclaratorChunk::MemberPointer: |
11271 | case DeclaratorChunk::Pipe: |
11272 | extendLeft(R&: Before, Before: Chunk.getSourceRange()); |
11273 | break; |
11274 | |
11275 | case DeclaratorChunk::Paren: |
11276 | extendLeft(R&: Before, Before: Chunk.Loc); |
11277 | extendRight(R&: After, After: Chunk.EndLoc); |
11278 | break; |
11279 | } |
11280 | } |
11281 | |
11282 | SourceLocation Loc = Before.isValid() ? Before.getBegin() : |
11283 | After.isValid() ? After.getBegin() : |
11284 | D.getIdentifierLoc(); |
11285 | auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); |
11286 | DB << Before << After; |
11287 | |
11288 | if (!NeedsTypedef) { |
11289 | DB << /*don't need a typedef*/0; |
11290 | |
11291 | // If we can provide a correct fix-it hint, do so. |
11292 | if (After.isInvalid() && ConvTSI) { |
11293 | SourceLocation InsertLoc = |
11294 | getLocForEndOfToken(Loc: ConvTSI->getTypeLoc().getEndLoc()); |
11295 | DB << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " " ) |
11296 | << FixItHint::CreateInsertionFromRange( |
11297 | InsertionLoc: InsertLoc, FromRange: CharSourceRange::getTokenRange(R: Before)) |
11298 | << FixItHint::CreateRemoval(RemoveRange: Before); |
11299 | } |
11300 | } else if (!Proto->getReturnType()->isDependentType()) { |
11301 | DB << /*typedef*/1 << Proto->getReturnType(); |
11302 | } else if (getLangOpts().CPlusPlus11) { |
11303 | DB << /*alias template*/2 << Proto->getReturnType(); |
11304 | } else { |
11305 | DB << /*might not be fixable*/3; |
11306 | } |
11307 | |
11308 | // Recover by incorporating the other type chunks into the result type. |
11309 | // Note, this does *not* change the name of the function. This is compatible |
11310 | // with the GCC extension: |
11311 | // struct S { &operator int(); } s; |
11312 | // int &r = s.operator int(); // ok in GCC |
11313 | // S::operator int&() {} // error in GCC, function name is 'operator int'. |
11314 | ConvType = Proto->getReturnType(); |
11315 | } |
11316 | |
11317 | // C++ [class.conv.fct]p4: |
11318 | // The conversion-type-id shall not represent a function type nor |
11319 | // an array type. |
11320 | if (ConvType->isArrayType()) { |
11321 | Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); |
11322 | ConvType = Context.getPointerType(T: ConvType); |
11323 | D.setInvalidType(); |
11324 | } else if (ConvType->isFunctionType()) { |
11325 | Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); |
11326 | ConvType = Context.getPointerType(T: ConvType); |
11327 | D.setInvalidType(); |
11328 | } |
11329 | |
11330 | // Rebuild the function type "R" without any parameters (in case any |
11331 | // of the errors above fired) and with the conversion type as the |
11332 | // return type. |
11333 | if (D.isInvalidType()) |
11334 | R = Context.getFunctionType(ResultTy: ConvType, Args: std::nullopt, |
11335 | EPI: Proto->getExtProtoInfo()); |
11336 | |
11337 | // C++0x explicit conversion operators. |
11338 | if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) |
11339 | Diag(DS.getExplicitSpecLoc(), |
11340 | getLangOpts().CPlusPlus11 |
11341 | ? diag::warn_cxx98_compat_explicit_conversion_functions |
11342 | : diag::ext_explicit_conversion_functions) |
11343 | << SourceRange(DS.getExplicitSpecRange()); |
11344 | } |
11345 | |
11346 | /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete |
11347 | /// the declaration of the given C++ conversion function. This routine |
11348 | /// is responsible for recording the conversion function in the C++ |
11349 | /// class, if possible. |
11350 | Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { |
11351 | assert(Conversion && "Expected to receive a conversion function declaration" ); |
11352 | |
11353 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); |
11354 | |
11355 | // Make sure we aren't redeclaring the conversion function. |
11356 | QualType ConvType = Context.getCanonicalType(T: Conversion->getConversionType()); |
11357 | // C++ [class.conv.fct]p1: |
11358 | // [...] A conversion function is never used to convert a |
11359 | // (possibly cv-qualified) object to the (possibly cv-qualified) |
11360 | // same object type (or a reference to it), to a (possibly |
11361 | // cv-qualified) base class of that type (or a reference to it), |
11362 | // or to (possibly cv-qualified) void. |
11363 | QualType ClassType |
11364 | = Context.getCanonicalType(T: Context.getTypeDeclType(ClassDecl)); |
11365 | if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) |
11366 | ConvType = ConvTypeRef->getPointeeType(); |
11367 | if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && |
11368 | Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) |
11369 | /* Suppress diagnostics for instantiations. */; |
11370 | else if (Conversion->size_overridden_methods() != 0) |
11371 | /* Suppress diagnostics for overriding virtual function in a base class. */; |
11372 | else if (ConvType->isRecordType()) { |
11373 | ConvType = Context.getCanonicalType(T: ConvType).getUnqualifiedType(); |
11374 | if (ConvType == ClassType) |
11375 | Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) |
11376 | << ClassType; |
11377 | else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) |
11378 | Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) |
11379 | << ClassType << ConvType; |
11380 | } else if (ConvType->isVoidType()) { |
11381 | Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) |
11382 | << ClassType << ConvType; |
11383 | } |
11384 | |
11385 | if (FunctionTemplateDecl *ConversionTemplate = |
11386 | Conversion->getDescribedFunctionTemplate()) { |
11387 | if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) { |
11388 | ConvType = ConvTypePtr->getPointeeType(); |
11389 | } |
11390 | if (ConvType->isUndeducedAutoType()) { |
11391 | Diag(Conversion->getTypeSpecStartLoc(), diag::err_auto_not_allowed) |
11392 | << getReturnTypeLoc(Conversion).getSourceRange() |
11393 | << llvm::to_underlying(ConvType->castAs<AutoType>()->getKeyword()) |
11394 | << /* in declaration of conversion function template= */ 24; |
11395 | } |
11396 | |
11397 | return ConversionTemplate; |
11398 | } |
11399 | |
11400 | return Conversion; |
11401 | } |
11402 | |
11403 | void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D, |
11404 | DeclarationName Name, QualType R) { |
11405 | CheckExplicitObjectMemberFunction(D, Name, R, IsLambda: false, DC); |
11406 | } |
11407 | |
11408 | void Sema::CheckExplicitObjectLambda(Declarator &D) { |
11409 | CheckExplicitObjectMemberFunction(D, Name: {}, R: {}, IsLambda: true); |
11410 | } |
11411 | |
11412 | void Sema::CheckExplicitObjectMemberFunction(Declarator &D, |
11413 | DeclarationName Name, QualType R, |
11414 | bool IsLambda, DeclContext *DC) { |
11415 | if (!D.isFunctionDeclarator()) |
11416 | return; |
11417 | |
11418 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); |
11419 | if (FTI.NumParams == 0) |
11420 | return; |
11421 | ParmVarDecl *ExplicitObjectParam = nullptr; |
11422 | for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) { |
11423 | const auto &ParamInfo = FTI.Params[Idx]; |
11424 | if (!ParamInfo.Param) |
11425 | continue; |
11426 | ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamInfo.Param); |
11427 | if (!Param->isExplicitObjectParameter()) |
11428 | continue; |
11429 | if (Idx == 0) { |
11430 | ExplicitObjectParam = Param; |
11431 | continue; |
11432 | } else { |
11433 | Diag(Param->getLocation(), |
11434 | diag::err_explicit_object_parameter_must_be_first) |
11435 | << IsLambda << Param->getSourceRange(); |
11436 | } |
11437 | } |
11438 | if (!ExplicitObjectParam) |
11439 | return; |
11440 | |
11441 | if (ExplicitObjectParam->hasDefaultArg()) { |
11442 | Diag(ExplicitObjectParam->getLocation(), |
11443 | diag::err_explicit_object_default_arg) |
11444 | << ExplicitObjectParam->getSourceRange(); |
11445 | } |
11446 | |
11447 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static || |
11448 | (D.getContext() == clang::DeclaratorContext::Member && |
11449 | D.isStaticMember())) { |
11450 | Diag(ExplicitObjectParam->getBeginLoc(), |
11451 | diag::err_explicit_object_parameter_nonmember) |
11452 | << D.getSourceRange() << /*static=*/0 << IsLambda; |
11453 | D.setInvalidType(); |
11454 | } |
11455 | |
11456 | if (D.getDeclSpec().isVirtualSpecified()) { |
11457 | Diag(ExplicitObjectParam->getBeginLoc(), |
11458 | diag::err_explicit_object_parameter_nonmember) |
11459 | << D.getSourceRange() << /*virtual=*/1 << IsLambda; |
11460 | D.setInvalidType(); |
11461 | } |
11462 | |
11463 | if (IsLambda && FTI.hasMutableQualifier()) { |
11464 | Diag(ExplicitObjectParam->getBeginLoc(), |
11465 | diag::err_explicit_object_parameter_mutable) |
11466 | << D.getSourceRange(); |
11467 | } |
11468 | |
11469 | if (IsLambda) |
11470 | return; |
11471 | |
11472 | if (!DC || !DC->isRecord()) { |
11473 | Diag(ExplicitObjectParam->getLocation(), |
11474 | diag::err_explicit_object_parameter_nonmember) |
11475 | << D.getSourceRange() << /*non-member=*/2 << IsLambda; |
11476 | D.setInvalidType(); |
11477 | return; |
11478 | } |
11479 | |
11480 | // CWG2674: constructors and destructors cannot have explicit parameters. |
11481 | if (Name.getNameKind() == DeclarationName::CXXConstructorName || |
11482 | Name.getNameKind() == DeclarationName::CXXDestructorName) { |
11483 | Diag(ExplicitObjectParam->getBeginLoc(), |
11484 | diag::err_explicit_object_parameter_constructor) |
11485 | << (Name.getNameKind() == DeclarationName::CXXDestructorName) |
11486 | << D.getSourceRange(); |
11487 | D.setInvalidType(); |
11488 | } |
11489 | } |
11490 | |
11491 | namespace { |
11492 | /// Utility class to accumulate and print a diagnostic listing the invalid |
11493 | /// specifier(s) on a declaration. |
11494 | struct BadSpecifierDiagnoser { |
11495 | BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) |
11496 | : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} |
11497 | ~BadSpecifierDiagnoser() { |
11498 | Diagnostic << Specifiers; |
11499 | } |
11500 | |
11501 | template<typename T> void check(SourceLocation SpecLoc, T Spec) { |
11502 | return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); |
11503 | } |
11504 | void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { |
11505 | return check(SpecLoc, |
11506 | Spec: DeclSpec::getSpecifierName(T: Spec, Policy: S.getPrintingPolicy())); |
11507 | } |
11508 | void check(SourceLocation SpecLoc, const char *Spec) { |
11509 | if (SpecLoc.isInvalid()) return; |
11510 | Diagnostic << SourceRange(SpecLoc, SpecLoc); |
11511 | if (!Specifiers.empty()) Specifiers += " " ; |
11512 | Specifiers += Spec; |
11513 | } |
11514 | |
11515 | Sema &S; |
11516 | Sema::SemaDiagnosticBuilder Diagnostic; |
11517 | std::string Specifiers; |
11518 | }; |
11519 | } |
11520 | |
11521 | /// Check the validity of a declarator that we parsed for a deduction-guide. |
11522 | /// These aren't actually declarators in the grammar, so we need to check that |
11523 | /// the user didn't specify any pieces that are not part of the deduction-guide |
11524 | /// grammar. Return true on invalid deduction-guide. |
11525 | bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, |
11526 | StorageClass &SC) { |
11527 | TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); |
11528 | TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); |
11529 | assert(GuidedTemplateDecl && "missing template decl for deduction guide" ); |
11530 | |
11531 | // C++ [temp.deduct.guide]p3: |
11532 | // A deduction-gide shall be declared in the same scope as the |
11533 | // corresponding class template. |
11534 | if (!CurContext->getRedeclContext()->Equals( |
11535 | DC: GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { |
11536 | Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) |
11537 | << GuidedTemplateDecl; |
11538 | NoteTemplateLocation(*GuidedTemplateDecl); |
11539 | } |
11540 | |
11541 | auto &DS = D.getMutableDeclSpec(); |
11542 | // We leave 'friend' and 'virtual' to be rejected in the normal way. |
11543 | if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || |
11544 | DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || |
11545 | DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { |
11546 | BadSpecifierDiagnoser Diagnoser( |
11547 | *this, D.getIdentifierLoc(), |
11548 | diag::err_deduction_guide_invalid_specifier); |
11549 | |
11550 | Diagnoser.check(SpecLoc: DS.getStorageClassSpecLoc(), Spec: DS.getStorageClassSpec()); |
11551 | DS.ClearStorageClassSpecs(); |
11552 | SC = SC_None; |
11553 | |
11554 | // 'explicit' is permitted. |
11555 | Diagnoser.check(SpecLoc: DS.getInlineSpecLoc(), Spec: "inline" ); |
11556 | Diagnoser.check(SpecLoc: DS.getNoreturnSpecLoc(), Spec: "_Noreturn" ); |
11557 | Diagnoser.check(SpecLoc: DS.getConstexprSpecLoc(), Spec: "constexpr" ); |
11558 | DS.ClearConstexprSpec(); |
11559 | |
11560 | Diagnoser.check(SpecLoc: DS.getConstSpecLoc(), Spec: "const" ); |
11561 | Diagnoser.check(SpecLoc: DS.getRestrictSpecLoc(), Spec: "__restrict" ); |
11562 | Diagnoser.check(SpecLoc: DS.getVolatileSpecLoc(), Spec: "volatile" ); |
11563 | Diagnoser.check(SpecLoc: DS.getAtomicSpecLoc(), Spec: "_Atomic" ); |
11564 | Diagnoser.check(SpecLoc: DS.getUnalignedSpecLoc(), Spec: "__unaligned" ); |
11565 | DS.ClearTypeQualifiers(); |
11566 | |
11567 | Diagnoser.check(SpecLoc: DS.getTypeSpecComplexLoc(), Spec: DS.getTypeSpecComplex()); |
11568 | Diagnoser.check(SpecLoc: DS.getTypeSpecSignLoc(), Spec: DS.getTypeSpecSign()); |
11569 | Diagnoser.check(SpecLoc: DS.getTypeSpecWidthLoc(), Spec: DS.getTypeSpecWidth()); |
11570 | Diagnoser.check(SpecLoc: DS.getTypeSpecTypeLoc(), Spec: DS.getTypeSpecType()); |
11571 | DS.ClearTypeSpecType(); |
11572 | } |
11573 | |
11574 | if (D.isInvalidType()) |
11575 | return true; |
11576 | |
11577 | // Check the declarator is simple enough. |
11578 | bool FoundFunction = false; |
11579 | for (const DeclaratorChunk &Chunk : llvm::reverse(C: D.type_objects())) { |
11580 | if (Chunk.Kind == DeclaratorChunk::Paren) |
11581 | continue; |
11582 | if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { |
11583 | Diag(D.getDeclSpec().getBeginLoc(), |
11584 | diag::err_deduction_guide_with_complex_decl) |
11585 | << D.getSourceRange(); |
11586 | break; |
11587 | } |
11588 | if (!Chunk.Fun.hasTrailingReturnType()) |
11589 | return Diag(D.getName().getBeginLoc(), |
11590 | diag::err_deduction_guide_no_trailing_return_type); |
11591 | |
11592 | // Check that the return type is written as a specialization of |
11593 | // the template specified as the deduction-guide's name. |
11594 | // The template name may not be qualified. [temp.deduct.guide] |
11595 | ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); |
11596 | TypeSourceInfo *TSI = nullptr; |
11597 | QualType RetTy = GetTypeFromParser(Ty: TrailingReturnType, TInfo: &TSI); |
11598 | assert(TSI && "deduction guide has valid type but invalid return type?" ); |
11599 | bool AcceptableReturnType = false; |
11600 | bool MightInstantiateToSpecialization = false; |
11601 | if (auto RetTST = |
11602 | TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) { |
11603 | TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); |
11604 | bool TemplateMatches = |
11605 | Context.hasSameTemplateName(X: SpecifiedName, Y: GuidedTemplate); |
11606 | auto TKind = SpecifiedName.getKind(); |
11607 | // A Using TemplateName can't actually be valid (either it's qualified, or |
11608 | // we're in the wrong scope). But we have diagnosed these problems |
11609 | // already. |
11610 | bool SimplyWritten = TKind == TemplateName::Template || |
11611 | TKind == TemplateName::UsingTemplate; |
11612 | if (SimplyWritten && TemplateMatches) |
11613 | AcceptableReturnType = true; |
11614 | else { |
11615 | // This could still instantiate to the right type, unless we know it |
11616 | // names the wrong class template. |
11617 | auto *TD = SpecifiedName.getAsTemplateDecl(); |
11618 | MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && |
11619 | !TemplateMatches); |
11620 | } |
11621 | } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { |
11622 | MightInstantiateToSpecialization = true; |
11623 | } |
11624 | |
11625 | if (!AcceptableReturnType) |
11626 | return Diag(TSI->getTypeLoc().getBeginLoc(), |
11627 | diag::err_deduction_guide_bad_trailing_return_type) |
11628 | << GuidedTemplate << TSI->getType() |
11629 | << MightInstantiateToSpecialization |
11630 | << TSI->getTypeLoc().getSourceRange(); |
11631 | |
11632 | // Keep going to check that we don't have any inner declarator pieces (we |
11633 | // could still have a function returning a pointer to a function). |
11634 | FoundFunction = true; |
11635 | } |
11636 | |
11637 | if (D.isFunctionDefinition()) |
11638 | // we can still create a valid deduction guide here. |
11639 | Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); |
11640 | return false; |
11641 | } |
11642 | |
11643 | //===----------------------------------------------------------------------===// |
11644 | // Namespace Handling |
11645 | //===----------------------------------------------------------------------===// |
11646 | |
11647 | /// Diagnose a mismatch in 'inline' qualifiers when a namespace is |
11648 | /// reopened. |
11649 | static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, |
11650 | SourceLocation Loc, |
11651 | IdentifierInfo *II, bool *IsInline, |
11652 | NamespaceDecl *PrevNS) { |
11653 | assert(*IsInline != PrevNS->isInline()); |
11654 | |
11655 | // 'inline' must appear on the original definition, but not necessarily |
11656 | // on all extension definitions, so the note should point to the first |
11657 | // definition to avoid confusion. |
11658 | PrevNS = PrevNS->getFirstDecl(); |
11659 | |
11660 | if (PrevNS->isInline()) |
11661 | // The user probably just forgot the 'inline', so suggest that it |
11662 | // be added back. |
11663 | S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) |
11664 | << FixItHint::CreateInsertion(KeywordLoc, "inline " ); |
11665 | else |
11666 | S.Diag(Loc, diag::err_inline_namespace_mismatch); |
11667 | |
11668 | S.Diag(PrevNS->getLocation(), diag::note_previous_definition); |
11669 | *IsInline = PrevNS->isInline(); |
11670 | } |
11671 | |
11672 | /// ActOnStartNamespaceDef - This is called at the start of a namespace |
11673 | /// definition. |
11674 | Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope, |
11675 | SourceLocation InlineLoc, |
11676 | SourceLocation NamespaceLoc, |
11677 | SourceLocation IdentLoc, IdentifierInfo *II, |
11678 | SourceLocation LBrace, |
11679 | const ParsedAttributesView &AttrList, |
11680 | UsingDirectiveDecl *&UD, bool IsNested) { |
11681 | SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; |
11682 | // For anonymous namespace, take the location of the left brace. |
11683 | SourceLocation Loc = II ? IdentLoc : LBrace; |
11684 | bool IsInline = InlineLoc.isValid(); |
11685 | bool IsInvalid = false; |
11686 | bool IsStd = false; |
11687 | bool AddToKnown = false; |
11688 | Scope *DeclRegionScope = NamespcScope->getParent(); |
11689 | |
11690 | NamespaceDecl *PrevNS = nullptr; |
11691 | if (II) { |
11692 | // C++ [namespace.std]p7: |
11693 | // A translation unit shall not declare namespace std to be an inline |
11694 | // namespace (9.8.2). |
11695 | // |
11696 | // Precondition: the std namespace is in the file scope and is declared to |
11697 | // be inline |
11698 | auto DiagnoseInlineStdNS = [&]() { |
11699 | assert(IsInline && II->isStr("std" ) && |
11700 | CurContext->getRedeclContext()->isTranslationUnit() && |
11701 | "Precondition of DiagnoseInlineStdNS not met" ); |
11702 | Diag(InlineLoc, diag::err_inline_namespace_std) |
11703 | << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(6)); |
11704 | IsInline = false; |
11705 | }; |
11706 | // C++ [namespace.def]p2: |
11707 | // The identifier in an original-namespace-definition shall not |
11708 | // have been previously defined in the declarative region in |
11709 | // which the original-namespace-definition appears. The |
11710 | // identifier in an original-namespace-definition is the name of |
11711 | // the namespace. Subsequently in that declarative region, it is |
11712 | // treated as an original-namespace-name. |
11713 | // |
11714 | // Since namespace names are unique in their scope, and we don't |
11715 | // look through using directives, just look for any ordinary names |
11716 | // as if by qualified name lookup. |
11717 | LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, |
11718 | RedeclarationKind::ForExternalRedeclaration); |
11719 | LookupQualifiedName(R, LookupCtx: CurContext->getRedeclContext()); |
11720 | NamedDecl *PrevDecl = |
11721 | R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; |
11722 | PrevNS = dyn_cast_or_null<NamespaceDecl>(Val: PrevDecl); |
11723 | |
11724 | if (PrevNS) { |
11725 | // This is an extended namespace definition. |
11726 | if (IsInline && II->isStr(Str: "std" ) && |
11727 | CurContext->getRedeclContext()->isTranslationUnit()) |
11728 | DiagnoseInlineStdNS(); |
11729 | else if (IsInline != PrevNS->isInline()) |
11730 | DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc, II, |
11731 | IsInline: &IsInline, PrevNS); |
11732 | } else if (PrevDecl) { |
11733 | // This is an invalid name redefinition. |
11734 | Diag(Loc, diag::err_redefinition_different_kind) |
11735 | << II; |
11736 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); |
11737 | IsInvalid = true; |
11738 | // Continue on to push Namespc as current DeclContext and return it. |
11739 | } else if (II->isStr(Str: "std" ) && |
11740 | CurContext->getRedeclContext()->isTranslationUnit()) { |
11741 | if (IsInline) |
11742 | DiagnoseInlineStdNS(); |
11743 | // This is the first "real" definition of the namespace "std", so update |
11744 | // our cache of the "std" namespace to point at this definition. |
11745 | PrevNS = getStdNamespace(); |
11746 | IsStd = true; |
11747 | AddToKnown = !IsInline; |
11748 | } else { |
11749 | // We've seen this namespace for the first time. |
11750 | AddToKnown = !IsInline; |
11751 | } |
11752 | } else { |
11753 | // Anonymous namespaces. |
11754 | |
11755 | // Determine whether the parent already has an anonymous namespace. |
11756 | DeclContext *Parent = CurContext->getRedeclContext(); |
11757 | if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) { |
11758 | PrevNS = TU->getAnonymousNamespace(); |
11759 | } else { |
11760 | NamespaceDecl *ND = cast<NamespaceDecl>(Val: Parent); |
11761 | PrevNS = ND->getAnonymousNamespace(); |
11762 | } |
11763 | |
11764 | if (PrevNS && IsInline != PrevNS->isInline()) |
11765 | DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc: NamespaceLoc, II, |
11766 | IsInline: &IsInline, PrevNS); |
11767 | } |
11768 | |
11769 | NamespaceDecl *Namespc = NamespaceDecl::Create( |
11770 | C&: Context, DC: CurContext, Inline: IsInline, StartLoc, IdLoc: Loc, Id: II, PrevDecl: PrevNS, Nested: IsNested); |
11771 | if (IsInvalid) |
11772 | Namespc->setInvalidDecl(); |
11773 | |
11774 | ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); |
11775 | AddPragmaAttributes(DeclRegionScope, Namespc); |
11776 | ProcessAPINotes(Namespc); |
11777 | |
11778 | // FIXME: Should we be merging attributes? |
11779 | if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) |
11780 | PushNamespaceVisibilityAttr(Attr, Loc); |
11781 | |
11782 | if (IsStd) |
11783 | StdNamespace = Namespc; |
11784 | if (AddToKnown) |
11785 | KnownNamespaces[Namespc] = false; |
11786 | |
11787 | if (II) { |
11788 | PushOnScopeChains(Namespc, DeclRegionScope); |
11789 | } else { |
11790 | // Link the anonymous namespace into its parent. |
11791 | DeclContext *Parent = CurContext->getRedeclContext(); |
11792 | if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) { |
11793 | TU->setAnonymousNamespace(Namespc); |
11794 | } else { |
11795 | cast<NamespaceDecl>(Val: Parent)->setAnonymousNamespace(Namespc); |
11796 | } |
11797 | |
11798 | CurContext->addDecl(Namespc); |
11799 | |
11800 | // C++ [namespace.unnamed]p1. An unnamed-namespace-definition |
11801 | // behaves as if it were replaced by |
11802 | // namespace unique { /* empty body */ } |
11803 | // using namespace unique; |
11804 | // namespace unique { namespace-body } |
11805 | // where all occurrences of 'unique' in a translation unit are |
11806 | // replaced by the same identifier and this identifier differs |
11807 | // from all other identifiers in the entire program. |
11808 | |
11809 | // We just create the namespace with an empty name and then add an |
11810 | // implicit using declaration, just like the standard suggests. |
11811 | // |
11812 | // CodeGen enforces the "universally unique" aspect by giving all |
11813 | // declarations semantically contained within an anonymous |
11814 | // namespace internal linkage. |
11815 | |
11816 | if (!PrevNS) { |
11817 | UD = UsingDirectiveDecl::Create(Context, Parent, |
11818 | /* 'using' */ LBrace, |
11819 | /* 'namespace' */ SourceLocation(), |
11820 | /* qualifier */ NestedNameSpecifierLoc(), |
11821 | /* identifier */ SourceLocation(), |
11822 | Namespc, |
11823 | /* Ancestor */ Parent); |
11824 | UD->setImplicit(); |
11825 | Parent->addDecl(UD); |
11826 | } |
11827 | } |
11828 | |
11829 | ActOnDocumentableDecl(Namespc); |
11830 | |
11831 | // Although we could have an invalid decl (i.e. the namespace name is a |
11832 | // redefinition), push it as current DeclContext and try to continue parsing. |
11833 | // FIXME: We should be able to push Namespc here, so that the each DeclContext |
11834 | // for the namespace has the declarations that showed up in that particular |
11835 | // namespace definition. |
11836 | PushDeclContext(NamespcScope, Namespc); |
11837 | return Namespc; |
11838 | } |
11839 | |
11840 | /// getNamespaceDecl - Returns the namespace a decl represents. If the decl |
11841 | /// is a namespace alias, returns the namespace it points to. |
11842 | static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { |
11843 | if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(Val: D)) |
11844 | return AD->getNamespace(); |
11845 | return dyn_cast_or_null<NamespaceDecl>(Val: D); |
11846 | } |
11847 | |
11848 | /// ActOnFinishNamespaceDef - This callback is called after a namespace is |
11849 | /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. |
11850 | void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { |
11851 | NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Val: Dcl); |
11852 | assert(Namespc && "Invalid parameter, expected NamespaceDecl" ); |
11853 | Namespc->setRBraceLoc(RBrace); |
11854 | PopDeclContext(); |
11855 | if (Namespc->hasAttr<VisibilityAttr>()) |
11856 | PopPragmaVisibility(IsNamespaceEnd: true, EndLoc: RBrace); |
11857 | // If this namespace contains an export-declaration, export it now. |
11858 | if (DeferredExportedNamespaces.erase(Ptr: Namespc)) |
11859 | Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); |
11860 | } |
11861 | |
11862 | CXXRecordDecl *Sema::getStdBadAlloc() const { |
11863 | return cast_or_null<CXXRecordDecl>( |
11864 | Val: StdBadAlloc.get(Source: Context.getExternalSource())); |
11865 | } |
11866 | |
11867 | EnumDecl *Sema::getStdAlignValT() const { |
11868 | return cast_or_null<EnumDecl>(Val: StdAlignValT.get(Source: Context.getExternalSource())); |
11869 | } |
11870 | |
11871 | NamespaceDecl *Sema::getStdNamespace() const { |
11872 | return cast_or_null<NamespaceDecl>( |
11873 | Val: StdNamespace.get(Source: Context.getExternalSource())); |
11874 | } |
11875 | namespace { |
11876 | |
11877 | enum UnsupportedSTLSelect { |
11878 | USS_InvalidMember, |
11879 | USS_MissingMember, |
11880 | USS_NonTrivial, |
11881 | USS_Other |
11882 | }; |
11883 | |
11884 | struct InvalidSTLDiagnoser { |
11885 | Sema &S; |
11886 | SourceLocation Loc; |
11887 | QualType TyForDiags; |
11888 | |
11889 | QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "" , |
11890 | const VarDecl *VD = nullptr) { |
11891 | { |
11892 | auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) |
11893 | << TyForDiags << ((int)Sel); |
11894 | if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { |
11895 | assert(!Name.empty()); |
11896 | D << Name; |
11897 | } |
11898 | } |
11899 | if (Sel == USS_InvalidMember) { |
11900 | S.Diag(VD->getLocation(), diag::note_var_declared_here) |
11901 | << VD << VD->getSourceRange(); |
11902 | } |
11903 | return QualType(); |
11904 | } |
11905 | }; |
11906 | } // namespace |
11907 | |
11908 | QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, |
11909 | SourceLocation Loc, |
11910 | ComparisonCategoryUsage Usage) { |
11911 | assert(getLangOpts().CPlusPlus && |
11912 | "Looking for comparison category type outside of C++." ); |
11913 | |
11914 | // Use an elaborated type for diagnostics which has a name containing the |
11915 | // prepended 'std' namespace but not any inline namespace names. |
11916 | auto TyForDiags = [&](ComparisonCategoryInfo *Info) { |
11917 | auto *NNS = |
11918 | NestedNameSpecifier::Create(Context, Prefix: nullptr, NS: getStdNamespace()); |
11919 | return Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS, |
11920 | NamedType: Info->getType()); |
11921 | }; |
11922 | |
11923 | // Check if we've already successfully checked the comparison category type |
11924 | // before. If so, skip checking it again. |
11925 | ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); |
11926 | if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { |
11927 | // The only thing we need to check is that the type has a reachable |
11928 | // definition in the current context. |
11929 | if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) |
11930 | return QualType(); |
11931 | |
11932 | return Info->getType(); |
11933 | } |
11934 | |
11935 | // If lookup failed |
11936 | if (!Info) { |
11937 | std::string NameForDiags = "std::" ; |
11938 | NameForDiags += ComparisonCategories::getCategoryString(Kind); |
11939 | Diag(Loc, diag::err_implied_comparison_category_type_not_found) |
11940 | << NameForDiags << (int)Usage; |
11941 | return QualType(); |
11942 | } |
11943 | |
11944 | assert(Info->Kind == Kind); |
11945 | assert(Info->Record); |
11946 | |
11947 | // Update the Record decl in case we encountered a forward declaration on our |
11948 | // first pass. FIXME: This is a bit of a hack. |
11949 | if (Info->Record->hasDefinition()) |
11950 | Info->Record = Info->Record->getDefinition(); |
11951 | |
11952 | if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) |
11953 | return QualType(); |
11954 | |
11955 | InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; |
11956 | |
11957 | if (!Info->Record->isTriviallyCopyable()) |
11958 | return UnsupportedSTLError(USS_NonTrivial); |
11959 | |
11960 | for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { |
11961 | CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); |
11962 | // Tolerate empty base classes. |
11963 | if (Base->isEmpty()) |
11964 | continue; |
11965 | // Reject STL implementations which have at least one non-empty base. |
11966 | return UnsupportedSTLError(); |
11967 | } |
11968 | |
11969 | // Check that the STL has implemented the types using a single integer field. |
11970 | // This expectation allows better codegen for builtin operators. We require: |
11971 | // (1) The class has exactly one field. |
11972 | // (2) The field is an integral or enumeration type. |
11973 | auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); |
11974 | if (std::distance(FIt, FEnd) != 1 || |
11975 | !FIt->getType()->isIntegralOrEnumerationType()) { |
11976 | return UnsupportedSTLError(); |
11977 | } |
11978 | |
11979 | // Build each of the require values and store them in Info. |
11980 | for (ComparisonCategoryResult CCR : |
11981 | ComparisonCategories::getPossibleResultsForType(Type: Kind)) { |
11982 | StringRef MemName = ComparisonCategories::getResultString(Kind: CCR); |
11983 | ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(ValueKind: CCR); |
11984 | |
11985 | if (!ValInfo) |
11986 | return UnsupportedSTLError(USS_MissingMember, MemName); |
11987 | |
11988 | VarDecl *VD = ValInfo->VD; |
11989 | assert(VD && "should not be null!" ); |
11990 | |
11991 | // Attempt to diagnose reasons why the STL definition of this type |
11992 | // might be foobar, including it failing to be a constant expression. |
11993 | // TODO Handle more ways the lookup or result can be invalid. |
11994 | if (!VD->isStaticDataMember() || |
11995 | !VD->isUsableInConstantExpressions(C: Context)) |
11996 | return UnsupportedSTLError(USS_InvalidMember, MemName, VD); |
11997 | |
11998 | // Attempt to evaluate the var decl as a constant expression and extract |
11999 | // the value of its first field as a ICE. If this fails, the STL |
12000 | // implementation is not supported. |
12001 | if (!ValInfo->hasValidIntValue()) |
12002 | return UnsupportedSTLError(); |
12003 | |
12004 | MarkVariableReferenced(Loc, Var: VD); |
12005 | } |
12006 | |
12007 | // We've successfully built the required types and expressions. Update |
12008 | // the cache and return the newly cached value. |
12009 | FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; |
12010 | return Info->getType(); |
12011 | } |
12012 | |
12013 | /// Retrieve the special "std" namespace, which may require us to |
12014 | /// implicitly define the namespace. |
12015 | NamespaceDecl *Sema::getOrCreateStdNamespace() { |
12016 | if (!StdNamespace) { |
12017 | // The "std" namespace has not yet been defined, so build one implicitly. |
12018 | StdNamespace = NamespaceDecl::Create( |
12019 | Context, Context.getTranslationUnitDecl(), |
12020 | /*Inline=*/false, SourceLocation(), SourceLocation(), |
12021 | &PP.getIdentifierTable().get(Name: "std" ), |
12022 | /*PrevDecl=*/nullptr, /*Nested=*/false); |
12023 | getStdNamespace()->setImplicit(true); |
12024 | // We want the created NamespaceDecl to be available for redeclaration |
12025 | // lookups, but not for regular name lookups. |
12026 | Context.getTranslationUnitDecl()->addDecl(getStdNamespace()); |
12027 | getStdNamespace()->clearIdentifierNamespace(); |
12028 | } |
12029 | |
12030 | return getStdNamespace(); |
12031 | } |
12032 | |
12033 | bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { |
12034 | assert(getLangOpts().CPlusPlus && |
12035 | "Looking for std::initializer_list outside of C++." ); |
12036 | |
12037 | // We're looking for implicit instantiations of |
12038 | // template <typename E> class std::initializer_list. |
12039 | |
12040 | if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. |
12041 | return false; |
12042 | |
12043 | ClassTemplateDecl *Template = nullptr; |
12044 | const TemplateArgument *Arguments = nullptr; |
12045 | |
12046 | if (const RecordType *RT = Ty->getAs<RecordType>()) { |
12047 | |
12048 | ClassTemplateSpecializationDecl *Specialization = |
12049 | dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl()); |
12050 | if (!Specialization) |
12051 | return false; |
12052 | |
12053 | Template = Specialization->getSpecializedTemplate(); |
12054 | Arguments = Specialization->getTemplateArgs().data(); |
12055 | } else if (const TemplateSpecializationType *TST = |
12056 | Ty->getAs<TemplateSpecializationType>()) { |
12057 | Template = dyn_cast_or_null<ClassTemplateDecl>( |
12058 | Val: TST->getTemplateName().getAsTemplateDecl()); |
12059 | Arguments = TST->template_arguments().begin(); |
12060 | } |
12061 | if (!Template) |
12062 | return false; |
12063 | |
12064 | if (!StdInitializerList) { |
12065 | // Haven't recognized std::initializer_list yet, maybe this is it. |
12066 | CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); |
12067 | if (TemplateClass->getIdentifier() != |
12068 | &PP.getIdentifierTable().get(Name: "initializer_list" ) || |
12069 | !getStdNamespace()->InEnclosingNamespaceSetOf( |
12070 | NS: TemplateClass->getDeclContext())) |
12071 | return false; |
12072 | // This is a template called std::initializer_list, but is it the right |
12073 | // template? |
12074 | TemplateParameterList *Params = Template->getTemplateParameters(); |
12075 | if (Params->getMinRequiredArguments() != 1) |
12076 | return false; |
12077 | if (!isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) |
12078 | return false; |
12079 | |
12080 | // It's the right template. |
12081 | StdInitializerList = Template; |
12082 | } |
12083 | |
12084 | if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) |
12085 | return false; |
12086 | |
12087 | // This is an instance of std::initializer_list. Find the argument type. |
12088 | if (Element) |
12089 | *Element = Arguments[0].getAsType(); |
12090 | return true; |
12091 | } |
12092 | |
12093 | static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ |
12094 | NamespaceDecl *Std = S.getStdNamespace(); |
12095 | if (!Std) { |
12096 | S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); |
12097 | return nullptr; |
12098 | } |
12099 | |
12100 | LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: "initializer_list" ), |
12101 | Loc, Sema::LookupOrdinaryName); |
12102 | if (!S.LookupQualifiedName(Result, Std)) { |
12103 | S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); |
12104 | return nullptr; |
12105 | } |
12106 | ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); |
12107 | if (!Template) { |
12108 | Result.suppressDiagnostics(); |
12109 | // We found something weird. Complain about the first thing we found. |
12110 | NamedDecl *Found = *Result.begin(); |
12111 | S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); |
12112 | return nullptr; |
12113 | } |
12114 | |
12115 | // We found some template called std::initializer_list. Now verify that it's |
12116 | // correct. |
12117 | TemplateParameterList *Params = Template->getTemplateParameters(); |
12118 | if (Params->getMinRequiredArguments() != 1 || |
12119 | !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) { |
12120 | S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); |
12121 | return nullptr; |
12122 | } |
12123 | |
12124 | return Template; |
12125 | } |
12126 | |
12127 | QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { |
12128 | if (!StdInitializerList) { |
12129 | StdInitializerList = LookupStdInitializerList(S&: *this, Loc); |
12130 | if (!StdInitializerList) |
12131 | return QualType(); |
12132 | } |
12133 | |
12134 | TemplateArgumentListInfo Args(Loc, Loc); |
12135 | Args.addArgument(Loc: TemplateArgumentLoc(TemplateArgument(Element), |
12136 | Context.getTrivialTypeSourceInfo(T: Element, |
12137 | Loc))); |
12138 | return Context.getElaboratedType( |
12139 | Keyword: ElaboratedTypeKeyword::None, |
12140 | NNS: NestedNameSpecifier::Create(Context, Prefix: nullptr, NS: getStdNamespace()), |
12141 | NamedType: CheckTemplateIdType(Template: TemplateName(StdInitializerList), TemplateLoc: Loc, TemplateArgs&: Args)); |
12142 | } |
12143 | |
12144 | bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { |
12145 | // C++ [dcl.init.list]p2: |
12146 | // A constructor is an initializer-list constructor if its first parameter |
12147 | // is of type std::initializer_list<E> or reference to possibly cv-qualified |
12148 | // std::initializer_list<E> for some type E, and either there are no other |
12149 | // parameters or else all other parameters have default arguments. |
12150 | if (!Ctor->hasOneParamOrDefaultArgs()) |
12151 | return false; |
12152 | |
12153 | QualType ArgType = Ctor->getParamDecl(i: 0)->getType(); |
12154 | if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) |
12155 | ArgType = RT->getPointeeType().getUnqualifiedType(); |
12156 | |
12157 | return isStdInitializerList(Ty: ArgType, Element: nullptr); |
12158 | } |
12159 | |
12160 | /// Determine whether a using statement is in a context where it will be |
12161 | /// apply in all contexts. |
12162 | static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { |
12163 | switch (CurContext->getDeclKind()) { |
12164 | case Decl::TranslationUnit: |
12165 | return true; |
12166 | case Decl::LinkageSpec: |
12167 | return IsUsingDirectiveInToplevelContext(CurContext: CurContext->getParent()); |
12168 | default: |
12169 | return false; |
12170 | } |
12171 | } |
12172 | |
12173 | namespace { |
12174 | |
12175 | // Callback to only accept typo corrections that are namespaces. |
12176 | class NamespaceValidatorCCC final : public CorrectionCandidateCallback { |
12177 | public: |
12178 | bool ValidateCandidate(const TypoCorrection &candidate) override { |
12179 | if (NamedDecl *ND = candidate.getCorrectionDecl()) |
12180 | return isa<NamespaceDecl>(Val: ND) || isa<NamespaceAliasDecl>(Val: ND); |
12181 | return false; |
12182 | } |
12183 | |
12184 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
12185 | return std::make_unique<NamespaceValidatorCCC>(args&: *this); |
12186 | } |
12187 | }; |
12188 | |
12189 | } |
12190 | |
12191 | static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected, |
12192 | Sema &S) { |
12193 | auto *ND = cast<NamespaceDecl>(Val: Corrected.getFoundDecl()); |
12194 | Module *M = ND->getOwningModule(); |
12195 | assert(M && "hidden namespace definition not in a module?" ); |
12196 | |
12197 | if (M->isExplicitGlobalModule()) |
12198 | S.Diag(Corrected.getCorrectionRange().getBegin(), |
12199 | diag::err_module_unimported_use_header) |
12200 | << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl() |
12201 | << /*Header Name*/ false; |
12202 | else |
12203 | S.Diag(Corrected.getCorrectionRange().getBegin(), |
12204 | diag::err_module_unimported_use) |
12205 | << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl() |
12206 | << M->getTopLevelModuleName(); |
12207 | } |
12208 | |
12209 | static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, |
12210 | CXXScopeSpec &SS, |
12211 | SourceLocation IdentLoc, |
12212 | IdentifierInfo *Ident) { |
12213 | R.clear(); |
12214 | NamespaceValidatorCCC CCC{}; |
12215 | if (TypoCorrection Corrected = |
12216 | S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Sc, SS: &SS, CCC, |
12217 | Mode: Sema::CTK_ErrorRecovery)) { |
12218 | // Generally we find it is confusing more than helpful to diagnose the |
12219 | // invisible namespace. |
12220 | // See https://github.com/llvm/llvm-project/issues/73893. |
12221 | // |
12222 | // However, we should diagnose when the users are trying to using an |
12223 | // invisible namespace. So we handle the case specially here. |
12224 | if (isa_and_nonnull<NamespaceDecl>(Val: Corrected.getFoundDecl()) && |
12225 | Corrected.requiresImport()) { |
12226 | DiagnoseInvisibleNamespace(Corrected, S); |
12227 | } else if (DeclContext *DC = S.computeDeclContext(SS, EnteringContext: false)) { |
12228 | std::string CorrectedStr(Corrected.getAsString(LO: S.getLangOpts())); |
12229 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && |
12230 | Ident->getName().equals(RHS: CorrectedStr); |
12231 | S.diagnoseTypo(Corrected, |
12232 | S.PDiag(diag::err_using_directive_member_suggest) |
12233 | << Ident << DC << DroppedSpecifier << SS.getRange(), |
12234 | S.PDiag(diag::note_namespace_defined_here)); |
12235 | } else { |
12236 | S.diagnoseTypo(Corrected, |
12237 | S.PDiag(diag::err_using_directive_suggest) << Ident, |
12238 | S.PDiag(diag::note_namespace_defined_here)); |
12239 | } |
12240 | R.addDecl(D: Corrected.getFoundDecl()); |
12241 | return true; |
12242 | } |
12243 | return false; |
12244 | } |
12245 | |
12246 | Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, |
12247 | SourceLocation NamespcLoc, CXXScopeSpec &SS, |
12248 | SourceLocation IdentLoc, |
12249 | IdentifierInfo *NamespcName, |
12250 | const ParsedAttributesView &AttrList) { |
12251 | assert(!SS.isInvalid() && "Invalid CXXScopeSpec." ); |
12252 | assert(NamespcName && "Invalid NamespcName." ); |
12253 | assert(IdentLoc.isValid() && "Invalid NamespceName location." ); |
12254 | |
12255 | // Get the innermost enclosing declaration scope. |
12256 | S = S->getDeclParent(); |
12257 | |
12258 | UsingDirectiveDecl *UDir = nullptr; |
12259 | NestedNameSpecifier *Qualifier = nullptr; |
12260 | if (SS.isSet()) |
12261 | Qualifier = SS.getScopeRep(); |
12262 | |
12263 | // Lookup namespace name. |
12264 | LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); |
12265 | LookupParsedName(R, S, SS: &SS); |
12266 | if (R.isAmbiguous()) |
12267 | return nullptr; |
12268 | |
12269 | if (R.empty()) { |
12270 | R.clear(); |
12271 | // Allow "using namespace std;" or "using namespace ::std;" even if |
12272 | // "std" hasn't been defined yet, for GCC compatibility. |
12273 | if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && |
12274 | NamespcName->isStr(Str: "std" )) { |
12275 | Diag(IdentLoc, diag::ext_using_undefined_std); |
12276 | R.addDecl(getOrCreateStdNamespace()); |
12277 | R.resolveKind(); |
12278 | } |
12279 | // Otherwise, attempt typo correction. |
12280 | else TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident: NamespcName); |
12281 | } |
12282 | |
12283 | if (!R.empty()) { |
12284 | NamedDecl *Named = R.getRepresentativeDecl(); |
12285 | NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); |
12286 | assert(NS && "expected namespace decl" ); |
12287 | |
12288 | // The use of a nested name specifier may trigger deprecation warnings. |
12289 | DiagnoseUseOfDecl(D: Named, Locs: IdentLoc); |
12290 | |
12291 | // C++ [namespace.udir]p1: |
12292 | // A using-directive specifies that the names in the nominated |
12293 | // namespace can be used in the scope in which the |
12294 | // using-directive appears after the using-directive. During |
12295 | // unqualified name lookup (3.4.1), the names appear as if they |
12296 | // were declared in the nearest enclosing namespace which |
12297 | // contains both the using-directive and the nominated |
12298 | // namespace. [Note: in this context, "contains" means "contains |
12299 | // directly or indirectly". ] |
12300 | |
12301 | // Find enclosing context containing both using-directive and |
12302 | // nominated namespace. |
12303 | DeclContext *CommonAncestor = NS; |
12304 | while (CommonAncestor && !CommonAncestor->Encloses(DC: CurContext)) |
12305 | CommonAncestor = CommonAncestor->getParent(); |
12306 | |
12307 | UDir = UsingDirectiveDecl::Create(C&: Context, DC: CurContext, UsingLoc, NamespaceLoc: NamespcLoc, |
12308 | QualifierLoc: SS.getWithLocInContext(Context), |
12309 | IdentLoc, Nominated: Named, CommonAncestor); |
12310 | |
12311 | if (IsUsingDirectiveInToplevelContext(CurContext) && |
12312 | !SourceMgr.isInMainFile(Loc: SourceMgr.getExpansionLoc(Loc: IdentLoc))) { |
12313 | Diag(IdentLoc, diag::warn_using_directive_in_header); |
12314 | } |
12315 | |
12316 | PushUsingDirective(S, UDir); |
12317 | } else { |
12318 | Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); |
12319 | } |
12320 | |
12321 | if (UDir) { |
12322 | ProcessDeclAttributeList(S, UDir, AttrList); |
12323 | ProcessAPINotes(UDir); |
12324 | } |
12325 | |
12326 | return UDir; |
12327 | } |
12328 | |
12329 | void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { |
12330 | // If the scope has an associated entity and the using directive is at |
12331 | // namespace or translation unit scope, add the UsingDirectiveDecl into |
12332 | // its lookup structure so qualified name lookup can find it. |
12333 | DeclContext *Ctx = S->getEntity(); |
12334 | if (Ctx && !Ctx->isFunctionOrMethod()) |
12335 | Ctx->addDecl(UDir); |
12336 | else |
12337 | // Otherwise, it is at block scope. The using-directives will affect lookup |
12338 | // only to the end of the scope. |
12339 | S->PushUsingDirective(UDir); |
12340 | } |
12341 | |
12342 | Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, |
12343 | SourceLocation UsingLoc, |
12344 | SourceLocation TypenameLoc, CXXScopeSpec &SS, |
12345 | UnqualifiedId &Name, |
12346 | SourceLocation EllipsisLoc, |
12347 | const ParsedAttributesView &AttrList) { |
12348 | assert(S->getFlags() & Scope::DeclScope && "Invalid Scope." ); |
12349 | |
12350 | if (SS.isEmpty()) { |
12351 | Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); |
12352 | return nullptr; |
12353 | } |
12354 | |
12355 | switch (Name.getKind()) { |
12356 | case UnqualifiedIdKind::IK_ImplicitSelfParam: |
12357 | case UnqualifiedIdKind::IK_Identifier: |
12358 | case UnqualifiedIdKind::IK_OperatorFunctionId: |
12359 | case UnqualifiedIdKind::IK_LiteralOperatorId: |
12360 | case UnqualifiedIdKind::IK_ConversionFunctionId: |
12361 | break; |
12362 | |
12363 | case UnqualifiedIdKind::IK_ConstructorName: |
12364 | case UnqualifiedIdKind::IK_ConstructorTemplateId: |
12365 | // C++11 inheriting constructors. |
12366 | Diag(Name.getBeginLoc(), |
12367 | getLangOpts().CPlusPlus11 |
12368 | ? diag::warn_cxx98_compat_using_decl_constructor |
12369 | : diag::err_using_decl_constructor) |
12370 | << SS.getRange(); |
12371 | |
12372 | if (getLangOpts().CPlusPlus11) break; |
12373 | |
12374 | return nullptr; |
12375 | |
12376 | case UnqualifiedIdKind::IK_DestructorName: |
12377 | Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); |
12378 | return nullptr; |
12379 | |
12380 | case UnqualifiedIdKind::IK_TemplateId: |
12381 | Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) |
12382 | << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); |
12383 | return nullptr; |
12384 | |
12385 | case UnqualifiedIdKind::IK_DeductionGuideName: |
12386 | llvm_unreachable("cannot parse qualified deduction guide name" ); |
12387 | } |
12388 | |
12389 | DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); |
12390 | DeclarationName TargetName = TargetNameInfo.getName(); |
12391 | if (!TargetName) |
12392 | return nullptr; |
12393 | |
12394 | // Warn about access declarations. |
12395 | if (UsingLoc.isInvalid()) { |
12396 | Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 |
12397 | ? diag::err_access_decl |
12398 | : diag::warn_access_decl_deprecated) |
12399 | << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using " ); |
12400 | } |
12401 | |
12402 | if (EllipsisLoc.isInvalid()) { |
12403 | if (DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_UsingDeclaration) || |
12404 | DiagnoseUnexpandedParameterPack(NameInfo: TargetNameInfo, UPPC: UPPC_UsingDeclaration)) |
12405 | return nullptr; |
12406 | } else { |
12407 | if (!SS.getScopeRep()->containsUnexpandedParameterPack() && |
12408 | !TargetNameInfo.containsUnexpandedParameterPack()) { |
12409 | Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) |
12410 | << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); |
12411 | EllipsisLoc = SourceLocation(); |
12412 | } |
12413 | } |
12414 | |
12415 | NamedDecl *UD = |
12416 | BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, |
12417 | SS, TargetNameInfo, EllipsisLoc, AttrList, |
12418 | /*IsInstantiation*/ false, |
12419 | AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists)); |
12420 | if (UD) |
12421 | PushOnScopeChains(D: UD, S, /*AddToContext*/ false); |
12422 | |
12423 | return UD; |
12424 | } |
12425 | |
12426 | Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS, |
12427 | SourceLocation UsingLoc, |
12428 | SourceLocation EnumLoc, |
12429 | SourceLocation IdentLoc, |
12430 | IdentifierInfo &II, CXXScopeSpec *SS) { |
12431 | assert(!SS->isInvalid() && "ScopeSpec is invalid" ); |
12432 | TypeSourceInfo *TSI = nullptr; |
12433 | QualType EnumTy = GetTypeFromParser( |
12434 | Ty: getTypeName(II, NameLoc: IdentLoc, S, SS, /*isClassName=*/false, |
12435 | /*HasTrailingDot=*/false, |
12436 | /*ObjectType=*/nullptr, /*IsCtorOrDtorName=*/false, |
12437 | /*WantNontrivialTypeSourceInfo=*/true), |
12438 | TInfo: &TSI); |
12439 | if (EnumTy.isNull()) { |
12440 | Diag(IdentLoc, SS && isDependentScopeSpecifier(*SS) |
12441 | ? diag::err_using_enum_is_dependent |
12442 | : diag::err_unknown_typename) |
12443 | << II.getName() |
12444 | << SourceRange(SS ? SS->getBeginLoc() : IdentLoc, IdentLoc); |
12445 | return nullptr; |
12446 | } |
12447 | |
12448 | auto *Enum = dyn_cast_if_present<EnumDecl>(Val: EnumTy->getAsTagDecl()); |
12449 | if (!Enum) { |
12450 | Diag(IdentLoc, diag::err_using_enum_not_enum) << EnumTy; |
12451 | return nullptr; |
12452 | } |
12453 | |
12454 | if (auto *Def = Enum->getDefinition()) |
12455 | Enum = Def; |
12456 | |
12457 | if (TSI == nullptr) |
12458 | TSI = Context.getTrivialTypeSourceInfo(T: EnumTy, Loc: IdentLoc); |
12459 | |
12460 | auto *UD = |
12461 | BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, NameLoc: IdentLoc, EnumType: TSI, ED: Enum); |
12462 | |
12463 | if (UD) |
12464 | PushOnScopeChains(D: UD, S, /*AddToContext*/ false); |
12465 | |
12466 | return UD; |
12467 | } |
12468 | |
12469 | /// Determine whether a using declaration considers the given |
12470 | /// declarations as "equivalent", e.g., if they are redeclarations of |
12471 | /// the same entity or are both typedefs of the same type. |
12472 | static bool |
12473 | IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { |
12474 | if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) |
12475 | return true; |
12476 | |
12477 | if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(Val: D1)) |
12478 | if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(Val: D2)) |
12479 | return Context.hasSameType(T1: TD1->getUnderlyingType(), |
12480 | T2: TD2->getUnderlyingType()); |
12481 | |
12482 | // Two using_if_exists using-declarations are equivalent if both are |
12483 | // unresolved. |
12484 | if (isa<UnresolvedUsingIfExistsDecl>(Val: D1) && |
12485 | isa<UnresolvedUsingIfExistsDecl>(Val: D2)) |
12486 | return true; |
12487 | |
12488 | return false; |
12489 | } |
12490 | |
12491 | |
12492 | /// Determines whether to create a using shadow decl for a particular |
12493 | /// decl, given the set of decls existing prior to this using lookup. |
12494 | bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig, |
12495 | const LookupResult &Previous, |
12496 | UsingShadowDecl *&PrevShadow) { |
12497 | // Diagnose finding a decl which is not from a base class of the |
12498 | // current class. We do this now because there are cases where this |
12499 | // function will silently decide not to build a shadow decl, which |
12500 | // will pre-empt further diagnostics. |
12501 | // |
12502 | // We don't need to do this in C++11 because we do the check once on |
12503 | // the qualifier. |
12504 | // |
12505 | // FIXME: diagnose the following if we care enough: |
12506 | // struct A { int foo; }; |
12507 | // struct B : A { using A::foo; }; |
12508 | // template <class T> struct C : A {}; |
12509 | // template <class T> struct D : C<T> { using B::foo; } // <--- |
12510 | // This is invalid (during instantiation) in C++03 because B::foo |
12511 | // resolves to the using decl in B, which is not a base class of D<T>. |
12512 | // We can't diagnose it immediately because C<T> is an unknown |
12513 | // specialization. The UsingShadowDecl in D<T> then points directly |
12514 | // to A::foo, which will look well-formed when we instantiate. |
12515 | // The right solution is to not collapse the shadow-decl chain. |
12516 | if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) |
12517 | if (auto *Using = dyn_cast<UsingDecl>(Val: BUD)) { |
12518 | DeclContext *OrigDC = Orig->getDeclContext(); |
12519 | |
12520 | // Handle enums and anonymous structs. |
12521 | if (isa<EnumDecl>(Val: OrigDC)) |
12522 | OrigDC = OrigDC->getParent(); |
12523 | CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(Val: OrigDC); |
12524 | while (OrigRec->isAnonymousStructOrUnion()) |
12525 | OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); |
12526 | |
12527 | if (cast<CXXRecordDecl>(Val: CurContext)->isProvablyNotDerivedFrom(Base: OrigRec)) { |
12528 | if (OrigDC == CurContext) { |
12529 | Diag(Using->getLocation(), |
12530 | diag::err_using_decl_nested_name_specifier_is_current_class) |
12531 | << Using->getQualifierLoc().getSourceRange(); |
12532 | Diag(Orig->getLocation(), diag::note_using_decl_target); |
12533 | Using->setInvalidDecl(); |
12534 | return true; |
12535 | } |
12536 | |
12537 | Diag(Using->getQualifierLoc().getBeginLoc(), |
12538 | diag::err_using_decl_nested_name_specifier_is_not_base_class) |
12539 | << Using->getQualifier() << cast<CXXRecordDecl>(CurContext) |
12540 | << Using->getQualifierLoc().getSourceRange(); |
12541 | Diag(Orig->getLocation(), diag::note_using_decl_target); |
12542 | Using->setInvalidDecl(); |
12543 | return true; |
12544 | } |
12545 | } |
12546 | |
12547 | if (Previous.empty()) return false; |
12548 | |
12549 | NamedDecl *Target = Orig; |
12550 | if (isa<UsingShadowDecl>(Val: Target)) |
12551 | Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl(); |
12552 | |
12553 | // If the target happens to be one of the previous declarations, we |
12554 | // don't have a conflict. |
12555 | // |
12556 | // FIXME: but we might be increasing its access, in which case we |
12557 | // should redeclare it. |
12558 | NamedDecl *NonTag = nullptr, *Tag = nullptr; |
12559 | bool FoundEquivalentDecl = false; |
12560 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); |
12561 | I != E; ++I) { |
12562 | NamedDecl *D = (*I)->getUnderlyingDecl(); |
12563 | // We can have UsingDecls in our Previous results because we use the same |
12564 | // LookupResult for checking whether the UsingDecl itself is a valid |
12565 | // redeclaration. |
12566 | if (isa<UsingDecl>(Val: D) || isa<UsingPackDecl>(Val: D) || isa<UsingEnumDecl>(Val: D)) |
12567 | continue; |
12568 | |
12569 | if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) { |
12570 | // C++ [class.mem]p19: |
12571 | // If T is the name of a class, then [every named member other than |
12572 | // a non-static data member] shall have a name different from T |
12573 | if (RD->isInjectedClassName() && !isa<FieldDecl>(Val: Target) && |
12574 | !isa<IndirectFieldDecl>(Val: Target) && |
12575 | !isa<UnresolvedUsingValueDecl>(Val: Target) && |
12576 | DiagnoseClassNameShadow( |
12577 | DC: CurContext, |
12578 | Info: DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation()))) |
12579 | return true; |
12580 | } |
12581 | |
12582 | if (IsEquivalentForUsingDecl(Context, D1: D, D2: Target)) { |
12583 | if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: *I)) |
12584 | PrevShadow = Shadow; |
12585 | FoundEquivalentDecl = true; |
12586 | } else if (isEquivalentInternalLinkageDeclaration(A: D, B: Target)) { |
12587 | // We don't conflict with an existing using shadow decl of an equivalent |
12588 | // declaration, but we're not a redeclaration of it. |
12589 | FoundEquivalentDecl = true; |
12590 | } |
12591 | |
12592 | if (isVisible(D)) |
12593 | (isa<TagDecl>(Val: D) ? Tag : NonTag) = D; |
12594 | } |
12595 | |
12596 | if (FoundEquivalentDecl) |
12597 | return false; |
12598 | |
12599 | // Always emit a diagnostic for a mismatch between an unresolved |
12600 | // using_if_exists and a resolved using declaration in either direction. |
12601 | if (isa<UnresolvedUsingIfExistsDecl>(Val: Target) != |
12602 | (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(Val: NonTag))) { |
12603 | if (!NonTag && !Tag) |
12604 | return false; |
12605 | Diag(BUD->getLocation(), diag::err_using_decl_conflict); |
12606 | Diag(Target->getLocation(), diag::note_using_decl_target); |
12607 | Diag((NonTag ? NonTag : Tag)->getLocation(), |
12608 | diag::note_using_decl_conflict); |
12609 | BUD->setInvalidDecl(); |
12610 | return true; |
12611 | } |
12612 | |
12613 | if (FunctionDecl *FD = Target->getAsFunction()) { |
12614 | NamedDecl *OldDecl = nullptr; |
12615 | switch (CheckOverload(S: nullptr, New: FD, OldDecls: Previous, OldDecl, |
12616 | /*IsForUsingDecl*/ UseMemberUsingDeclRules: true)) { |
12617 | case Ovl_Overload: |
12618 | return false; |
12619 | |
12620 | case Ovl_NonFunction: |
12621 | Diag(BUD->getLocation(), diag::err_using_decl_conflict); |
12622 | break; |
12623 | |
12624 | // We found a decl with the exact signature. |
12625 | case Ovl_Match: |
12626 | // If we're in a record, we want to hide the target, so we |
12627 | // return true (without a diagnostic) to tell the caller not to |
12628 | // build a shadow decl. |
12629 | if (CurContext->isRecord()) |
12630 | return true; |
12631 | |
12632 | // If we're not in a record, this is an error. |
12633 | Diag(BUD->getLocation(), diag::err_using_decl_conflict); |
12634 | break; |
12635 | } |
12636 | |
12637 | Diag(Target->getLocation(), diag::note_using_decl_target); |
12638 | Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); |
12639 | BUD->setInvalidDecl(); |
12640 | return true; |
12641 | } |
12642 | |
12643 | // Target is not a function. |
12644 | |
12645 | if (isa<TagDecl>(Val: Target)) { |
12646 | // No conflict between a tag and a non-tag. |
12647 | if (!Tag) return false; |
12648 | |
12649 | Diag(BUD->getLocation(), diag::err_using_decl_conflict); |
12650 | Diag(Target->getLocation(), diag::note_using_decl_target); |
12651 | Diag(Tag->getLocation(), diag::note_using_decl_conflict); |
12652 | BUD->setInvalidDecl(); |
12653 | return true; |
12654 | } |
12655 | |
12656 | // No conflict between a tag and a non-tag. |
12657 | if (!NonTag) return false; |
12658 | |
12659 | Diag(BUD->getLocation(), diag::err_using_decl_conflict); |
12660 | Diag(Target->getLocation(), diag::note_using_decl_target); |
12661 | Diag(NonTag->getLocation(), diag::note_using_decl_conflict); |
12662 | BUD->setInvalidDecl(); |
12663 | return true; |
12664 | } |
12665 | |
12666 | /// Determine whether a direct base class is a virtual base class. |
12667 | static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { |
12668 | if (!Derived->getNumVBases()) |
12669 | return false; |
12670 | for (auto &B : Derived->bases()) |
12671 | if (B.getType()->getAsCXXRecordDecl() == Base) |
12672 | return B.isVirtual(); |
12673 | llvm_unreachable("not a direct base class" ); |
12674 | } |
12675 | |
12676 | /// Builds a shadow declaration corresponding to a 'using' declaration. |
12677 | UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, |
12678 | NamedDecl *Orig, |
12679 | UsingShadowDecl *PrevDecl) { |
12680 | // If we resolved to another shadow declaration, just coalesce them. |
12681 | NamedDecl *Target = Orig; |
12682 | if (isa<UsingShadowDecl>(Val: Target)) { |
12683 | Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl(); |
12684 | assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration" ); |
12685 | } |
12686 | |
12687 | NamedDecl *NonTemplateTarget = Target; |
12688 | if (auto *TargetTD = dyn_cast<TemplateDecl>(Val: Target)) |
12689 | NonTemplateTarget = TargetTD->getTemplatedDecl(); |
12690 | |
12691 | UsingShadowDecl *Shadow; |
12692 | if (NonTemplateTarget && isa<CXXConstructorDecl>(Val: NonTemplateTarget)) { |
12693 | UsingDecl *Using = cast<UsingDecl>(Val: BUD); |
12694 | bool IsVirtualBase = |
12695 | isVirtualDirectBase(Derived: cast<CXXRecordDecl>(Val: CurContext), |
12696 | Base: Using->getQualifier()->getAsRecordDecl()); |
12697 | Shadow = ConstructorUsingShadowDecl::Create( |
12698 | C&: Context, DC: CurContext, Loc: Using->getLocation(), Using, Target: Orig, IsVirtual: IsVirtualBase); |
12699 | } else { |
12700 | Shadow = UsingShadowDecl::Create(C&: Context, DC: CurContext, Loc: BUD->getLocation(), |
12701 | Name: Target->getDeclName(), Introducer: BUD, Target); |
12702 | } |
12703 | BUD->addShadowDecl(S: Shadow); |
12704 | |
12705 | Shadow->setAccess(BUD->getAccess()); |
12706 | if (Orig->isInvalidDecl() || BUD->isInvalidDecl()) |
12707 | Shadow->setInvalidDecl(); |
12708 | |
12709 | Shadow->setPreviousDecl(PrevDecl); |
12710 | |
12711 | if (S) |
12712 | PushOnScopeChains(Shadow, S); |
12713 | else |
12714 | CurContext->addDecl(Shadow); |
12715 | |
12716 | |
12717 | return Shadow; |
12718 | } |
12719 | |
12720 | /// Hides a using shadow declaration. This is required by the current |
12721 | /// using-decl implementation when a resolvable using declaration in a |
12722 | /// class is followed by a declaration which would hide or override |
12723 | /// one or more of the using decl's targets; for example: |
12724 | /// |
12725 | /// struct Base { void foo(int); }; |
12726 | /// struct Derived : Base { |
12727 | /// using Base::foo; |
12728 | /// void foo(int); |
12729 | /// }; |
12730 | /// |
12731 | /// The governing language is C++03 [namespace.udecl]p12: |
12732 | /// |
12733 | /// When a using-declaration brings names from a base class into a |
12734 | /// derived class scope, member functions in the derived class |
12735 | /// override and/or hide member functions with the same name and |
12736 | /// parameter types in a base class (rather than conflicting). |
12737 | /// |
12738 | /// There are two ways to implement this: |
12739 | /// (1) optimistically create shadow decls when they're not hidden |
12740 | /// by existing declarations, or |
12741 | /// (2) don't create any shadow decls (or at least don't make them |
12742 | /// visible) until we've fully parsed/instantiated the class. |
12743 | /// The problem with (1) is that we might have to retroactively remove |
12744 | /// a shadow decl, which requires several O(n) operations because the |
12745 | /// decl structures are (very reasonably) not designed for removal. |
12746 | /// (2) avoids this but is very fiddly and phase-dependent. |
12747 | void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { |
12748 | if (Shadow->getDeclName().getNameKind() == |
12749 | DeclarationName::CXXConversionFunctionName) |
12750 | cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); |
12751 | |
12752 | // Remove it from the DeclContext... |
12753 | Shadow->getDeclContext()->removeDecl(Shadow); |
12754 | |
12755 | // ...and the scope, if applicable... |
12756 | if (S) { |
12757 | S->RemoveDecl(Shadow); |
12758 | IdResolver.RemoveDecl(Shadow); |
12759 | } |
12760 | |
12761 | // ...and the using decl. |
12762 | Shadow->getIntroducer()->removeShadowDecl(S: Shadow); |
12763 | |
12764 | // TODO: complain somehow if Shadow was used. It shouldn't |
12765 | // be possible for this to happen, because...? |
12766 | } |
12767 | |
12768 | /// Find the base specifier for a base class with the given type. |
12769 | static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, |
12770 | QualType DesiredBase, |
12771 | bool &AnyDependentBases) { |
12772 | // Check whether the named type is a direct base class. |
12773 | CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() |
12774 | .getUnqualifiedType(); |
12775 | for (auto &Base : Derived->bases()) { |
12776 | CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); |
12777 | if (CanonicalDesiredBase == BaseType) |
12778 | return &Base; |
12779 | if (BaseType->isDependentType()) |
12780 | AnyDependentBases = true; |
12781 | } |
12782 | return nullptr; |
12783 | } |
12784 | |
12785 | namespace { |
12786 | class UsingValidatorCCC final : public CorrectionCandidateCallback { |
12787 | public: |
12788 | UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, |
12789 | NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) |
12790 | : HasTypenameKeyword(HasTypenameKeyword), |
12791 | IsInstantiation(IsInstantiation), OldNNS(NNS), |
12792 | RequireMemberOf(RequireMemberOf) {} |
12793 | |
12794 | bool ValidateCandidate(const TypoCorrection &Candidate) override { |
12795 | NamedDecl *ND = Candidate.getCorrectionDecl(); |
12796 | |
12797 | // Keywords are not valid here. |
12798 | if (!ND || isa<NamespaceDecl>(Val: ND)) |
12799 | return false; |
12800 | |
12801 | // Completely unqualified names are invalid for a 'using' declaration. |
12802 | if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) |
12803 | return false; |
12804 | |
12805 | // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would |
12806 | // reject. |
12807 | |
12808 | if (RequireMemberOf) { |
12809 | auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND); |
12810 | if (FoundRecord && FoundRecord->isInjectedClassName()) { |
12811 | // No-one ever wants a using-declaration to name an injected-class-name |
12812 | // of a base class, unless they're declaring an inheriting constructor. |
12813 | ASTContext &Ctx = ND->getASTContext(); |
12814 | if (!Ctx.getLangOpts().CPlusPlus11) |
12815 | return false; |
12816 | QualType FoundType = Ctx.getRecordType(FoundRecord); |
12817 | |
12818 | // Check that the injected-class-name is named as a member of its own |
12819 | // type; we don't want to suggest 'using Derived::Base;', since that |
12820 | // means something else. |
12821 | NestedNameSpecifier *Specifier = |
12822 | Candidate.WillReplaceSpecifier() |
12823 | ? Candidate.getCorrectionSpecifier() |
12824 | : OldNNS; |
12825 | if (!Specifier->getAsType() || |
12826 | !Ctx.hasSameType(T1: QualType(Specifier->getAsType(), 0), T2: FoundType)) |
12827 | return false; |
12828 | |
12829 | // Check that this inheriting constructor declaration actually names a |
12830 | // direct base class of the current class. |
12831 | bool AnyDependentBases = false; |
12832 | if (!findDirectBaseWithType(Derived: RequireMemberOf, |
12833 | DesiredBase: Ctx.getRecordType(FoundRecord), |
12834 | AnyDependentBases) && |
12835 | !AnyDependentBases) |
12836 | return false; |
12837 | } else { |
12838 | auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); |
12839 | if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(Base: RD)) |
12840 | return false; |
12841 | |
12842 | // FIXME: Check that the base class member is accessible? |
12843 | } |
12844 | } else { |
12845 | auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND); |
12846 | if (FoundRecord && FoundRecord->isInjectedClassName()) |
12847 | return false; |
12848 | } |
12849 | |
12850 | if (isa<TypeDecl>(Val: ND)) |
12851 | return HasTypenameKeyword || !IsInstantiation; |
12852 | |
12853 | return !HasTypenameKeyword; |
12854 | } |
12855 | |
12856 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
12857 | return std::make_unique<UsingValidatorCCC>(args&: *this); |
12858 | } |
12859 | |
12860 | private: |
12861 | bool HasTypenameKeyword; |
12862 | bool IsInstantiation; |
12863 | NestedNameSpecifier *OldNNS; |
12864 | CXXRecordDecl *RequireMemberOf; |
12865 | }; |
12866 | } // end anonymous namespace |
12867 | |
12868 | /// Remove decls we can't actually see from a lookup being used to declare |
12869 | /// shadow using decls. |
12870 | /// |
12871 | /// \param S - The scope of the potential shadow decl |
12872 | /// \param Previous - The lookup of a potential shadow decl's name. |
12873 | void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) { |
12874 | // It is really dumb that we have to do this. |
12875 | LookupResult::Filter F = Previous.makeFilter(); |
12876 | while (F.hasNext()) { |
12877 | NamedDecl *D = F.next(); |
12878 | if (!isDeclInScope(D, Ctx: CurContext, S)) |
12879 | F.erase(); |
12880 | // If we found a local extern declaration that's not ordinarily visible, |
12881 | // and this declaration is being added to a non-block scope, ignore it. |
12882 | // We're only checking for scope conflicts here, not also for violations |
12883 | // of the linkage rules. |
12884 | else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && |
12885 | !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) |
12886 | F.erase(); |
12887 | } |
12888 | F.done(); |
12889 | } |
12890 | |
12891 | /// Builds a using declaration. |
12892 | /// |
12893 | /// \param IsInstantiation - Whether this call arises from an |
12894 | /// instantiation of an unresolved using declaration. We treat |
12895 | /// the lookup differently for these declarations. |
12896 | NamedDecl *Sema::BuildUsingDeclaration( |
12897 | Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, |
12898 | bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, |
12899 | DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, |
12900 | const ParsedAttributesView &AttrList, bool IsInstantiation, |
12901 | bool IsUsingIfExists) { |
12902 | assert(!SS.isInvalid() && "Invalid CXXScopeSpec." ); |
12903 | SourceLocation IdentLoc = NameInfo.getLoc(); |
12904 | assert(IdentLoc.isValid() && "Invalid TargetName location." ); |
12905 | |
12906 | // FIXME: We ignore attributes for now. |
12907 | |
12908 | // For an inheriting constructor declaration, the name of the using |
12909 | // declaration is the name of a constructor in this class, not in the |
12910 | // base class. |
12911 | DeclarationNameInfo UsingName = NameInfo; |
12912 | if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) |
12913 | if (auto *RD = dyn_cast<CXXRecordDecl>(Val: CurContext)) |
12914 | UsingName.setName(Context.DeclarationNames.getCXXConstructorName( |
12915 | Ty: Context.getCanonicalType(T: Context.getRecordType(RD)))); |
12916 | |
12917 | // Do the redeclaration lookup in the current scope. |
12918 | LookupResult Previous(*this, UsingName, LookupUsingDeclName, |
12919 | RedeclarationKind::ForVisibleRedeclaration); |
12920 | Previous.setHideTags(false); |
12921 | if (S) { |
12922 | LookupName(R&: Previous, S); |
12923 | |
12924 | FilterUsingLookup(S, Previous); |
12925 | } else { |
12926 | assert(IsInstantiation && "no scope in non-instantiation" ); |
12927 | if (CurContext->isRecord()) |
12928 | LookupQualifiedName(R&: Previous, LookupCtx: CurContext); |
12929 | else { |
12930 | // No redeclaration check is needed here; in non-member contexts we |
12931 | // diagnosed all possible conflicts with other using-declarations when |
12932 | // building the template: |
12933 | // |
12934 | // For a dependent non-type using declaration, the only valid case is |
12935 | // if we instantiate to a single enumerator. We check for conflicts |
12936 | // between shadow declarations we introduce, and we check in the template |
12937 | // definition for conflicts between a non-type using declaration and any |
12938 | // other declaration, which together covers all cases. |
12939 | // |
12940 | // A dependent typename using declaration will never successfully |
12941 | // instantiate, since it will always name a class member, so we reject |
12942 | // that in the template definition. |
12943 | } |
12944 | } |
12945 | |
12946 | // Check for invalid redeclarations. |
12947 | if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, |
12948 | SS, NameLoc: IdentLoc, Previous)) |
12949 | return nullptr; |
12950 | |
12951 | // 'using_if_exists' doesn't make sense on an inherited constructor. |
12952 | if (IsUsingIfExists && UsingName.getName().getNameKind() == |
12953 | DeclarationName::CXXConstructorName) { |
12954 | Diag(UsingLoc, diag::err_using_if_exists_on_ctor); |
12955 | return nullptr; |
12956 | } |
12957 | |
12958 | DeclContext *LookupContext = computeDeclContext(SS); |
12959 | NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); |
12960 | if (!LookupContext || EllipsisLoc.isValid()) { |
12961 | NamedDecl *D; |
12962 | // Dependent scope, or an unexpanded pack |
12963 | if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword, |
12964 | SS, NameInfo, NameLoc: IdentLoc)) |
12965 | return nullptr; |
12966 | |
12967 | if (HasTypenameKeyword) { |
12968 | // FIXME: not all declaration name kinds are legal here |
12969 | D = UnresolvedUsingTypenameDecl::Create(C&: Context, DC: CurContext, |
12970 | UsingLoc, TypenameLoc, |
12971 | QualifierLoc, |
12972 | TargetNameLoc: IdentLoc, TargetName: NameInfo.getName(), |
12973 | EllipsisLoc); |
12974 | } else { |
12975 | D = UnresolvedUsingValueDecl::Create(C&: Context, DC: CurContext, UsingLoc, |
12976 | QualifierLoc, NameInfo, EllipsisLoc); |
12977 | } |
12978 | D->setAccess(AS); |
12979 | CurContext->addDecl(D); |
12980 | ProcessDeclAttributeList(S, D, AttrList); |
12981 | return D; |
12982 | } |
12983 | |
12984 | auto Build = [&](bool Invalid) { |
12985 | UsingDecl *UD = |
12986 | UsingDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc, QualifierLoc, |
12987 | NameInfo: UsingName, HasTypenameKeyword); |
12988 | UD->setAccess(AS); |
12989 | CurContext->addDecl(UD); |
12990 | ProcessDeclAttributeList(S, UD, AttrList); |
12991 | UD->setInvalidDecl(Invalid); |
12992 | return UD; |
12993 | }; |
12994 | auto BuildInvalid = [&]{ return Build(true); }; |
12995 | auto BuildValid = [&]{ return Build(false); }; |
12996 | |
12997 | if (RequireCompleteDeclContext(SS, DC: LookupContext)) |
12998 | return BuildInvalid(); |
12999 | |
13000 | // Look up the target name. |
13001 | LookupResult R(*this, NameInfo, LookupOrdinaryName); |
13002 | |
13003 | // Unlike most lookups, we don't always want to hide tag |
13004 | // declarations: tag names are visible through the using declaration |
13005 | // even if hidden by ordinary names, *except* in a dependent context |
13006 | // where they may be used by two-phase lookup. |
13007 | if (!IsInstantiation) |
13008 | R.setHideTags(false); |
13009 | |
13010 | // For the purposes of this lookup, we have a base object type |
13011 | // equal to that of the current context. |
13012 | if (CurContext->isRecord()) { |
13013 | R.setBaseObjectType( |
13014 | Context.getTypeDeclType(cast<CXXRecordDecl>(Val: CurContext))); |
13015 | } |
13016 | |
13017 | LookupQualifiedName(R, LookupCtx: LookupContext); |
13018 | |
13019 | // Validate the context, now we have a lookup |
13020 | if (CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword, SS, NameInfo, |
13021 | NameLoc: IdentLoc, R: &R)) |
13022 | return nullptr; |
13023 | |
13024 | if (R.empty() && IsUsingIfExists) |
13025 | R.addDecl(UnresolvedUsingIfExistsDecl::Create(Ctx&: Context, DC: CurContext, Loc: UsingLoc, |
13026 | Name: UsingName.getName()), |
13027 | AS_public); |
13028 | |
13029 | // Try to correct typos if possible. If constructor name lookup finds no |
13030 | // results, that means the named class has no explicit constructors, and we |
13031 | // suppressed declaring implicit ones (probably because it's dependent or |
13032 | // invalid). |
13033 | if (R.empty() && |
13034 | NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { |
13035 | // HACK 2017-01-08: Work around an issue with libstdc++'s detection of |
13036 | // ::gets. Sometimes it believes that glibc provides a ::gets in cases where |
13037 | // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later. |
13038 | auto *II = NameInfo.getName().getAsIdentifierInfo(); |
13039 | if (getLangOpts().CPlusPlus14 && II && II->isStr(Str: "gets" ) && |
13040 | CurContext->isStdNamespace() && |
13041 | isa<TranslationUnitDecl>(Val: LookupContext) && |
13042 | getSourceManager().isInSystemHeader(Loc: UsingLoc)) |
13043 | return nullptr; |
13044 | UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), |
13045 | dyn_cast<CXXRecordDecl>(Val: CurContext)); |
13046 | if (TypoCorrection Corrected = |
13047 | CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC, |
13048 | Mode: CTK_ErrorRecovery)) { |
13049 | // We reject candidates where DroppedSpecifier == true, hence the |
13050 | // literal '0' below. |
13051 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) |
13052 | << NameInfo.getName() << LookupContext << 0 |
13053 | << SS.getRange()); |
13054 | |
13055 | // If we picked a correction with no attached Decl we can't do anything |
13056 | // useful with it, bail out. |
13057 | NamedDecl *ND = Corrected.getCorrectionDecl(); |
13058 | if (!ND) |
13059 | return BuildInvalid(); |
13060 | |
13061 | // If we corrected to an inheriting constructor, handle it as one. |
13062 | auto *RD = dyn_cast<CXXRecordDecl>(Val: ND); |
13063 | if (RD && RD->isInjectedClassName()) { |
13064 | // The parent of the injected class name is the class itself. |
13065 | RD = cast<CXXRecordDecl>(RD->getParent()); |
13066 | |
13067 | // Fix up the information we'll use to build the using declaration. |
13068 | if (Corrected.WillReplaceSpecifier()) { |
13069 | NestedNameSpecifierLocBuilder Builder; |
13070 | Builder.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(), |
13071 | R: QualifierLoc.getSourceRange()); |
13072 | QualifierLoc = Builder.getWithLocInContext(Context); |
13073 | } |
13074 | |
13075 | // In this case, the name we introduce is the name of a derived class |
13076 | // constructor. |
13077 | auto *CurClass = cast<CXXRecordDecl>(Val: CurContext); |
13078 | UsingName.setName(Context.DeclarationNames.getCXXConstructorName( |
13079 | Ty: Context.getCanonicalType(T: Context.getRecordType(CurClass)))); |
13080 | UsingName.setNamedTypeInfo(nullptr); |
13081 | for (auto *Ctor : LookupConstructors(Class: RD)) |
13082 | R.addDecl(D: Ctor); |
13083 | R.resolveKind(); |
13084 | } else { |
13085 | // FIXME: Pick up all the declarations if we found an overloaded |
13086 | // function. |
13087 | UsingName.setName(ND->getDeclName()); |
13088 | R.addDecl(D: ND); |
13089 | } |
13090 | } else { |
13091 | Diag(IdentLoc, diag::err_no_member) |
13092 | << NameInfo.getName() << LookupContext << SS.getRange(); |
13093 | return BuildInvalid(); |
13094 | } |
13095 | } |
13096 | |
13097 | if (R.isAmbiguous()) |
13098 | return BuildInvalid(); |
13099 | |
13100 | if (HasTypenameKeyword) { |
13101 | // If we asked for a typename and got a non-type decl, error out. |
13102 | if (!R.getAsSingle<TypeDecl>() && |
13103 | !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) { |
13104 | Diag(IdentLoc, diag::err_using_typename_non_type); |
13105 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) |
13106 | Diag((*I)->getUnderlyingDecl()->getLocation(), |
13107 | diag::note_using_decl_target); |
13108 | return BuildInvalid(); |
13109 | } |
13110 | } else { |
13111 | // If we asked for a non-typename and we got a type, error out, |
13112 | // but only if this is an instantiation of an unresolved using |
13113 | // decl. Otherwise just silently find the type name. |
13114 | if (IsInstantiation && R.getAsSingle<TypeDecl>()) { |
13115 | Diag(IdentLoc, diag::err_using_dependent_value_is_type); |
13116 | Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); |
13117 | return BuildInvalid(); |
13118 | } |
13119 | } |
13120 | |
13121 | // C++14 [namespace.udecl]p6: |
13122 | // A using-declaration shall not name a namespace. |
13123 | if (R.getAsSingle<NamespaceDecl>()) { |
13124 | Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) |
13125 | << SS.getRange(); |
13126 | return BuildInvalid(); |
13127 | } |
13128 | |
13129 | UsingDecl *UD = BuildValid(); |
13130 | |
13131 | // Some additional rules apply to inheriting constructors. |
13132 | if (UsingName.getName().getNameKind() == |
13133 | DeclarationName::CXXConstructorName) { |
13134 | // Suppress access diagnostics; the access check is instead performed at the |
13135 | // point of use for an inheriting constructor. |
13136 | R.suppressDiagnostics(); |
13137 | if (CheckInheritingConstructorUsingDecl(UD)) |
13138 | return UD; |
13139 | } |
13140 | |
13141 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { |
13142 | UsingShadowDecl *PrevDecl = nullptr; |
13143 | if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) |
13144 | BuildUsingShadowDecl(S, UD, *I, PrevDecl); |
13145 | } |
13146 | |
13147 | return UD; |
13148 | } |
13149 | |
13150 | NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, |
13151 | SourceLocation UsingLoc, |
13152 | SourceLocation EnumLoc, |
13153 | SourceLocation NameLoc, |
13154 | TypeSourceInfo *EnumType, |
13155 | EnumDecl *ED) { |
13156 | bool Invalid = false; |
13157 | |
13158 | if (CurContext->getRedeclContext()->isRecord()) { |
13159 | /// In class scope, check if this is a duplicate, for better a diagnostic. |
13160 | DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc); |
13161 | LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName, |
13162 | RedeclarationKind::ForVisibleRedeclaration); |
13163 | |
13164 | LookupName(R&: Previous, S); |
13165 | |
13166 | for (NamedDecl *D : Previous) |
13167 | if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D)) |
13168 | if (UED->getEnumDecl() == ED) { |
13169 | Diag(UsingLoc, diag::err_using_enum_decl_redeclaration) |
13170 | << SourceRange(EnumLoc, NameLoc); |
13171 | Diag(D->getLocation(), diag::note_using_enum_decl) << 1; |
13172 | Invalid = true; |
13173 | break; |
13174 | } |
13175 | } |
13176 | |
13177 | if (RequireCompleteEnumDecl(D: ED, L: NameLoc)) |
13178 | Invalid = true; |
13179 | |
13180 | UsingEnumDecl *UD = UsingEnumDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc, |
13181 | EnumL: EnumLoc, NameL: NameLoc, EnumType); |
13182 | UD->setAccess(AS); |
13183 | CurContext->addDecl(UD); |
13184 | |
13185 | if (Invalid) { |
13186 | UD->setInvalidDecl(); |
13187 | return UD; |
13188 | } |
13189 | |
13190 | // Create the shadow decls for each enumerator |
13191 | for (EnumConstantDecl *EC : ED->enumerators()) { |
13192 | UsingShadowDecl *PrevDecl = nullptr; |
13193 | DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation()); |
13194 | LookupResult Previous(*this, DNI, LookupOrdinaryName, |
13195 | RedeclarationKind::ForVisibleRedeclaration); |
13196 | LookupName(R&: Previous, S); |
13197 | FilterUsingLookup(S, Previous); |
13198 | |
13199 | if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl)) |
13200 | BuildUsingShadowDecl(S, UD, EC, PrevDecl); |
13201 | } |
13202 | |
13203 | return UD; |
13204 | } |
13205 | |
13206 | NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, |
13207 | ArrayRef<NamedDecl *> Expansions) { |
13208 | assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || |
13209 | isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || |
13210 | isa<UsingPackDecl>(InstantiatedFrom)); |
13211 | |
13212 | auto *UPD = |
13213 | UsingPackDecl::Create(C&: Context, DC: CurContext, InstantiatedFrom, UsingDecls: Expansions); |
13214 | UPD->setAccess(InstantiatedFrom->getAccess()); |
13215 | CurContext->addDecl(UPD); |
13216 | return UPD; |
13217 | } |
13218 | |
13219 | /// Additional checks for a using declaration referring to a constructor name. |
13220 | bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { |
13221 | assert(!UD->hasTypename() && "expecting a constructor name" ); |
13222 | |
13223 | const Type *SourceType = UD->getQualifier()->getAsType(); |
13224 | assert(SourceType && |
13225 | "Using decl naming constructor doesn't have type in scope spec." ); |
13226 | CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(Val: CurContext); |
13227 | |
13228 | // Check whether the named type is a direct base class. |
13229 | bool AnyDependentBases = false; |
13230 | auto *Base = findDirectBaseWithType(Derived: TargetClass, DesiredBase: QualType(SourceType, 0), |
13231 | AnyDependentBases); |
13232 | if (!Base && !AnyDependentBases) { |
13233 | Diag(UD->getUsingLoc(), |
13234 | diag::err_using_decl_constructor_not_in_direct_base) |
13235 | << UD->getNameInfo().getSourceRange() |
13236 | << QualType(SourceType, 0) << TargetClass; |
13237 | UD->setInvalidDecl(); |
13238 | return true; |
13239 | } |
13240 | |
13241 | if (Base) |
13242 | Base->setInheritConstructors(); |
13243 | |
13244 | return false; |
13245 | } |
13246 | |
13247 | /// Checks that the given using declaration is not an invalid |
13248 | /// redeclaration. Note that this is checking only for the using decl |
13249 | /// itself, not for any ill-formedness among the UsingShadowDecls. |
13250 | bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, |
13251 | bool HasTypenameKeyword, |
13252 | const CXXScopeSpec &SS, |
13253 | SourceLocation NameLoc, |
13254 | const LookupResult &Prev) { |
13255 | NestedNameSpecifier *Qual = SS.getScopeRep(); |
13256 | |
13257 | // C++03 [namespace.udecl]p8: |
13258 | // C++0x [namespace.udecl]p10: |
13259 | // A using-declaration is a declaration and can therefore be used |
13260 | // repeatedly where (and only where) multiple declarations are |
13261 | // allowed. |
13262 | // |
13263 | // That's in non-member contexts. |
13264 | if (!CurContext->getRedeclContext()->isRecord()) { |
13265 | // A dependent qualifier outside a class can only ever resolve to an |
13266 | // enumeration type. Therefore it conflicts with any other non-type |
13267 | // declaration in the same scope. |
13268 | // FIXME: How should we check for dependent type-type conflicts at block |
13269 | // scope? |
13270 | if (Qual->isDependent() && !HasTypenameKeyword) { |
13271 | for (auto *D : Prev) { |
13272 | if (!isa<TypeDecl>(Val: D) && !isa<UsingDecl>(Val: D) && !isa<UsingPackDecl>(Val: D)) { |
13273 | bool OldCouldBeEnumerator = |
13274 | isa<UnresolvedUsingValueDecl>(Val: D) || isa<EnumConstantDecl>(Val: D); |
13275 | Diag(NameLoc, |
13276 | OldCouldBeEnumerator ? diag::err_redefinition |
13277 | : diag::err_redefinition_different_kind) |
13278 | << Prev.getLookupName(); |
13279 | Diag(D->getLocation(), diag::note_previous_definition); |
13280 | return true; |
13281 | } |
13282 | } |
13283 | } |
13284 | return false; |
13285 | } |
13286 | |
13287 | const NestedNameSpecifier *CNNS = |
13288 | Context.getCanonicalNestedNameSpecifier(NNS: Qual); |
13289 | for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { |
13290 | NamedDecl *D = *I; |
13291 | |
13292 | bool DTypename; |
13293 | NestedNameSpecifier *DQual; |
13294 | if (UsingDecl *UD = dyn_cast<UsingDecl>(Val: D)) { |
13295 | DTypename = UD->hasTypename(); |
13296 | DQual = UD->getQualifier(); |
13297 | } else if (UnresolvedUsingValueDecl *UD |
13298 | = dyn_cast<UnresolvedUsingValueDecl>(Val: D)) { |
13299 | DTypename = false; |
13300 | DQual = UD->getQualifier(); |
13301 | } else if (UnresolvedUsingTypenameDecl *UD |
13302 | = dyn_cast<UnresolvedUsingTypenameDecl>(Val: D)) { |
13303 | DTypename = true; |
13304 | DQual = UD->getQualifier(); |
13305 | } else continue; |
13306 | |
13307 | // using decls differ if one says 'typename' and the other doesn't. |
13308 | // FIXME: non-dependent using decls? |
13309 | if (HasTypenameKeyword != DTypename) continue; |
13310 | |
13311 | // using decls differ if they name different scopes (but note that |
13312 | // template instantiation can cause this check to trigger when it |
13313 | // didn't before instantiation). |
13314 | if (CNNS != Context.getCanonicalNestedNameSpecifier(NNS: DQual)) |
13315 | continue; |
13316 | |
13317 | Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); |
13318 | Diag(D->getLocation(), diag::note_using_decl) << 1; |
13319 | return true; |
13320 | } |
13321 | |
13322 | return false; |
13323 | } |
13324 | |
13325 | /// Checks that the given nested-name qualifier used in a using decl |
13326 | /// in the current context is appropriately related to the current |
13327 | /// scope. If an error is found, diagnoses it and returns true. |
13328 | /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the |
13329 | /// result of that lookup. UD is likewise nullptr, except when we have an |
13330 | /// already-populated UsingDecl whose shadow decls contain the same information |
13331 | /// (i.e. we're instantiating a UsingDecl with non-dependent scope). |
13332 | bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, |
13333 | const CXXScopeSpec &SS, |
13334 | const DeclarationNameInfo &NameInfo, |
13335 | SourceLocation NameLoc, |
13336 | const LookupResult *R, const UsingDecl *UD) { |
13337 | DeclContext *NamedContext = computeDeclContext(SS); |
13338 | assert(bool(NamedContext) == (R || UD) && !(R && UD) && |
13339 | "resolvable context must have exactly one set of decls" ); |
13340 | |
13341 | // C++ 20 permits using an enumerator that does not have a class-hierarchy |
13342 | // relationship. |
13343 | bool Cxx20Enumerator = false; |
13344 | if (NamedContext) { |
13345 | EnumConstantDecl *EC = nullptr; |
13346 | if (R) |
13347 | EC = R->getAsSingle<EnumConstantDecl>(); |
13348 | else if (UD && UD->shadow_size() == 1) |
13349 | EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl()); |
13350 | if (EC) |
13351 | Cxx20Enumerator = getLangOpts().CPlusPlus20; |
13352 | |
13353 | if (auto *ED = dyn_cast<EnumDecl>(Val: NamedContext)) { |
13354 | // C++14 [namespace.udecl]p7: |
13355 | // A using-declaration shall not name a scoped enumerator. |
13356 | // C++20 p1099 permits enumerators. |
13357 | if (EC && R && ED->isScoped()) |
13358 | Diag(SS.getBeginLoc(), |
13359 | getLangOpts().CPlusPlus20 |
13360 | ? diag::warn_cxx17_compat_using_decl_scoped_enumerator |
13361 | : diag::ext_using_decl_scoped_enumerator) |
13362 | << SS.getRange(); |
13363 | |
13364 | // We want to consider the scope of the enumerator |
13365 | NamedContext = ED->getDeclContext(); |
13366 | } |
13367 | } |
13368 | |
13369 | if (!CurContext->isRecord()) { |
13370 | // C++03 [namespace.udecl]p3: |
13371 | // C++0x [namespace.udecl]p8: |
13372 | // A using-declaration for a class member shall be a member-declaration. |
13373 | // C++20 [namespace.udecl]p7 |
13374 | // ... other than an enumerator ... |
13375 | |
13376 | // If we weren't able to compute a valid scope, it might validly be a |
13377 | // dependent class or enumeration scope. If we have a 'typename' keyword, |
13378 | // the scope must resolve to a class type. |
13379 | if (NamedContext ? !NamedContext->getRedeclContext()->isRecord() |
13380 | : !HasTypename) |
13381 | return false; // OK |
13382 | |
13383 | Diag(NameLoc, |
13384 | Cxx20Enumerator |
13385 | ? diag::warn_cxx17_compat_using_decl_class_member_enumerator |
13386 | : diag::err_using_decl_can_not_refer_to_class_member) |
13387 | << SS.getRange(); |
13388 | |
13389 | if (Cxx20Enumerator) |
13390 | return false; // OK |
13391 | |
13392 | auto *RD = NamedContext |
13393 | ? cast<CXXRecordDecl>(Val: NamedContext->getRedeclContext()) |
13394 | : nullptr; |
13395 | if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) { |
13396 | // See if there's a helpful fixit |
13397 | |
13398 | if (!R) { |
13399 | // We will have already diagnosed the problem on the template |
13400 | // definition, Maybe we should do so again? |
13401 | } else if (R->getAsSingle<TypeDecl>()) { |
13402 | if (getLangOpts().CPlusPlus11) { |
13403 | // Convert 'using X::Y;' to 'using Y = X::Y;'. |
13404 | Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) |
13405 | << 0 // alias declaration |
13406 | << FixItHint::CreateInsertion(SS.getBeginLoc(), |
13407 | NameInfo.getName().getAsString() + |
13408 | " = " ); |
13409 | } else { |
13410 | // Convert 'using X::Y;' to 'typedef X::Y Y;'. |
13411 | SourceLocation InsertLoc = getLocForEndOfToken(Loc: NameInfo.getEndLoc()); |
13412 | Diag(InsertLoc, diag::note_using_decl_class_member_workaround) |
13413 | << 1 // typedef declaration |
13414 | << FixItHint::CreateReplacement(UsingLoc, "typedef" ) |
13415 | << FixItHint::CreateInsertion( |
13416 | InsertLoc, " " + NameInfo.getName().getAsString()); |
13417 | } |
13418 | } else if (R->getAsSingle<VarDecl>()) { |
13419 | // Don't provide a fixit outside C++11 mode; we don't want to suggest |
13420 | // repeating the type of the static data member here. |
13421 | FixItHint FixIt; |
13422 | if (getLangOpts().CPlusPlus11) { |
13423 | // Convert 'using X::Y;' to 'auto &Y = X::Y;'. |
13424 | FixIt = FixItHint::CreateReplacement( |
13425 | RemoveRange: UsingLoc, Code: "auto &" + NameInfo.getName().getAsString() + " = " ); |
13426 | } |
13427 | |
13428 | Diag(UsingLoc, diag::note_using_decl_class_member_workaround) |
13429 | << 2 // reference declaration |
13430 | << FixIt; |
13431 | } else if (R->getAsSingle<EnumConstantDecl>()) { |
13432 | // Don't provide a fixit outside C++11 mode; we don't want to suggest |
13433 | // repeating the type of the enumeration here, and we can't do so if |
13434 | // the type is anonymous. |
13435 | FixItHint FixIt; |
13436 | if (getLangOpts().CPlusPlus11) { |
13437 | // Convert 'using X::Y;' to 'auto &Y = X::Y;'. |
13438 | FixIt = FixItHint::CreateReplacement( |
13439 | RemoveRange: UsingLoc, |
13440 | Code: "constexpr auto " + NameInfo.getName().getAsString() + " = " ); |
13441 | } |
13442 | |
13443 | Diag(UsingLoc, diag::note_using_decl_class_member_workaround) |
13444 | << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable |
13445 | << FixIt; |
13446 | } |
13447 | } |
13448 | |
13449 | return true; // Fail |
13450 | } |
13451 | |
13452 | // If the named context is dependent, we can't decide much. |
13453 | if (!NamedContext) { |
13454 | // FIXME: in C++0x, we can diagnose if we can prove that the |
13455 | // nested-name-specifier does not refer to a base class, which is |
13456 | // still possible in some cases. |
13457 | |
13458 | // Otherwise we have to conservatively report that things might be |
13459 | // okay. |
13460 | return false; |
13461 | } |
13462 | |
13463 | // The current scope is a record. |
13464 | if (!NamedContext->isRecord()) { |
13465 | // Ideally this would point at the last name in the specifier, |
13466 | // but we don't have that level of source info. |
13467 | Diag(SS.getBeginLoc(), |
13468 | Cxx20Enumerator |
13469 | ? diag::warn_cxx17_compat_using_decl_non_member_enumerator |
13470 | : diag::err_using_decl_nested_name_specifier_is_not_class) |
13471 | << SS.getScopeRep() << SS.getRange(); |
13472 | |
13473 | if (Cxx20Enumerator) |
13474 | return false; // OK |
13475 | |
13476 | return true; |
13477 | } |
13478 | |
13479 | if (!NamedContext->isDependentContext() && |
13480 | RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec&>(SS), DC: NamedContext)) |
13481 | return true; |
13482 | |
13483 | if (getLangOpts().CPlusPlus11) { |
13484 | // C++11 [namespace.udecl]p3: |
13485 | // In a using-declaration used as a member-declaration, the |
13486 | // nested-name-specifier shall name a base class of the class |
13487 | // being defined. |
13488 | |
13489 | if (cast<CXXRecordDecl>(Val: CurContext)->isProvablyNotDerivedFrom( |
13490 | Base: cast<CXXRecordDecl>(Val: NamedContext))) { |
13491 | |
13492 | if (Cxx20Enumerator) { |
13493 | Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator) |
13494 | << SS.getRange(); |
13495 | return false; |
13496 | } |
13497 | |
13498 | if (CurContext == NamedContext) { |
13499 | Diag(SS.getBeginLoc(), |
13500 | diag::err_using_decl_nested_name_specifier_is_current_class) |
13501 | << SS.getRange(); |
13502 | return !getLangOpts().CPlusPlus20; |
13503 | } |
13504 | |
13505 | if (!cast<CXXRecordDecl>(Val: NamedContext)->isInvalidDecl()) { |
13506 | Diag(SS.getBeginLoc(), |
13507 | diag::err_using_decl_nested_name_specifier_is_not_base_class) |
13508 | << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext) |
13509 | << SS.getRange(); |
13510 | } |
13511 | return true; |
13512 | } |
13513 | |
13514 | return false; |
13515 | } |
13516 | |
13517 | // C++03 [namespace.udecl]p4: |
13518 | // A using-declaration used as a member-declaration shall refer |
13519 | // to a member of a base class of the class being defined [etc.]. |
13520 | |
13521 | // Salient point: SS doesn't have to name a base class as long as |
13522 | // lookup only finds members from base classes. Therefore we can |
13523 | // diagnose here only if we can prove that can't happen, |
13524 | // i.e. if the class hierarchies provably don't intersect. |
13525 | |
13526 | // TODO: it would be nice if "definitely valid" results were cached |
13527 | // in the UsingDecl and UsingShadowDecl so that these checks didn't |
13528 | // need to be repeated. |
13529 | |
13530 | llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; |
13531 | auto Collect = [&Bases](const CXXRecordDecl *Base) { |
13532 | Bases.insert(Ptr: Base); |
13533 | return true; |
13534 | }; |
13535 | |
13536 | // Collect all bases. Return false if we find a dependent base. |
13537 | if (!cast<CXXRecordDecl>(Val: CurContext)->forallBases(BaseMatches: Collect)) |
13538 | return false; |
13539 | |
13540 | // Returns true if the base is dependent or is one of the accumulated base |
13541 | // classes. |
13542 | auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { |
13543 | return !Bases.count(Ptr: Base); |
13544 | }; |
13545 | |
13546 | // Return false if the class has a dependent base or if it or one |
13547 | // of its bases is present in the base set of the current context. |
13548 | if (Bases.count(Ptr: cast<CXXRecordDecl>(Val: NamedContext)) || |
13549 | !cast<CXXRecordDecl>(Val: NamedContext)->forallBases(BaseMatches: IsNotBase)) |
13550 | return false; |
13551 | |
13552 | Diag(SS.getRange().getBegin(), |
13553 | diag::err_using_decl_nested_name_specifier_is_not_base_class) |
13554 | << SS.getScopeRep() |
13555 | << cast<CXXRecordDecl>(CurContext) |
13556 | << SS.getRange(); |
13557 | |
13558 | return true; |
13559 | } |
13560 | |
13561 | Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, |
13562 | MultiTemplateParamsArg TemplateParamLists, |
13563 | SourceLocation UsingLoc, UnqualifiedId &Name, |
13564 | const ParsedAttributesView &AttrList, |
13565 | TypeResult Type, Decl *DeclFromDeclSpec) { |
13566 | // Get the innermost enclosing declaration scope. |
13567 | S = S->getDeclParent(); |
13568 | |
13569 | if (Type.isInvalid()) |
13570 | return nullptr; |
13571 | |
13572 | bool Invalid = false; |
13573 | DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); |
13574 | TypeSourceInfo *TInfo = nullptr; |
13575 | GetTypeFromParser(Ty: Type.get(), TInfo: &TInfo); |
13576 | |
13577 | if (DiagnoseClassNameShadow(DC: CurContext, Info: NameInfo)) |
13578 | return nullptr; |
13579 | |
13580 | if (DiagnoseUnexpandedParameterPack(Loc: Name.StartLocation, T: TInfo, |
13581 | UPPC: UPPC_DeclarationType)) { |
13582 | Invalid = true; |
13583 | TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy, |
13584 | Loc: TInfo->getTypeLoc().getBeginLoc()); |
13585 | } |
13586 | |
13587 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, |
13588 | TemplateParamLists.size() |
13589 | ? forRedeclarationInCurContext() |
13590 | : RedeclarationKind::ForVisibleRedeclaration); |
13591 | LookupName(R&: Previous, S); |
13592 | |
13593 | // Warn about shadowing the name of a template parameter. |
13594 | if (Previous.isSingleResult() && |
13595 | Previous.getFoundDecl()->isTemplateParameter()) { |
13596 | DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); |
13597 | Previous.clear(); |
13598 | } |
13599 | |
13600 | assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier && |
13601 | "name in alias declaration must be an identifier" ); |
13602 | TypeAliasDecl *NewTD = TypeAliasDecl::Create(C&: Context, DC: CurContext, StartLoc: UsingLoc, |
13603 | IdLoc: Name.StartLocation, |
13604 | Id: Name.Identifier, TInfo); |
13605 | |
13606 | NewTD->setAccess(AS); |
13607 | |
13608 | if (Invalid) |
13609 | NewTD->setInvalidDecl(); |
13610 | |
13611 | ProcessDeclAttributeList(S, NewTD, AttrList); |
13612 | AddPragmaAttributes(S, NewTD); |
13613 | ProcessAPINotes(NewTD); |
13614 | |
13615 | CheckTypedefForVariablyModifiedType(S, NewTD); |
13616 | Invalid |= NewTD->isInvalidDecl(); |
13617 | |
13618 | bool Redeclaration = false; |
13619 | |
13620 | NamedDecl *NewND; |
13621 | if (TemplateParamLists.size()) { |
13622 | TypeAliasTemplateDecl *OldDecl = nullptr; |
13623 | TemplateParameterList *OldTemplateParams = nullptr; |
13624 | |
13625 | if (TemplateParamLists.size() != 1) { |
13626 | Diag(UsingLoc, diag::err_alias_template_extra_headers) |
13627 | << SourceRange(TemplateParamLists[1]->getTemplateLoc(), |
13628 | TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); |
13629 | Invalid = true; |
13630 | } |
13631 | TemplateParameterList *TemplateParams = TemplateParamLists[0]; |
13632 | |
13633 | // Check that we can declare a template here. |
13634 | if (CheckTemplateDeclScope(S, TemplateParams)) |
13635 | return nullptr; |
13636 | |
13637 | // Only consider previous declarations in the same scope. |
13638 | FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage*/false, |
13639 | /*ExplicitInstantiationOrSpecialization*/AllowInlineNamespace: false); |
13640 | if (!Previous.empty()) { |
13641 | Redeclaration = true; |
13642 | |
13643 | OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); |
13644 | if (!OldDecl && !Invalid) { |
13645 | Diag(UsingLoc, diag::err_redefinition_different_kind) |
13646 | << Name.Identifier; |
13647 | |
13648 | NamedDecl *OldD = Previous.getRepresentativeDecl(); |
13649 | if (OldD->getLocation().isValid()) |
13650 | Diag(OldD->getLocation(), diag::note_previous_definition); |
13651 | |
13652 | Invalid = true; |
13653 | } |
13654 | |
13655 | if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { |
13656 | if (TemplateParameterListsAreEqual(TemplateParams, |
13657 | OldDecl->getTemplateParameters(), |
13658 | /*Complain=*/true, |
13659 | TPL_TemplateMatch)) |
13660 | OldTemplateParams = |
13661 | OldDecl->getMostRecentDecl()->getTemplateParameters(); |
13662 | else |
13663 | Invalid = true; |
13664 | |
13665 | TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); |
13666 | if (!Invalid && |
13667 | !Context.hasSameType(OldTD->getUnderlyingType(), |
13668 | NewTD->getUnderlyingType())) { |
13669 | // FIXME: The C++0x standard does not clearly say this is ill-formed, |
13670 | // but we can't reasonably accept it. |
13671 | Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) |
13672 | << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); |
13673 | if (OldTD->getLocation().isValid()) |
13674 | Diag(OldTD->getLocation(), diag::note_previous_definition); |
13675 | Invalid = true; |
13676 | } |
13677 | } |
13678 | } |
13679 | |
13680 | // Merge any previous default template arguments into our parameters, |
13681 | // and check the parameter list. |
13682 | if (CheckTemplateParameterList(NewParams: TemplateParams, OldParams: OldTemplateParams, |
13683 | TPC: TPC_TypeAliasTemplate)) |
13684 | return nullptr; |
13685 | |
13686 | TypeAliasTemplateDecl *NewDecl = |
13687 | TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, |
13688 | Name.Identifier, TemplateParams, |
13689 | NewTD); |
13690 | NewTD->setDescribedAliasTemplate(NewDecl); |
13691 | |
13692 | NewDecl->setAccess(AS); |
13693 | |
13694 | if (Invalid) |
13695 | NewDecl->setInvalidDecl(); |
13696 | else if (OldDecl) { |
13697 | NewDecl->setPreviousDecl(OldDecl); |
13698 | CheckRedeclarationInModule(NewDecl, OldDecl); |
13699 | } |
13700 | |
13701 | NewND = NewDecl; |
13702 | } else { |
13703 | if (auto *TD = dyn_cast_or_null<TagDecl>(Val: DeclFromDeclSpec)) { |
13704 | setTagNameForLinkagePurposes(TD, NewTD); |
13705 | handleTagNumbering(Tag: TD, TagScope: S); |
13706 | } |
13707 | ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); |
13708 | NewND = NewTD; |
13709 | } |
13710 | |
13711 | PushOnScopeChains(D: NewND, S); |
13712 | ActOnDocumentableDecl(NewND); |
13713 | return NewND; |
13714 | } |
13715 | |
13716 | Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, |
13717 | SourceLocation AliasLoc, |
13718 | IdentifierInfo *Alias, CXXScopeSpec &SS, |
13719 | SourceLocation IdentLoc, |
13720 | IdentifierInfo *Ident) { |
13721 | |
13722 | // Lookup the namespace name. |
13723 | LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); |
13724 | LookupParsedName(R, S, SS: &SS); |
13725 | |
13726 | if (R.isAmbiguous()) |
13727 | return nullptr; |
13728 | |
13729 | if (R.empty()) { |
13730 | if (!TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident)) { |
13731 | Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); |
13732 | return nullptr; |
13733 | } |
13734 | } |
13735 | assert(!R.isAmbiguous() && !R.empty()); |
13736 | NamedDecl *ND = R.getRepresentativeDecl(); |
13737 | |
13738 | // Check if we have a previous declaration with the same name. |
13739 | LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, |
13740 | RedeclarationKind::ForVisibleRedeclaration); |
13741 | LookupName(R&: PrevR, S); |
13742 | |
13743 | // Check we're not shadowing a template parameter. |
13744 | if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { |
13745 | DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); |
13746 | PrevR.clear(); |
13747 | } |
13748 | |
13749 | // Filter out any other lookup result from an enclosing scope. |
13750 | FilterLookupForScope(R&: PrevR, Ctx: CurContext, S, /*ConsiderLinkage*/false, |
13751 | /*AllowInlineNamespace*/false); |
13752 | |
13753 | // Find the previous declaration and check that we can redeclare it. |
13754 | NamespaceAliasDecl *Prev = nullptr; |
13755 | if (PrevR.isSingleResult()) { |
13756 | NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); |
13757 | if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(Val: PrevDecl)) { |
13758 | // We already have an alias with the same name that points to the same |
13759 | // namespace; check that it matches. |
13760 | if (AD->getNamespace()->Equals(getNamespaceDecl(D: ND))) { |
13761 | Prev = AD; |
13762 | } else if (isVisible(D: PrevDecl)) { |
13763 | Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) |
13764 | << Alias; |
13765 | Diag(AD->getLocation(), diag::note_previous_namespace_alias) |
13766 | << AD->getNamespace(); |
13767 | return nullptr; |
13768 | } |
13769 | } else if (isVisible(D: PrevDecl)) { |
13770 | unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) |
13771 | ? diag::err_redefinition |
13772 | : diag::err_redefinition_different_kind; |
13773 | Diag(AliasLoc, DiagID) << Alias; |
13774 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); |
13775 | return nullptr; |
13776 | } |
13777 | } |
13778 | |
13779 | // The use of a nested name specifier may trigger deprecation warnings. |
13780 | DiagnoseUseOfDecl(D: ND, Locs: IdentLoc); |
13781 | |
13782 | NamespaceAliasDecl *AliasDecl = |
13783 | NamespaceAliasDecl::Create(C&: Context, DC: CurContext, NamespaceLoc, AliasLoc, |
13784 | Alias, QualifierLoc: SS.getWithLocInContext(Context), |
13785 | IdentLoc, Namespace: ND); |
13786 | if (Prev) |
13787 | AliasDecl->setPreviousDecl(Prev); |
13788 | |
13789 | PushOnScopeChains(AliasDecl, S); |
13790 | return AliasDecl; |
13791 | } |
13792 | |
13793 | namespace { |
13794 | struct SpecialMemberExceptionSpecInfo |
13795 | : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { |
13796 | SourceLocation Loc; |
13797 | Sema::ImplicitExceptionSpecification ExceptSpec; |
13798 | |
13799 | SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, |
13800 | CXXSpecialMemberKind CSM, |
13801 | Sema::InheritedConstructorInfo *ICI, |
13802 | SourceLocation Loc) |
13803 | : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} |
13804 | |
13805 | bool visitBase(CXXBaseSpecifier *Base); |
13806 | bool visitField(FieldDecl *FD); |
13807 | |
13808 | void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, |
13809 | unsigned Quals); |
13810 | |
13811 | void visitSubobjectCall(Subobject Subobj, |
13812 | Sema::SpecialMemberOverloadResult SMOR); |
13813 | }; |
13814 | } |
13815 | |
13816 | bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { |
13817 | auto *RT = Base->getType()->getAs<RecordType>(); |
13818 | if (!RT) |
13819 | return false; |
13820 | |
13821 | auto *BaseClass = cast<CXXRecordDecl>(Val: RT->getDecl()); |
13822 | Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass); |
13823 | if (auto *BaseCtor = SMOR.getMethod()) { |
13824 | visitSubobjectCall(Subobj: Base, SMOR: BaseCtor); |
13825 | return false; |
13826 | } |
13827 | |
13828 | visitClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0); |
13829 | return false; |
13830 | } |
13831 | |
13832 | bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { |
13833 | if (CSM == CXXSpecialMemberKind::DefaultConstructor && |
13834 | FD->hasInClassInitializer()) { |
13835 | Expr *E = FD->getInClassInitializer(); |
13836 | if (!E) |
13837 | // FIXME: It's a little wasteful to build and throw away a |
13838 | // CXXDefaultInitExpr here. |
13839 | // FIXME: We should have a single context note pointing at Loc, and |
13840 | // this location should be MD->getLocation() instead, since that's |
13841 | // the location where we actually use the default init expression. |
13842 | E = S.BuildCXXDefaultInitExpr(Loc, Field: FD).get(); |
13843 | if (E) |
13844 | ExceptSpec.CalledExpr(E); |
13845 | } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) |
13846 | ->getAs<RecordType>()) { |
13847 | visitClassSubobject(Class: cast<CXXRecordDecl>(RT->getDecl()), Subobj: FD, |
13848 | Quals: FD->getType().getCVRQualifiers()); |
13849 | } |
13850 | return false; |
13851 | } |
13852 | |
13853 | void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, |
13854 | Subobject Subobj, |
13855 | unsigned Quals) { |
13856 | FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); |
13857 | bool IsMutable = Field && Field->isMutable(); |
13858 | visitSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable)); |
13859 | } |
13860 | |
13861 | void SpecialMemberExceptionSpecInfo::visitSubobjectCall( |
13862 | Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { |
13863 | // Note, if lookup fails, it doesn't matter what exception specification we |
13864 | // choose because the special member will be deleted. |
13865 | if (CXXMethodDecl *MD = SMOR.getMethod()) |
13866 | ExceptSpec.CalledDecl(CallLoc: getSubobjectLoc(Subobj), Method: MD); |
13867 | } |
13868 | |
13869 | bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { |
13870 | llvm::APSInt Result; |
13871 | ExprResult Converted = CheckConvertedConstantExpression( |
13872 | ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); |
13873 | ExplicitSpec.setExpr(Converted.get()); |
13874 | if (Converted.isUsable() && !Converted.get()->isValueDependent()) { |
13875 | ExplicitSpec.setKind(Result.getBoolValue() |
13876 | ? ExplicitSpecKind::ResolvedTrue |
13877 | : ExplicitSpecKind::ResolvedFalse); |
13878 | return true; |
13879 | } |
13880 | ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); |
13881 | return false; |
13882 | } |
13883 | |
13884 | ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { |
13885 | ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); |
13886 | if (!ExplicitExpr->isTypeDependent()) |
13887 | tryResolveExplicitSpecifier(ExplicitSpec&: ES); |
13888 | return ES; |
13889 | } |
13890 | |
13891 | static Sema::ImplicitExceptionSpecification |
13892 | ComputeDefaultedSpecialMemberExceptionSpec( |
13893 | Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM, |
13894 | Sema::InheritedConstructorInfo *ICI) { |
13895 | ComputingExceptionSpec CES(S, MD, Loc); |
13896 | |
13897 | CXXRecordDecl *ClassDecl = MD->getParent(); |
13898 | |
13899 | // C++ [except.spec]p14: |
13900 | // An implicitly declared special member function (Clause 12) shall have an |
13901 | // exception-specification. [...] |
13902 | SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); |
13903 | if (ClassDecl->isInvalidDecl()) |
13904 | return Info.ExceptSpec; |
13905 | |
13906 | // FIXME: If this diagnostic fires, we're probably missing a check for |
13907 | // attempting to resolve an exception specification before it's known |
13908 | // at a higher level. |
13909 | if (S.RequireCompleteType(MD->getLocation(), |
13910 | S.Context.getRecordType(ClassDecl), |
13911 | diag::err_exception_spec_incomplete_type)) |
13912 | return Info.ExceptSpec; |
13913 | |
13914 | // C++1z [except.spec]p7: |
13915 | // [Look for exceptions thrown by] a constructor selected [...] to |
13916 | // initialize a potentially constructed subobject, |
13917 | // C++1z [except.spec]p8: |
13918 | // The exception specification for an implicitly-declared destructor, or a |
13919 | // destructor without a noexcept-specifier, is potentially-throwing if and |
13920 | // only if any of the destructors for any of its potentially constructed |
13921 | // subojects is potentially throwing. |
13922 | // FIXME: We respect the first rule but ignore the "potentially constructed" |
13923 | // in the second rule to resolve a core issue (no number yet) that would have |
13924 | // us reject: |
13925 | // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; |
13926 | // struct B : A {}; |
13927 | // struct C : B { void f(); }; |
13928 | // ... due to giving B::~B() a non-throwing exception specification. |
13929 | Info.visit(Bases: Info.IsConstructor ? Info.VisitPotentiallyConstructedBases |
13930 | : Info.VisitAllBases); |
13931 | |
13932 | return Info.ExceptSpec; |
13933 | } |
13934 | |
13935 | namespace { |
13936 | /// RAII object to register a special member as being currently declared. |
13937 | struct DeclaringSpecialMember { |
13938 | Sema &S; |
13939 | Sema::SpecialMemberDecl D; |
13940 | Sema::ContextRAII SavedContext; |
13941 | bool WasAlreadyBeingDeclared; |
13942 | |
13943 | DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM) |
13944 | : S(S), D(RD, CSM), SavedContext(S, RD) { |
13945 | WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(Ptr: D).second; |
13946 | if (WasAlreadyBeingDeclared) |
13947 | // This almost never happens, but if it does, ensure that our cache |
13948 | // doesn't contain a stale result. |
13949 | S.SpecialMemberCache.clear(); |
13950 | else { |
13951 | // Register a note to be produced if we encounter an error while |
13952 | // declaring the special member. |
13953 | Sema::CodeSynthesisContext Ctx; |
13954 | Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; |
13955 | // FIXME: We don't have a location to use here. Using the class's |
13956 | // location maintains the fiction that we declare all special members |
13957 | // with the class, but (1) it's not clear that lying about that helps our |
13958 | // users understand what's going on, and (2) there may be outer contexts |
13959 | // on the stack (some of which are relevant) and printing them exposes |
13960 | // our lies. |
13961 | Ctx.PointOfInstantiation = RD->getLocation(); |
13962 | Ctx.Entity = RD; |
13963 | Ctx.SpecialMember = CSM; |
13964 | S.pushCodeSynthesisContext(Ctx); |
13965 | } |
13966 | } |
13967 | ~DeclaringSpecialMember() { |
13968 | if (!WasAlreadyBeingDeclared) { |
13969 | S.SpecialMembersBeingDeclared.erase(Ptr: D); |
13970 | S.popCodeSynthesisContext(); |
13971 | } |
13972 | } |
13973 | |
13974 | /// Are we already trying to declare this special member? |
13975 | bool isAlreadyBeingDeclared() const { |
13976 | return WasAlreadyBeingDeclared; |
13977 | } |
13978 | }; |
13979 | } |
13980 | |
13981 | void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { |
13982 | // Look up any existing declarations, but don't trigger declaration of all |
13983 | // implicit special members with this name. |
13984 | DeclarationName Name = FD->getDeclName(); |
13985 | LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, |
13986 | RedeclarationKind::ForExternalRedeclaration); |
13987 | for (auto *D : FD->getParent()->lookup(Name)) |
13988 | if (auto *Acceptable = R.getAcceptableDecl(D)) |
13989 | R.addDecl(Acceptable); |
13990 | R.resolveKind(); |
13991 | R.suppressDiagnostics(); |
13992 | |
13993 | CheckFunctionDeclaration(S, NewFD: FD, Previous&: R, /*IsMemberSpecialization*/ false, |
13994 | DeclIsDefn: FD->isThisDeclarationADefinition()); |
13995 | } |
13996 | |
13997 | void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, |
13998 | QualType ResultTy, |
13999 | ArrayRef<QualType> Args) { |
14000 | // Build an exception specification pointing back at this constructor. |
14001 | FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(S&: *this, MD: SpecialMem); |
14002 | |
14003 | LangAS AS = getDefaultCXXMethodAddrSpace(); |
14004 | if (AS != LangAS::Default) { |
14005 | EPI.TypeQuals.addAddressSpace(space: AS); |
14006 | } |
14007 | |
14008 | auto QT = Context.getFunctionType(ResultTy, Args, EPI); |
14009 | SpecialMem->setType(QT); |
14010 | |
14011 | // During template instantiation of implicit special member functions we need |
14012 | // a reliable TypeSourceInfo for the function prototype in order to allow |
14013 | // functions to be substituted. |
14014 | if (inTemplateInstantiation() && |
14015 | cast<CXXRecordDecl>(Val: SpecialMem->getParent())->isLambda()) { |
14016 | TypeSourceInfo *TSI = |
14017 | Context.getTrivialTypeSourceInfo(T: SpecialMem->getType()); |
14018 | SpecialMem->setTypeSourceInfo(TSI); |
14019 | } |
14020 | } |
14021 | |
14022 | CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( |
14023 | CXXRecordDecl *ClassDecl) { |
14024 | // C++ [class.ctor]p5: |
14025 | // A default constructor for a class X is a constructor of class X |
14026 | // that can be called without an argument. If there is no |
14027 | // user-declared constructor for class X, a default constructor is |
14028 | // implicitly declared. An implicitly-declared default constructor |
14029 | // is an inline public member of its class. |
14030 | assert(ClassDecl->needsImplicitDefaultConstructor() && |
14031 | "Should not build implicit default constructor!" ); |
14032 | |
14033 | DeclaringSpecialMember DSM(*this, ClassDecl, |
14034 | CXXSpecialMemberKind::DefaultConstructor); |
14035 | if (DSM.isAlreadyBeingDeclared()) |
14036 | return nullptr; |
14037 | |
14038 | bool Constexpr = defaultedSpecialMemberIsConstexpr( |
14039 | S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, ConstArg: false); |
14040 | |
14041 | // Create the actual constructor declaration. |
14042 | CanQualType ClassType |
14043 | = Context.getCanonicalType(T: Context.getTypeDeclType(ClassDecl)); |
14044 | SourceLocation ClassLoc = ClassDecl->getLocation(); |
14045 | DeclarationName Name |
14046 | = Context.DeclarationNames.getCXXConstructorName(Ty: ClassType); |
14047 | DeclarationNameInfo NameInfo(Name, ClassLoc); |
14048 | CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( |
14049 | C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, /*Type*/ T: QualType(), |
14050 | /*TInfo=*/nullptr, ES: ExplicitSpecifier(), |
14051 | UsesFPIntrin: getCurFPFeatures().isFPConstrained(), |
14052 | /*isInline=*/true, /*isImplicitlyDeclared=*/true, |
14053 | ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr |
14054 | : ConstexprSpecKind::Unspecified); |
14055 | DefaultCon->setAccess(AS_public); |
14056 | DefaultCon->setDefaulted(); |
14057 | |
14058 | setupImplicitSpecialMemberType(SpecialMem: DefaultCon, ResultTy: Context.VoidTy, Args: std::nullopt); |
14059 | |
14060 | if (getLangOpts().CUDA) |
14061 | CUDA().inferTargetForImplicitSpecialMember( |
14062 | ClassDecl, CXXSpecialMemberKind::DefaultConstructor, DefaultCon, |
14063 | /* ConstRHS */ false, |
14064 | /* Diagnose */ false); |
14065 | |
14066 | // We don't need to use SpecialMemberIsTrivial here; triviality for default |
14067 | // constructors is easy to compute. |
14068 | DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); |
14069 | |
14070 | // Note that we have declared this constructor. |
14071 | ++getASTContext().NumImplicitDefaultConstructorsDeclared; |
14072 | |
14073 | Scope *S = getScopeForContext(ClassDecl); |
14074 | CheckImplicitSpecialMemberDeclaration(S, DefaultCon); |
14075 | |
14076 | if (ShouldDeleteSpecialMember(DefaultCon, |
14077 | CXXSpecialMemberKind::DefaultConstructor)) |
14078 | SetDeclDeleted(DefaultCon, ClassLoc); |
14079 | |
14080 | if (S) |
14081 | PushOnScopeChains(DefaultCon, S, false); |
14082 | ClassDecl->addDecl(DefaultCon); |
14083 | |
14084 | return DefaultCon; |
14085 | } |
14086 | |
14087 | void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, |
14088 | CXXConstructorDecl *Constructor) { |
14089 | assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && |
14090 | !Constructor->doesThisDeclarationHaveABody() && |
14091 | !Constructor->isDeleted()) && |
14092 | "DefineImplicitDefaultConstructor - call it for implicit default ctor" ); |
14093 | if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) |
14094 | return; |
14095 | |
14096 | CXXRecordDecl *ClassDecl = Constructor->getParent(); |
14097 | assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor" ); |
14098 | if (ClassDecl->isInvalidDecl()) { |
14099 | return; |
14100 | } |
14101 | |
14102 | SynthesizedFunctionScope Scope(*this, Constructor); |
14103 | |
14104 | // The exception specification is needed because we are defining the |
14105 | // function. |
14106 | ResolveExceptionSpec(Loc: CurrentLocation, |
14107 | FPT: Constructor->getType()->castAs<FunctionProtoType>()); |
14108 | MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl); |
14109 | |
14110 | // Add a context note for diagnostics produced after this point. |
14111 | Scope.addContextNote(UseLoc: CurrentLocation); |
14112 | |
14113 | if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { |
14114 | Constructor->setInvalidDecl(); |
14115 | return; |
14116 | } |
14117 | |
14118 | SourceLocation Loc = Constructor->getEndLoc().isValid() |
14119 | ? Constructor->getEndLoc() |
14120 | : Constructor->getLocation(); |
14121 | Constructor->setBody(new (Context) CompoundStmt(Loc)); |
14122 | Constructor->markUsed(Context); |
14123 | |
14124 | if (ASTMutationListener *L = getASTMutationListener()) { |
14125 | L->CompletedImplicitDefinition(Constructor); |
14126 | } |
14127 | |
14128 | DiagnoseUninitializedFields(SemaRef&: *this, Constructor); |
14129 | } |
14130 | |
14131 | void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { |
14132 | // Perform any delayed checks on exception specifications. |
14133 | CheckDelayedMemberExceptionSpecs(); |
14134 | } |
14135 | |
14136 | /// Find or create the fake constructor we synthesize to model constructing an |
14137 | /// object of a derived class via a constructor of a base class. |
14138 | CXXConstructorDecl * |
14139 | Sema::findInheritingConstructor(SourceLocation Loc, |
14140 | CXXConstructorDecl *BaseCtor, |
14141 | ConstructorUsingShadowDecl *Shadow) { |
14142 | CXXRecordDecl *Derived = Shadow->getParent(); |
14143 | SourceLocation UsingLoc = Shadow->getLocation(); |
14144 | |
14145 | // FIXME: Add a new kind of DeclarationName for an inherited constructor. |
14146 | // For now we use the name of the base class constructor as a member of the |
14147 | // derived class to indicate a (fake) inherited constructor name. |
14148 | DeclarationName Name = BaseCtor->getDeclName(); |
14149 | |
14150 | // Check to see if we already have a fake constructor for this inherited |
14151 | // constructor call. |
14152 | for (NamedDecl *Ctor : Derived->lookup(Name)) |
14153 | if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) |
14154 | ->getInheritedConstructor() |
14155 | .getConstructor(), |
14156 | BaseCtor)) |
14157 | return cast<CXXConstructorDecl>(Ctor); |
14158 | |
14159 | DeclarationNameInfo NameInfo(Name, UsingLoc); |
14160 | TypeSourceInfo *TInfo = |
14161 | Context.getTrivialTypeSourceInfo(T: BaseCtor->getType(), Loc: UsingLoc); |
14162 | FunctionProtoTypeLoc ProtoLoc = |
14163 | TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); |
14164 | |
14165 | // Check the inherited constructor is valid and find the list of base classes |
14166 | // from which it was inherited. |
14167 | InheritedConstructorInfo ICI(*this, Loc, Shadow); |
14168 | |
14169 | bool Constexpr = BaseCtor->isConstexpr() && |
14170 | defaultedSpecialMemberIsConstexpr( |
14171 | S&: *this, ClassDecl: Derived, CSM: CXXSpecialMemberKind::DefaultConstructor, |
14172 | ConstArg: false, InheritedCtor: BaseCtor, Inherited: &ICI); |
14173 | |
14174 | CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( |
14175 | C&: Context, RD: Derived, StartLoc: UsingLoc, NameInfo, T: TInfo->getType(), TInfo, |
14176 | ES: BaseCtor->getExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(), |
14177 | /*isInline=*/true, |
14178 | /*isImplicitlyDeclared=*/true, |
14179 | ConstexprKind: Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, |
14180 | Inherited: InheritedConstructor(Shadow, BaseCtor), |
14181 | TrailingRequiresClause: BaseCtor->getTrailingRequiresClause()); |
14182 | if (Shadow->isInvalidDecl()) |
14183 | DerivedCtor->setInvalidDecl(); |
14184 | |
14185 | // Build an unevaluated exception specification for this fake constructor. |
14186 | const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); |
14187 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); |
14188 | EPI.ExceptionSpec.Type = EST_Unevaluated; |
14189 | EPI.ExceptionSpec.SourceDecl = DerivedCtor; |
14190 | DerivedCtor->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(), |
14191 | Args: FPT->getParamTypes(), EPI)); |
14192 | |
14193 | // Build the parameter declarations. |
14194 | SmallVector<ParmVarDecl *, 16> ParamDecls; |
14195 | for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { |
14196 | TypeSourceInfo *TInfo = |
14197 | Context.getTrivialTypeSourceInfo(T: FPT->getParamType(i: I), Loc: UsingLoc); |
14198 | ParmVarDecl *PD = ParmVarDecl::Create( |
14199 | Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, |
14200 | FPT->getParamType(i: I), TInfo, SC_None, /*DefArg=*/nullptr); |
14201 | PD->setScopeInfo(scopeDepth: 0, parameterIndex: I); |
14202 | PD->setImplicit(); |
14203 | // Ensure attributes are propagated onto parameters (this matters for |
14204 | // format, pass_object_size, ...). |
14205 | mergeDeclAttributes(New: PD, Old: BaseCtor->getParamDecl(I)); |
14206 | ParamDecls.push_back(Elt: PD); |
14207 | ProtoLoc.setParam(I, PD); |
14208 | } |
14209 | |
14210 | // Set up the new constructor. |
14211 | assert(!BaseCtor->isDeleted() && "should not use deleted constructor" ); |
14212 | DerivedCtor->setAccess(BaseCtor->getAccess()); |
14213 | DerivedCtor->setParams(ParamDecls); |
14214 | Derived->addDecl(DerivedCtor); |
14215 | |
14216 | if (ShouldDeleteSpecialMember(DerivedCtor, |
14217 | CXXSpecialMemberKind::DefaultConstructor, &ICI)) |
14218 | SetDeclDeleted(DerivedCtor, UsingLoc); |
14219 | |
14220 | return DerivedCtor; |
14221 | } |
14222 | |
14223 | void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { |
14224 | InheritedConstructorInfo ICI(*this, Ctor->getLocation(), |
14225 | Ctor->getInheritedConstructor().getShadowDecl()); |
14226 | ShouldDeleteSpecialMember(Ctor, CXXSpecialMemberKind::DefaultConstructor, |
14227 | &ICI, |
14228 | /*Diagnose*/ true); |
14229 | } |
14230 | |
14231 | void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, |
14232 | CXXConstructorDecl *Constructor) { |
14233 | CXXRecordDecl *ClassDecl = Constructor->getParent(); |
14234 | assert(Constructor->getInheritedConstructor() && |
14235 | !Constructor->doesThisDeclarationHaveABody() && |
14236 | !Constructor->isDeleted()); |
14237 | if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) |
14238 | return; |
14239 | |
14240 | // Initializations are performed "as if by a defaulted default constructor", |
14241 | // so enter the appropriate scope. |
14242 | SynthesizedFunctionScope Scope(*this, Constructor); |
14243 | |
14244 | // The exception specification is needed because we are defining the |
14245 | // function. |
14246 | ResolveExceptionSpec(Loc: CurrentLocation, |
14247 | FPT: Constructor->getType()->castAs<FunctionProtoType>()); |
14248 | MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl); |
14249 | |
14250 | // Add a context note for diagnostics produced after this point. |
14251 | Scope.addContextNote(UseLoc: CurrentLocation); |
14252 | |
14253 | ConstructorUsingShadowDecl *Shadow = |
14254 | Constructor->getInheritedConstructor().getShadowDecl(); |
14255 | CXXConstructorDecl *InheritedCtor = |
14256 | Constructor->getInheritedConstructor().getConstructor(); |
14257 | |
14258 | // [class.inhctor.init]p1: |
14259 | // initialization proceeds as if a defaulted default constructor is used to |
14260 | // initialize the D object and each base class subobject from which the |
14261 | // constructor was inherited |
14262 | |
14263 | InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); |
14264 | CXXRecordDecl *RD = Shadow->getParent(); |
14265 | SourceLocation InitLoc = Shadow->getLocation(); |
14266 | |
14267 | // Build explicit initializers for all base classes from which the |
14268 | // constructor was inherited. |
14269 | SmallVector<CXXCtorInitializer*, 8> Inits; |
14270 | for (bool VBase : {false, true}) { |
14271 | for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { |
14272 | if (B.isVirtual() != VBase) |
14273 | continue; |
14274 | |
14275 | auto *BaseRD = B.getType()->getAsCXXRecordDecl(); |
14276 | if (!BaseRD) |
14277 | continue; |
14278 | |
14279 | auto BaseCtor = ICI.findConstructorForBase(Base: BaseRD, Ctor: InheritedCtor); |
14280 | if (!BaseCtor.first) |
14281 | continue; |
14282 | |
14283 | MarkFunctionReferenced(CurrentLocation, BaseCtor.first); |
14284 | ExprResult Init = new (Context) CXXInheritedCtorInitExpr( |
14285 | InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); |
14286 | |
14287 | auto *TInfo = Context.getTrivialTypeSourceInfo(T: B.getType(), Loc: InitLoc); |
14288 | Inits.push_back(Elt: new (Context) CXXCtorInitializer( |
14289 | Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, |
14290 | SourceLocation())); |
14291 | } |
14292 | } |
14293 | |
14294 | // We now proceed as if for a defaulted default constructor, with the relevant |
14295 | // initializers replaced. |
14296 | |
14297 | if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Initializers: Inits)) { |
14298 | Constructor->setInvalidDecl(); |
14299 | return; |
14300 | } |
14301 | |
14302 | Constructor->setBody(new (Context) CompoundStmt(InitLoc)); |
14303 | Constructor->markUsed(Context); |
14304 | |
14305 | if (ASTMutationListener *L = getASTMutationListener()) { |
14306 | L->CompletedImplicitDefinition(Constructor); |
14307 | } |
14308 | |
14309 | DiagnoseUninitializedFields(SemaRef&: *this, Constructor); |
14310 | } |
14311 | |
14312 | CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { |
14313 | // C++ [class.dtor]p2: |
14314 | // If a class has no user-declared destructor, a destructor is |
14315 | // declared implicitly. An implicitly-declared destructor is an |
14316 | // inline public member of its class. |
14317 | assert(ClassDecl->needsImplicitDestructor()); |
14318 | |
14319 | DeclaringSpecialMember DSM(*this, ClassDecl, |
14320 | CXXSpecialMemberKind::Destructor); |
14321 | if (DSM.isAlreadyBeingDeclared()) |
14322 | return nullptr; |
14323 | |
14324 | bool Constexpr = defaultedSpecialMemberIsConstexpr( |
14325 | S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::Destructor, ConstArg: false); |
14326 | |
14327 | // Create the actual destructor declaration. |
14328 | CanQualType ClassType |
14329 | = Context.getCanonicalType(T: Context.getTypeDeclType(ClassDecl)); |
14330 | SourceLocation ClassLoc = ClassDecl->getLocation(); |
14331 | DeclarationName Name |
14332 | = Context.DeclarationNames.getCXXDestructorName(Ty: ClassType); |
14333 | DeclarationNameInfo NameInfo(Name, ClassLoc); |
14334 | CXXDestructorDecl *Destructor = CXXDestructorDecl::Create( |
14335 | C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), TInfo: nullptr, |
14336 | UsesFPIntrin: getCurFPFeatures().isFPConstrained(), |
14337 | /*isInline=*/true, |
14338 | /*isImplicitlyDeclared=*/true, |
14339 | ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr |
14340 | : ConstexprSpecKind::Unspecified); |
14341 | Destructor->setAccess(AS_public); |
14342 | Destructor->setDefaulted(); |
14343 | |
14344 | setupImplicitSpecialMemberType(SpecialMem: Destructor, ResultTy: Context.VoidTy, Args: std::nullopt); |
14345 | |
14346 | if (getLangOpts().CUDA) |
14347 | CUDA().inferTargetForImplicitSpecialMember( |
14348 | ClassDecl, CXXSpecialMemberKind::Destructor, Destructor, |
14349 | /* ConstRHS */ false, |
14350 | /* Diagnose */ false); |
14351 | |
14352 | // We don't need to use SpecialMemberIsTrivial here; triviality for |
14353 | // destructors is easy to compute. |
14354 | Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); |
14355 | Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || |
14356 | ClassDecl->hasTrivialDestructorForCall()); |
14357 | |
14358 | // Note that we have declared this destructor. |
14359 | ++getASTContext().NumImplicitDestructorsDeclared; |
14360 | |
14361 | Scope *S = getScopeForContext(ClassDecl); |
14362 | CheckImplicitSpecialMemberDeclaration(S, Destructor); |
14363 | |
14364 | // We can't check whether an implicit destructor is deleted before we complete |
14365 | // the definition of the class, because its validity depends on the alignment |
14366 | // of the class. We'll check this from ActOnFields once the class is complete. |
14367 | if (ClassDecl->isCompleteDefinition() && |
14368 | ShouldDeleteSpecialMember(Destructor, CXXSpecialMemberKind::Destructor)) |
14369 | SetDeclDeleted(Destructor, ClassLoc); |
14370 | |
14371 | // Introduce this destructor into its scope. |
14372 | if (S) |
14373 | PushOnScopeChains(Destructor, S, false); |
14374 | ClassDecl->addDecl(Destructor); |
14375 | |
14376 | return Destructor; |
14377 | } |
14378 | |
14379 | void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, |
14380 | CXXDestructorDecl *Destructor) { |
14381 | assert((Destructor->isDefaulted() && |
14382 | !Destructor->doesThisDeclarationHaveABody() && |
14383 | !Destructor->isDeleted()) && |
14384 | "DefineImplicitDestructor - call it for implicit default dtor" ); |
14385 | if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) |
14386 | return; |
14387 | |
14388 | CXXRecordDecl *ClassDecl = Destructor->getParent(); |
14389 | assert(ClassDecl && "DefineImplicitDestructor - invalid destructor" ); |
14390 | |
14391 | SynthesizedFunctionScope Scope(*this, Destructor); |
14392 | |
14393 | // The exception specification is needed because we are defining the |
14394 | // function. |
14395 | ResolveExceptionSpec(Loc: CurrentLocation, |
14396 | FPT: Destructor->getType()->castAs<FunctionProtoType>()); |
14397 | MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl); |
14398 | |
14399 | // Add a context note for diagnostics produced after this point. |
14400 | Scope.addContextNote(UseLoc: CurrentLocation); |
14401 | |
14402 | MarkBaseAndMemberDestructorsReferenced(Location: Destructor->getLocation(), |
14403 | ClassDecl: Destructor->getParent()); |
14404 | |
14405 | if (CheckDestructor(Destructor)) { |
14406 | Destructor->setInvalidDecl(); |
14407 | return; |
14408 | } |
14409 | |
14410 | SourceLocation Loc = Destructor->getEndLoc().isValid() |
14411 | ? Destructor->getEndLoc() |
14412 | : Destructor->getLocation(); |
14413 | Destructor->setBody(new (Context) CompoundStmt(Loc)); |
14414 | Destructor->markUsed(Context); |
14415 | |
14416 | if (ASTMutationListener *L = getASTMutationListener()) { |
14417 | L->CompletedImplicitDefinition(Destructor); |
14418 | } |
14419 | } |
14420 | |
14421 | void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, |
14422 | CXXDestructorDecl *Destructor) { |
14423 | if (Destructor->isInvalidDecl()) |
14424 | return; |
14425 | |
14426 | CXXRecordDecl *ClassDecl = Destructor->getParent(); |
14427 | assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && |
14428 | "implicit complete dtors unneeded outside MS ABI" ); |
14429 | assert(ClassDecl->getNumVBases() > 0 && |
14430 | "complete dtor only exists for classes with vbases" ); |
14431 | |
14432 | SynthesizedFunctionScope Scope(*this, Destructor); |
14433 | |
14434 | // Add a context note for diagnostics produced after this point. |
14435 | Scope.addContextNote(UseLoc: CurrentLocation); |
14436 | |
14437 | MarkVirtualBaseDestructorsReferenced(Location: Destructor->getLocation(), ClassDecl); |
14438 | } |
14439 | |
14440 | /// Perform any semantic analysis which needs to be delayed until all |
14441 | /// pending class member declarations have been parsed. |
14442 | void Sema::ActOnFinishCXXMemberDecls() { |
14443 | // If the context is an invalid C++ class, just suppress these checks. |
14444 | if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: CurContext)) { |
14445 | if (Record->isInvalidDecl()) { |
14446 | DelayedOverridingExceptionSpecChecks.clear(); |
14447 | DelayedEquivalentExceptionSpecChecks.clear(); |
14448 | return; |
14449 | } |
14450 | checkForMultipleExportedDefaultConstructors(S&: *this, Class: Record); |
14451 | } |
14452 | } |
14453 | |
14454 | void Sema::ActOnFinishCXXNonNestedClass() { |
14455 | referenceDLLExportedClassMethods(); |
14456 | |
14457 | if (!DelayedDllExportMemberFunctions.empty()) { |
14458 | SmallVector<CXXMethodDecl*, 4> WorkList; |
14459 | std::swap(LHS&: DelayedDllExportMemberFunctions, RHS&: WorkList); |
14460 | for (CXXMethodDecl *M : WorkList) { |
14461 | DefineDefaultedFunction(*this, M, M->getLocation()); |
14462 | |
14463 | // Pass the method to the consumer to get emitted. This is not necessary |
14464 | // for explicit instantiation definitions, as they will get emitted |
14465 | // anyway. |
14466 | if (M->getParent()->getTemplateSpecializationKind() != |
14467 | TSK_ExplicitInstantiationDefinition) |
14468 | ActOnFinishInlineFunctionDef(M); |
14469 | } |
14470 | } |
14471 | } |
14472 | |
14473 | void Sema::referenceDLLExportedClassMethods() { |
14474 | if (!DelayedDllExportClasses.empty()) { |
14475 | // Calling ReferenceDllExportedMembers might cause the current function to |
14476 | // be called again, so use a local copy of DelayedDllExportClasses. |
14477 | SmallVector<CXXRecordDecl *, 4> WorkList; |
14478 | std::swap(LHS&: DelayedDllExportClasses, RHS&: WorkList); |
14479 | for (CXXRecordDecl *Class : WorkList) |
14480 | ReferenceDllExportedMembers(S&: *this, Class); |
14481 | } |
14482 | } |
14483 | |
14484 | void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { |
14485 | assert(getLangOpts().CPlusPlus11 && |
14486 | "adjusting dtor exception specs was introduced in c++11" ); |
14487 | |
14488 | if (Destructor->isDependentContext()) |
14489 | return; |
14490 | |
14491 | // C++11 [class.dtor]p3: |
14492 | // A declaration of a destructor that does not have an exception- |
14493 | // specification is implicitly considered to have the same exception- |
14494 | // specification as an implicit declaration. |
14495 | const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); |
14496 | if (DtorType->hasExceptionSpec()) |
14497 | return; |
14498 | |
14499 | // Replace the destructor's type, building off the existing one. Fortunately, |
14500 | // the only thing of interest in the destructor type is its extended info. |
14501 | // The return and arguments are fixed. |
14502 | FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); |
14503 | EPI.ExceptionSpec.Type = EST_Unevaluated; |
14504 | EPI.ExceptionSpec.SourceDecl = Destructor; |
14505 | Destructor->setType( |
14506 | Context.getFunctionType(ResultTy: Context.VoidTy, Args: std::nullopt, EPI)); |
14507 | |
14508 | // FIXME: If the destructor has a body that could throw, and the newly created |
14509 | // spec doesn't allow exceptions, we should emit a warning, because this |
14510 | // change in behavior can break conforming C++03 programs at runtime. |
14511 | // However, we don't have a body or an exception specification yet, so it |
14512 | // needs to be done somewhere else. |
14513 | } |
14514 | |
14515 | namespace { |
14516 | /// An abstract base class for all helper classes used in building the |
14517 | // copy/move operators. These classes serve as factory functions and help us |
14518 | // avoid using the same Expr* in the AST twice. |
14519 | class ExprBuilder { |
14520 | ExprBuilder(const ExprBuilder&) = delete; |
14521 | ExprBuilder &operator=(const ExprBuilder&) = delete; |
14522 | |
14523 | protected: |
14524 | static Expr *assertNotNull(Expr *E) { |
14525 | assert(E && "Expression construction must not fail." ); |
14526 | return E; |
14527 | } |
14528 | |
14529 | public: |
14530 | ExprBuilder() {} |
14531 | virtual ~ExprBuilder() {} |
14532 | |
14533 | virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; |
14534 | }; |
14535 | |
14536 | class RefBuilder: public ExprBuilder { |
14537 | VarDecl *Var; |
14538 | QualType VarType; |
14539 | |
14540 | public: |
14541 | Expr *build(Sema &S, SourceLocation Loc) const override { |
14542 | return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); |
14543 | } |
14544 | |
14545 | RefBuilder(VarDecl *Var, QualType VarType) |
14546 | : Var(Var), VarType(VarType) {} |
14547 | }; |
14548 | |
14549 | class ThisBuilder: public ExprBuilder { |
14550 | public: |
14551 | Expr *build(Sema &S, SourceLocation Loc) const override { |
14552 | return assertNotNull(E: S.ActOnCXXThis(Loc).getAs<Expr>()); |
14553 | } |
14554 | }; |
14555 | |
14556 | class CastBuilder: public ExprBuilder { |
14557 | const ExprBuilder &Builder; |
14558 | QualType Type; |
14559 | ExprValueKind Kind; |
14560 | const CXXCastPath &Path; |
14561 | |
14562 | public: |
14563 | Expr *build(Sema &S, SourceLocation Loc) const override { |
14564 | return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, |
14565 | CK_UncheckedDerivedToBase, Kind, |
14566 | &Path).get()); |
14567 | } |
14568 | |
14569 | CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, |
14570 | const CXXCastPath &Path) |
14571 | : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} |
14572 | }; |
14573 | |
14574 | class DerefBuilder: public ExprBuilder { |
14575 | const ExprBuilder &Builder; |
14576 | |
14577 | public: |
14578 | Expr *build(Sema &S, SourceLocation Loc) const override { |
14579 | return assertNotNull( |
14580 | E: S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: Builder.build(S, Loc)).get()); |
14581 | } |
14582 | |
14583 | DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} |
14584 | }; |
14585 | |
14586 | class MemberBuilder: public ExprBuilder { |
14587 | const ExprBuilder &Builder; |
14588 | QualType Type; |
14589 | CXXScopeSpec SS; |
14590 | bool IsArrow; |
14591 | LookupResult &MemberLookup; |
14592 | |
14593 | public: |
14594 | Expr *build(Sema &S, SourceLocation Loc) const override { |
14595 | return assertNotNull(S.BuildMemberReferenceExpr( |
14596 | Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), |
14597 | nullptr, MemberLookup, nullptr, nullptr).get()); |
14598 | } |
14599 | |
14600 | MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, |
14601 | LookupResult &MemberLookup) |
14602 | : Builder(Builder), Type(Type), IsArrow(IsArrow), |
14603 | MemberLookup(MemberLookup) {} |
14604 | }; |
14605 | |
14606 | class MoveCastBuilder: public ExprBuilder { |
14607 | const ExprBuilder &Builder; |
14608 | |
14609 | public: |
14610 | Expr *build(Sema &S, SourceLocation Loc) const override { |
14611 | return assertNotNull(E: CastForMoving(SemaRef&: S, E: Builder.build(S, Loc))); |
14612 | } |
14613 | |
14614 | MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} |
14615 | }; |
14616 | |
14617 | class LvalueConvBuilder: public ExprBuilder { |
14618 | const ExprBuilder &Builder; |
14619 | |
14620 | public: |
14621 | Expr *build(Sema &S, SourceLocation Loc) const override { |
14622 | return assertNotNull( |
14623 | E: S.DefaultLvalueConversion(E: Builder.build(S, Loc)).get()); |
14624 | } |
14625 | |
14626 | LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} |
14627 | }; |
14628 | |
14629 | class SubscriptBuilder: public ExprBuilder { |
14630 | const ExprBuilder &Base; |
14631 | const ExprBuilder &Index; |
14632 | |
14633 | public: |
14634 | Expr *build(Sema &S, SourceLocation Loc) const override { |
14635 | return assertNotNull(E: S.CreateBuiltinArraySubscriptExpr( |
14636 | Base: Base.build(S, Loc), LLoc: Loc, Idx: Index.build(S, Loc), RLoc: Loc).get()); |
14637 | } |
14638 | |
14639 | SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) |
14640 | : Base(Base), Index(Index) {} |
14641 | }; |
14642 | |
14643 | } // end anonymous namespace |
14644 | |
14645 | /// When generating a defaulted copy or move assignment operator, if a field |
14646 | /// should be copied with __builtin_memcpy rather than via explicit assignments, |
14647 | /// do so. This optimization only applies for arrays of scalars, and for arrays |
14648 | /// of class type where the selected copy/move-assignment operator is trivial. |
14649 | static StmtResult |
14650 | buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, |
14651 | const ExprBuilder &ToB, const ExprBuilder &FromB) { |
14652 | // Compute the size of the memory buffer to be copied. |
14653 | QualType SizeType = S.Context.getSizeType(); |
14654 | llvm::APInt Size(S.Context.getTypeSize(T: SizeType), |
14655 | S.Context.getTypeSizeInChars(T).getQuantity()); |
14656 | |
14657 | // Take the address of the field references for "from" and "to". We |
14658 | // directly construct UnaryOperators here because semantic analysis |
14659 | // does not permit us to take the address of an xvalue. |
14660 | Expr *From = FromB.build(S, Loc); |
14661 | From = UnaryOperator::Create( |
14662 | C: S.Context, input: From, opc: UO_AddrOf, type: S.Context.getPointerType(T: From->getType()), |
14663 | VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides()); |
14664 | Expr *To = ToB.build(S, Loc); |
14665 | To = UnaryOperator::Create( |
14666 | C: S.Context, input: To, opc: UO_AddrOf, type: S.Context.getPointerType(T: To->getType()), |
14667 | VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides()); |
14668 | |
14669 | const Type *E = T->getBaseElementTypeUnsafe(); |
14670 | bool NeedsCollectableMemCpy = |
14671 | E->isRecordType() && |
14672 | E->castAs<RecordType>()->getDecl()->hasObjectMember(); |
14673 | |
14674 | // Create a reference to the __builtin_objc_memmove_collectable function |
14675 | StringRef MemCpyName = NeedsCollectableMemCpy ? |
14676 | "__builtin_objc_memmove_collectable" : |
14677 | "__builtin_memcpy" ; |
14678 | LookupResult R(S, &S.Context.Idents.get(Name: MemCpyName), Loc, |
14679 | Sema::LookupOrdinaryName); |
14680 | S.LookupName(R, S: S.TUScope, AllowBuiltinCreation: true); |
14681 | |
14682 | FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); |
14683 | if (!MemCpy) |
14684 | // Something went horribly wrong earlier, and we will have complained |
14685 | // about it. |
14686 | return StmtError(); |
14687 | |
14688 | ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, |
14689 | VK_PRValue, Loc, nullptr); |
14690 | assert(MemCpyRef.isUsable() && "Builtin reference cannot fail" ); |
14691 | |
14692 | Expr *CallArgs[] = { |
14693 | To, From, IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc) |
14694 | }; |
14695 | ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), |
14696 | Loc, CallArgs, Loc); |
14697 | |
14698 | assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!" ); |
14699 | return Call.getAs<Stmt>(); |
14700 | } |
14701 | |
14702 | /// Builds a statement that copies/moves the given entity from \p From to |
14703 | /// \c To. |
14704 | /// |
14705 | /// This routine is used to copy/move the members of a class with an |
14706 | /// implicitly-declared copy/move assignment operator. When the entities being |
14707 | /// copied are arrays, this routine builds for loops to copy them. |
14708 | /// |
14709 | /// \param S The Sema object used for type-checking. |
14710 | /// |
14711 | /// \param Loc The location where the implicit copy/move is being generated. |
14712 | /// |
14713 | /// \param T The type of the expressions being copied/moved. Both expressions |
14714 | /// must have this type. |
14715 | /// |
14716 | /// \param To The expression we are copying/moving to. |
14717 | /// |
14718 | /// \param From The expression we are copying/moving from. |
14719 | /// |
14720 | /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. |
14721 | /// Otherwise, it's a non-static member subobject. |
14722 | /// |
14723 | /// \param Copying Whether we're copying or moving. |
14724 | /// |
14725 | /// \param Depth Internal parameter recording the depth of the recursion. |
14726 | /// |
14727 | /// \returns A statement or a loop that copies the expressions, or StmtResult(0) |
14728 | /// if a memcpy should be used instead. |
14729 | static StmtResult |
14730 | buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, |
14731 | const ExprBuilder &To, const ExprBuilder &From, |
14732 | bool CopyingBaseSubobject, bool Copying, |
14733 | unsigned Depth = 0) { |
14734 | // C++11 [class.copy]p28: |
14735 | // Each subobject is assigned in the manner appropriate to its type: |
14736 | // |
14737 | // - if the subobject is of class type, as if by a call to operator= with |
14738 | // the subobject as the object expression and the corresponding |
14739 | // subobject of x as a single function argument (as if by explicit |
14740 | // qualification; that is, ignoring any possible virtual overriding |
14741 | // functions in more derived classes); |
14742 | // |
14743 | // C++03 [class.copy]p13: |
14744 | // - if the subobject is of class type, the copy assignment operator for |
14745 | // the class is used (as if by explicit qualification; that is, |
14746 | // ignoring any possible virtual overriding functions in more derived |
14747 | // classes); |
14748 | if (const RecordType *RecordTy = T->getAs<RecordType>()) { |
14749 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: RecordTy->getDecl()); |
14750 | |
14751 | // Look for operator=. |
14752 | DeclarationName Name |
14753 | = S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal); |
14754 | LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); |
14755 | S.LookupQualifiedName(OpLookup, ClassDecl, false); |
14756 | |
14757 | // Prior to C++11, filter out any result that isn't a copy/move-assignment |
14758 | // operator. |
14759 | if (!S.getLangOpts().CPlusPlus11) { |
14760 | LookupResult::Filter F = OpLookup.makeFilter(); |
14761 | while (F.hasNext()) { |
14762 | NamedDecl *D = F.next(); |
14763 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) |
14764 | if (Method->isCopyAssignmentOperator() || |
14765 | (!Copying && Method->isMoveAssignmentOperator())) |
14766 | continue; |
14767 | |
14768 | F.erase(); |
14769 | } |
14770 | F.done(); |
14771 | } |
14772 | |
14773 | // Suppress the protected check (C++ [class.protected]) for each of the |
14774 | // assignment operators we found. This strange dance is required when |
14775 | // we're assigning via a base classes's copy-assignment operator. To |
14776 | // ensure that we're getting the right base class subobject (without |
14777 | // ambiguities), we need to cast "this" to that subobject type; to |
14778 | // ensure that we don't go through the virtual call mechanism, we need |
14779 | // to qualify the operator= name with the base class (see below). However, |
14780 | // this means that if the base class has a protected copy assignment |
14781 | // operator, the protected member access check will fail. So, we |
14782 | // rewrite "protected" access to "public" access in this case, since we |
14783 | // know by construction that we're calling from a derived class. |
14784 | if (CopyingBaseSubobject) { |
14785 | for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); |
14786 | L != LEnd; ++L) { |
14787 | if (L.getAccess() == AS_protected) |
14788 | L.setAccess(AS_public); |
14789 | } |
14790 | } |
14791 | |
14792 | // Create the nested-name-specifier that will be used to qualify the |
14793 | // reference to operator=; this is required to suppress the virtual |
14794 | // call mechanism. |
14795 | CXXScopeSpec SS; |
14796 | const Type *CanonicalT = S.Context.getCanonicalType(T: T.getTypePtr()); |
14797 | SS.MakeTrivial(Context&: S.Context, |
14798 | Qualifier: NestedNameSpecifier::Create(Context: S.Context, Prefix: nullptr, Template: false, |
14799 | T: CanonicalT), |
14800 | R: Loc); |
14801 | |
14802 | // Create the reference to operator=. |
14803 | ExprResult OpEqualRef |
14804 | = S.BuildMemberReferenceExpr(Base: To.build(S, Loc), BaseType: T, OpLoc: Loc, /*IsArrow=*/false, |
14805 | SS, /*TemplateKWLoc=*/SourceLocation(), |
14806 | /*FirstQualifierInScope=*/nullptr, |
14807 | R&: OpLookup, |
14808 | /*TemplateArgs=*/nullptr, /*S*/nullptr, |
14809 | /*SuppressQualifierCheck=*/true); |
14810 | if (OpEqualRef.isInvalid()) |
14811 | return StmtError(); |
14812 | |
14813 | // Build the call to the assignment operator. |
14814 | |
14815 | Expr *FromInst = From.build(S, Loc); |
14816 | ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/S: nullptr, |
14817 | MemExpr: OpEqualRef.getAs<Expr>(), |
14818 | LParenLoc: Loc, Args: FromInst, RParenLoc: Loc); |
14819 | if (Call.isInvalid()) |
14820 | return StmtError(); |
14821 | |
14822 | // If we built a call to a trivial 'operator=' while copying an array, |
14823 | // bail out. We'll replace the whole shebang with a memcpy. |
14824 | CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Val: Call.get()); |
14825 | if (CE && CE->getMethodDecl()->isTrivial() && Depth) |
14826 | return StmtResult((Stmt*)nullptr); |
14827 | |
14828 | // Convert to an expression-statement, and clean up any produced |
14829 | // temporaries. |
14830 | return S.ActOnExprStmt(Arg: Call); |
14831 | } |
14832 | |
14833 | // - if the subobject is of scalar type, the built-in assignment |
14834 | // operator is used. |
14835 | const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); |
14836 | if (!ArrayTy) { |
14837 | ExprResult Assignment = S.CreateBuiltinBinOp( |
14838 | OpLoc: Loc, Opc: BO_Assign, LHSExpr: To.build(S, Loc), RHSExpr: From.build(S, Loc)); |
14839 | if (Assignment.isInvalid()) |
14840 | return StmtError(); |
14841 | return S.ActOnExprStmt(Arg: Assignment); |
14842 | } |
14843 | |
14844 | // - if the subobject is an array, each element is assigned, in the |
14845 | // manner appropriate to the element type; |
14846 | |
14847 | // Construct a loop over the array bounds, e.g., |
14848 | // |
14849 | // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) |
14850 | // |
14851 | // that will copy each of the array elements. |
14852 | QualType SizeType = S.Context.getSizeType(); |
14853 | |
14854 | // Create the iteration variable. |
14855 | IdentifierInfo *IterationVarName = nullptr; |
14856 | { |
14857 | SmallString<8> Str; |
14858 | llvm::raw_svector_ostream OS(Str); |
14859 | OS << "__i" << Depth; |
14860 | IterationVarName = &S.Context.Idents.get(Name: OS.str()); |
14861 | } |
14862 | VarDecl *IterationVar = VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, |
14863 | Id: IterationVarName, T: SizeType, |
14864 | TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc), |
14865 | S: SC_None); |
14866 | |
14867 | // Initialize the iteration variable to zero. |
14868 | llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0); |
14869 | IterationVar->setInit(IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc)); |
14870 | |
14871 | // Creates a reference to the iteration variable. |
14872 | RefBuilder IterationVarRef(IterationVar, SizeType); |
14873 | LvalueConvBuilder IterationVarRefRVal(IterationVarRef); |
14874 | |
14875 | // Create the DeclStmt that holds the iteration variable. |
14876 | Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); |
14877 | |
14878 | // Subscript the "from" and "to" expressions with the iteration variable. |
14879 | SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); |
14880 | MoveCastBuilder FromIndexMove(FromIndexCopy); |
14881 | const ExprBuilder *FromIndex; |
14882 | if (Copying) |
14883 | FromIndex = &FromIndexCopy; |
14884 | else |
14885 | FromIndex = &FromIndexMove; |
14886 | |
14887 | SubscriptBuilder ToIndex(To, IterationVarRefRVal); |
14888 | |
14889 | // Build the copy/move for an individual element of the array. |
14890 | StmtResult Copy = |
14891 | buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), |
14892 | ToIndex, *FromIndex, CopyingBaseSubobject, |
14893 | Copying, Depth + 1); |
14894 | // Bail out if copying fails or if we determined that we should use memcpy. |
14895 | if (Copy.isInvalid() || !Copy.get()) |
14896 | return Copy; |
14897 | |
14898 | // Create the comparison against the array bound. |
14899 | llvm::APInt Upper |
14900 | = ArrayTy->getSize().zextOrTrunc(width: S.Context.getTypeSize(T: SizeType)); |
14901 | Expr *Comparison = BinaryOperator::Create( |
14902 | C: S.Context, lhs: IterationVarRefRVal.build(S, Loc), |
14903 | rhs: IntegerLiteral::Create(C: S.Context, V: Upper, type: SizeType, l: Loc), opc: BO_NE, |
14904 | ResTy: S.Context.BoolTy, VK: VK_PRValue, OK: OK_Ordinary, opLoc: Loc, |
14905 | FPFeatures: S.CurFPFeatureOverrides()); |
14906 | |
14907 | // Create the pre-increment of the iteration variable. We can determine |
14908 | // whether the increment will overflow based on the value of the array |
14909 | // bound. |
14910 | Expr *Increment = UnaryOperator::Create( |
14911 | C: S.Context, input: IterationVarRef.build(S, Loc), opc: UO_PreInc, type: SizeType, VK: VK_LValue, |
14912 | OK: OK_Ordinary, l: Loc, CanOverflow: Upper.isMaxValue(), FPFeatures: S.CurFPFeatureOverrides()); |
14913 | |
14914 | // Construct the loop that copies all elements of this array. |
14915 | return S.ActOnForStmt( |
14916 | ForLoc: Loc, LParenLoc: Loc, First: InitStmt, |
14917 | Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Comparison, CK: Sema::ConditionKind::Boolean), |
14918 | Third: S.MakeFullDiscardedValueExpr(Arg: Increment), RParenLoc: Loc, Body: Copy.get()); |
14919 | } |
14920 | |
14921 | static StmtResult |
14922 | buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, |
14923 | const ExprBuilder &To, const ExprBuilder &From, |
14924 | bool CopyingBaseSubobject, bool Copying) { |
14925 | // Maybe we should use a memcpy? |
14926 | if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && |
14927 | T.isTriviallyCopyableType(Context: S.Context)) |
14928 | return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From); |
14929 | |
14930 | StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, |
14931 | CopyingBaseSubobject, |
14932 | Copying, Depth: 0)); |
14933 | |
14934 | // If we ended up picking a trivial assignment operator for an array of a |
14935 | // non-trivially-copyable class type, just emit a memcpy. |
14936 | if (!Result.isInvalid() && !Result.get()) |
14937 | return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From); |
14938 | |
14939 | return Result; |
14940 | } |
14941 | |
14942 | CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { |
14943 | // Note: The following rules are largely analoguous to the copy |
14944 | // constructor rules. Note that virtual bases are not taken into account |
14945 | // for determining the argument type of the operator. Note also that |
14946 | // operators taking an object instead of a reference are allowed. |
14947 | assert(ClassDecl->needsImplicitCopyAssignment()); |
14948 | |
14949 | DeclaringSpecialMember DSM(*this, ClassDecl, |
14950 | CXXSpecialMemberKind::CopyAssignment); |
14951 | if (DSM.isAlreadyBeingDeclared()) |
14952 | return nullptr; |
14953 | |
14954 | QualType ArgType = Context.getTypeDeclType(ClassDecl); |
14955 | ArgType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr, |
14956 | NamedType: ArgType, OwnedTagDecl: nullptr); |
14957 | LangAS AS = getDefaultCXXMethodAddrSpace(); |
14958 | if (AS != LangAS::Default) |
14959 | ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS); |
14960 | QualType RetType = Context.getLValueReferenceType(T: ArgType); |
14961 | bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); |
14962 | if (Const) |
14963 | ArgType = ArgType.withConst(); |
14964 | |
14965 | ArgType = Context.getLValueReferenceType(T: ArgType); |
14966 | |
14967 | bool Constexpr = defaultedSpecialMemberIsConstexpr( |
14968 | S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, ConstArg: Const); |
14969 | |
14970 | // An implicitly-declared copy assignment operator is an inline public |
14971 | // member of its class. |
14972 | DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal); |
14973 | SourceLocation ClassLoc = ClassDecl->getLocation(); |
14974 | DeclarationNameInfo NameInfo(Name, ClassLoc); |
14975 | CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( |
14976 | C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), |
14977 | /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None, |
14978 | UsesFPIntrin: getCurFPFeatures().isFPConstrained(), |
14979 | /*isInline=*/true, |
14980 | ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, |
14981 | EndLocation: SourceLocation()); |
14982 | CopyAssignment->setAccess(AS_public); |
14983 | CopyAssignment->setDefaulted(); |
14984 | CopyAssignment->setImplicit(); |
14985 | |
14986 | setupImplicitSpecialMemberType(SpecialMem: CopyAssignment, ResultTy: RetType, Args: ArgType); |
14987 | |
14988 | if (getLangOpts().CUDA) |
14989 | CUDA().inferTargetForImplicitSpecialMember( |
14990 | ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, MemberDecl: CopyAssignment, |
14991 | /* ConstRHS */ Const, |
14992 | /* Diagnose */ false); |
14993 | |
14994 | // Add the parameter to the operator. |
14995 | ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, |
14996 | ClassLoc, ClassLoc, |
14997 | /*Id=*/nullptr, ArgType, |
14998 | /*TInfo=*/nullptr, SC_None, |
14999 | nullptr); |
15000 | CopyAssignment->setParams(FromParam); |
15001 | |
15002 | CopyAssignment->setTrivial( |
15003 | ClassDecl->needsOverloadResolutionForCopyAssignment() |
15004 | ? SpecialMemberIsTrivial(MD: CopyAssignment, |
15005 | CSM: CXXSpecialMemberKind::CopyAssignment) |
15006 | : ClassDecl->hasTrivialCopyAssignment()); |
15007 | |
15008 | // Note that we have added this copy-assignment operator. |
15009 | ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; |
15010 | |
15011 | Scope *S = getScopeForContext(ClassDecl); |
15012 | CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); |
15013 | |
15014 | if (ShouldDeleteSpecialMember(MD: CopyAssignment, |
15015 | CSM: CXXSpecialMemberKind::CopyAssignment)) { |
15016 | ClassDecl->setImplicitCopyAssignmentIsDeleted(); |
15017 | SetDeclDeleted(CopyAssignment, ClassLoc); |
15018 | } |
15019 | |
15020 | if (S) |
15021 | PushOnScopeChains(CopyAssignment, S, false); |
15022 | ClassDecl->addDecl(CopyAssignment); |
15023 | |
15024 | return CopyAssignment; |
15025 | } |
15026 | |
15027 | /// Diagnose an implicit copy operation for a class which is odr-used, but |
15028 | /// which is deprecated because the class has a user-declared copy constructor, |
15029 | /// copy assignment operator, or destructor. |
15030 | static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { |
15031 | assert(CopyOp->isImplicit()); |
15032 | |
15033 | CXXRecordDecl *RD = CopyOp->getParent(); |
15034 | CXXMethodDecl *UserDeclaredOperation = nullptr; |
15035 | |
15036 | if (RD->hasUserDeclaredDestructor()) { |
15037 | UserDeclaredOperation = RD->getDestructor(); |
15038 | } else if (!isa<CXXConstructorDecl>(Val: CopyOp) && |
15039 | RD->hasUserDeclaredCopyConstructor()) { |
15040 | // Find any user-declared copy constructor. |
15041 | for (auto *I : RD->ctors()) { |
15042 | if (I->isCopyConstructor()) { |
15043 | UserDeclaredOperation = I; |
15044 | break; |
15045 | } |
15046 | } |
15047 | assert(UserDeclaredOperation); |
15048 | } else if (isa<CXXConstructorDecl>(Val: CopyOp) && |
15049 | RD->hasUserDeclaredCopyAssignment()) { |
15050 | // Find any user-declared move assignment operator. |
15051 | for (auto *I : RD->methods()) { |
15052 | if (I->isCopyAssignmentOperator()) { |
15053 | UserDeclaredOperation = I; |
15054 | break; |
15055 | } |
15056 | } |
15057 | assert(UserDeclaredOperation); |
15058 | } |
15059 | |
15060 | if (UserDeclaredOperation) { |
15061 | bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided(); |
15062 | bool UDOIsDestructor = isa<CXXDestructorDecl>(Val: UserDeclaredOperation); |
15063 | bool IsCopyAssignment = !isa<CXXConstructorDecl>(Val: CopyOp); |
15064 | unsigned DiagID = |
15065 | (UDOIsUserProvided && UDOIsDestructor) |
15066 | ? diag::warn_deprecated_copy_with_user_provided_dtor |
15067 | : (UDOIsUserProvided && !UDOIsDestructor) |
15068 | ? diag::warn_deprecated_copy_with_user_provided_copy |
15069 | : (!UDOIsUserProvided && UDOIsDestructor) |
15070 | ? diag::warn_deprecated_copy_with_dtor |
15071 | : diag::warn_deprecated_copy; |
15072 | S.Diag(UserDeclaredOperation->getLocation(), DiagID) |
15073 | << RD << IsCopyAssignment; |
15074 | } |
15075 | } |
15076 | |
15077 | void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, |
15078 | CXXMethodDecl *CopyAssignOperator) { |
15079 | assert((CopyAssignOperator->isDefaulted() && |
15080 | CopyAssignOperator->isOverloadedOperator() && |
15081 | CopyAssignOperator->getOverloadedOperator() == OO_Equal && |
15082 | !CopyAssignOperator->doesThisDeclarationHaveABody() && |
15083 | !CopyAssignOperator->isDeleted()) && |
15084 | "DefineImplicitCopyAssignment called for wrong function" ); |
15085 | if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) |
15086 | return; |
15087 | |
15088 | CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); |
15089 | if (ClassDecl->isInvalidDecl()) { |
15090 | CopyAssignOperator->setInvalidDecl(); |
15091 | return; |
15092 | } |
15093 | |
15094 | SynthesizedFunctionScope Scope(*this, CopyAssignOperator); |
15095 | |
15096 | // The exception specification is needed because we are defining the |
15097 | // function. |
15098 | ResolveExceptionSpec(Loc: CurrentLocation, |
15099 | FPT: CopyAssignOperator->getType()->castAs<FunctionProtoType>()); |
15100 | |
15101 | // Add a context note for diagnostics produced after this point. |
15102 | Scope.addContextNote(UseLoc: CurrentLocation); |
15103 | |
15104 | // C++11 [class.copy]p18: |
15105 | // The [definition of an implicitly declared copy assignment operator] is |
15106 | // deprecated if the class has a user-declared copy constructor or a |
15107 | // user-declared destructor. |
15108 | if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) |
15109 | diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyAssignOperator); |
15110 | |
15111 | // C++0x [class.copy]p30: |
15112 | // The implicitly-defined or explicitly-defaulted copy assignment operator |
15113 | // for a non-union class X performs memberwise copy assignment of its |
15114 | // subobjects. The direct base classes of X are assigned first, in the |
15115 | // order of their declaration in the base-specifier-list, and then the |
15116 | // immediate non-static data members of X are assigned, in the order in |
15117 | // which they were declared in the class definition. |
15118 | |
15119 | // The statements that form the synthesized function body. |
15120 | SmallVector<Stmt*, 8> Statements; |
15121 | |
15122 | // The parameter for the "other" object, which we are copying from. |
15123 | ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(0); |
15124 | Qualifiers OtherQuals = Other->getType().getQualifiers(); |
15125 | QualType OtherRefType = Other->getType(); |
15126 | if (OtherRefType->isLValueReferenceType()) { |
15127 | OtherRefType = OtherRefType->getPointeeType(); |
15128 | OtherQuals = OtherRefType.getQualifiers(); |
15129 | } |
15130 | |
15131 | // Our location for everything implicitly-generated. |
15132 | SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() |
15133 | ? CopyAssignOperator->getEndLoc() |
15134 | : CopyAssignOperator->getLocation(); |
15135 | |
15136 | // Builds a DeclRefExpr for the "other" object. |
15137 | RefBuilder OtherRef(Other, OtherRefType); |
15138 | |
15139 | // Builds the function object parameter. |
15140 | std::optional<ThisBuilder> This; |
15141 | std::optional<DerefBuilder> DerefThis; |
15142 | std::optional<RefBuilder> ExplicitObject; |
15143 | bool IsArrow = false; |
15144 | QualType ObjectType; |
15145 | if (CopyAssignOperator->isExplicitObjectMemberFunction()) { |
15146 | ObjectType = CopyAssignOperator->getParamDecl(0)->getType(); |
15147 | if (ObjectType->isReferenceType()) |
15148 | ObjectType = ObjectType->getPointeeType(); |
15149 | ExplicitObject.emplace(CopyAssignOperator->getParamDecl(0), ObjectType); |
15150 | } else { |
15151 | ObjectType = getCurrentThisType(); |
15152 | This.emplace(); |
15153 | DerefThis.emplace(args&: *This); |
15154 | IsArrow = !LangOpts.HLSL; |
15155 | } |
15156 | ExprBuilder &ObjectParameter = |
15157 | ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject) |
15158 | : static_cast<ExprBuilder &>(*This); |
15159 | |
15160 | // Assign base classes. |
15161 | bool Invalid = false; |
15162 | for (auto &Base : ClassDecl->bases()) { |
15163 | // Form the assignment: |
15164 | // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); |
15165 | QualType BaseType = Base.getType().getUnqualifiedType(); |
15166 | if (!BaseType->isRecordType()) { |
15167 | Invalid = true; |
15168 | continue; |
15169 | } |
15170 | |
15171 | CXXCastPath BasePath; |
15172 | BasePath.push_back(Elt: &Base); |
15173 | |
15174 | // Construct the "from" expression, which is an implicit cast to the |
15175 | // appropriately-qualified base type. |
15176 | CastBuilder From(OtherRef, Context.getQualifiedType(T: BaseType, Qs: OtherQuals), |
15177 | VK_LValue, BasePath); |
15178 | |
15179 | // Dereference "this". |
15180 | CastBuilder To( |
15181 | ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject) |
15182 | : static_cast<ExprBuilder &>(*DerefThis), |
15183 | Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()), |
15184 | VK_LValue, BasePath); |
15185 | |
15186 | // Build the copy. |
15187 | StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, |
15188 | To, From, |
15189 | /*CopyingBaseSubobject=*/true, |
15190 | /*Copying=*/true); |
15191 | if (Copy.isInvalid()) { |
15192 | CopyAssignOperator->setInvalidDecl(); |
15193 | return; |
15194 | } |
15195 | |
15196 | // Success! Record the copy. |
15197 | Statements.push_back(Copy.getAs<Expr>()); |
15198 | } |
15199 | |
15200 | // Assign non-static members. |
15201 | for (auto *Field : ClassDecl->fields()) { |
15202 | // FIXME: We should form some kind of AST representation for the implied |
15203 | // memcpy in a union copy operation. |
15204 | if (Field->isUnnamedBitField() || Field->getParent()->isUnion()) |
15205 | continue; |
15206 | |
15207 | if (Field->isInvalidDecl()) { |
15208 | Invalid = true; |
15209 | continue; |
15210 | } |
15211 | |
15212 | // Check for members of reference type; we can't copy those. |
15213 | if (Field->getType()->isReferenceType()) { |
15214 | Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) |
15215 | << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); |
15216 | Diag(Field->getLocation(), diag::note_declared_at); |
15217 | Invalid = true; |
15218 | continue; |
15219 | } |
15220 | |
15221 | // Check for members of const-qualified, non-class type. |
15222 | QualType BaseType = Context.getBaseElementType(Field->getType()); |
15223 | if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { |
15224 | Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) |
15225 | << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); |
15226 | Diag(Field->getLocation(), diag::note_declared_at); |
15227 | Invalid = true; |
15228 | continue; |
15229 | } |
15230 | |
15231 | // Suppress assigning zero-width bitfields. |
15232 | if (Field->isZeroLengthBitField(Context)) |
15233 | continue; |
15234 | |
15235 | QualType FieldType = Field->getType().getNonReferenceType(); |
15236 | if (FieldType->isIncompleteArrayType()) { |
15237 | assert(ClassDecl->hasFlexibleArrayMember() && |
15238 | "Incomplete array type is not valid" ); |
15239 | continue; |
15240 | } |
15241 | |
15242 | // Build references to the field in the object we're copying from and to. |
15243 | CXXScopeSpec SS; // Intentionally empty |
15244 | LookupResult MemberLookup(*this, Field->getDeclName(), Loc, |
15245 | LookupMemberName); |
15246 | MemberLookup.addDecl(Field); |
15247 | MemberLookup.resolveKind(); |
15248 | |
15249 | MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); |
15250 | MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup); |
15251 | // Build the copy of this field. |
15252 | StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, |
15253 | To, From, |
15254 | /*CopyingBaseSubobject=*/false, |
15255 | /*Copying=*/true); |
15256 | if (Copy.isInvalid()) { |
15257 | CopyAssignOperator->setInvalidDecl(); |
15258 | return; |
15259 | } |
15260 | |
15261 | // Success! Record the copy. |
15262 | Statements.push_back(Copy.getAs<Stmt>()); |
15263 | } |
15264 | |
15265 | if (!Invalid) { |
15266 | // Add a "return *this;" |
15267 | Expr *ThisExpr = |
15268 | (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject) |
15269 | : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This) |
15270 | : static_cast<ExprBuilder &>(*DerefThis)) |
15271 | .build(*this, Loc); |
15272 | StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr); |
15273 | if (Return.isInvalid()) |
15274 | Invalid = true; |
15275 | else |
15276 | Statements.push_back(Elt: Return.getAs<Stmt>()); |
15277 | } |
15278 | |
15279 | if (Invalid) { |
15280 | CopyAssignOperator->setInvalidDecl(); |
15281 | return; |
15282 | } |
15283 | |
15284 | StmtResult Body; |
15285 | { |
15286 | CompoundScopeRAII CompoundScope(*this); |
15287 | Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements, |
15288 | /*isStmtExpr=*/false); |
15289 | assert(!Body.isInvalid() && "Compound statement creation cannot fail" ); |
15290 | } |
15291 | CopyAssignOperator->setBody(Body.getAs<Stmt>()); |
15292 | CopyAssignOperator->markUsed(Context); |
15293 | |
15294 | if (ASTMutationListener *L = getASTMutationListener()) { |
15295 | L->CompletedImplicitDefinition(CopyAssignOperator); |
15296 | } |
15297 | } |
15298 | |
15299 | CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { |
15300 | assert(ClassDecl->needsImplicitMoveAssignment()); |
15301 | |
15302 | DeclaringSpecialMember DSM(*this, ClassDecl, |
15303 | CXXSpecialMemberKind::MoveAssignment); |
15304 | if (DSM.isAlreadyBeingDeclared()) |
15305 | return nullptr; |
15306 | |
15307 | // Note: The following rules are largely analoguous to the move |
15308 | // constructor rules. |
15309 | |
15310 | QualType ArgType = Context.getTypeDeclType(ClassDecl); |
15311 | ArgType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr, |
15312 | NamedType: ArgType, OwnedTagDecl: nullptr); |
15313 | LangAS AS = getDefaultCXXMethodAddrSpace(); |
15314 | if (AS != LangAS::Default) |
15315 | ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS); |
15316 | QualType RetType = Context.getLValueReferenceType(T: ArgType); |
15317 | ArgType = Context.getRValueReferenceType(T: ArgType); |
15318 | |
15319 | bool Constexpr = defaultedSpecialMemberIsConstexpr( |
15320 | S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, ConstArg: false); |
15321 | |
15322 | // An implicitly-declared move assignment operator is an inline public |
15323 | // member of its class. |
15324 | DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal); |
15325 | SourceLocation ClassLoc = ClassDecl->getLocation(); |
15326 | DeclarationNameInfo NameInfo(Name, ClassLoc); |
15327 | CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( |
15328 | C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), |
15329 | /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None, |
15330 | UsesFPIntrin: getCurFPFeatures().isFPConstrained(), |
15331 | /*isInline=*/true, |
15332 | ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, |
15333 | EndLocation: SourceLocation()); |
15334 | MoveAssignment->setAccess(AS_public); |
15335 | MoveAssignment->setDefaulted(); |
15336 | MoveAssignment->setImplicit(); |
15337 | |
15338 | setupImplicitSpecialMemberType(SpecialMem: MoveAssignment, ResultTy: RetType, Args: ArgType); |
15339 | |
15340 | if (getLangOpts().CUDA) |
15341 | CUDA().inferTargetForImplicitSpecialMember( |
15342 | ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, MemberDecl: MoveAssignment, |
15343 | /* ConstRHS */ false, |
15344 | /* Diagnose */ false); |
15345 | |
15346 | // Add the parameter to the operator. |
15347 | ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, |
15348 | ClassLoc, ClassLoc, |
15349 | /*Id=*/nullptr, ArgType, |
15350 | /*TInfo=*/nullptr, SC_None, |
15351 | nullptr); |
15352 | MoveAssignment->setParams(FromParam); |
15353 | |
15354 | MoveAssignment->setTrivial( |
15355 | ClassDecl->needsOverloadResolutionForMoveAssignment() |
15356 | ? SpecialMemberIsTrivial(MD: MoveAssignment, |
15357 | CSM: CXXSpecialMemberKind::MoveAssignment) |
15358 | : ClassDecl->hasTrivialMoveAssignment()); |
15359 | |
15360 | // Note that we have added this copy-assignment operator. |
15361 | ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; |
15362 | |
15363 | Scope *S = getScopeForContext(ClassDecl); |
15364 | CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); |
15365 | |
15366 | if (ShouldDeleteSpecialMember(MD: MoveAssignment, |
15367 | CSM: CXXSpecialMemberKind::MoveAssignment)) { |
15368 | ClassDecl->setImplicitMoveAssignmentIsDeleted(); |
15369 | SetDeclDeleted(MoveAssignment, ClassLoc); |
15370 | } |
15371 | |
15372 | if (S) |
15373 | PushOnScopeChains(MoveAssignment, S, false); |
15374 | ClassDecl->addDecl(MoveAssignment); |
15375 | |
15376 | return MoveAssignment; |
15377 | } |
15378 | |
15379 | /// Check if we're implicitly defining a move assignment operator for a class |
15380 | /// with virtual bases. Such a move assignment might move-assign the virtual |
15381 | /// base multiple times. |
15382 | static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, |
15383 | SourceLocation CurrentLocation) { |
15384 | assert(!Class->isDependentContext() && "should not define dependent move" ); |
15385 | |
15386 | // Only a virtual base could get implicitly move-assigned multiple times. |
15387 | // Only a non-trivial move assignment can observe this. We only want to |
15388 | // diagnose if we implicitly define an assignment operator that assigns |
15389 | // two base classes, both of which move-assign the same virtual base. |
15390 | if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || |
15391 | Class->getNumBases() < 2) |
15392 | return; |
15393 | |
15394 | llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; |
15395 | typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; |
15396 | VBaseMap VBases; |
15397 | |
15398 | for (auto &BI : Class->bases()) { |
15399 | Worklist.push_back(Elt: &BI); |
15400 | while (!Worklist.empty()) { |
15401 | CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); |
15402 | CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); |
15403 | |
15404 | // If the base has no non-trivial move assignment operators, |
15405 | // we don't care about moves from it. |
15406 | if (!Base->hasNonTrivialMoveAssignment()) |
15407 | continue; |
15408 | |
15409 | // If there's nothing virtual here, skip it. |
15410 | if (!BaseSpec->isVirtual() && !Base->getNumVBases()) |
15411 | continue; |
15412 | |
15413 | // If we're not actually going to call a move assignment for this base, |
15414 | // or the selected move assignment is trivial, skip it. |
15415 | Sema::SpecialMemberOverloadResult SMOR = |
15416 | S.LookupSpecialMember(D: Base, SM: CXXSpecialMemberKind::MoveAssignment, |
15417 | /*ConstArg*/ false, /*VolatileArg*/ false, |
15418 | /*RValueThis*/ true, /*ConstThis*/ false, |
15419 | /*VolatileThis*/ false); |
15420 | if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || |
15421 | !SMOR.getMethod()->isMoveAssignmentOperator()) |
15422 | continue; |
15423 | |
15424 | if (BaseSpec->isVirtual()) { |
15425 | // We're going to move-assign this virtual base, and its move |
15426 | // assignment operator is not trivial. If this can happen for |
15427 | // multiple distinct direct bases of Class, diagnose it. (If it |
15428 | // only happens in one base, we'll diagnose it when synthesizing |
15429 | // that base class's move assignment operator.) |
15430 | CXXBaseSpecifier *&Existing = |
15431 | VBases.insert(KV: std::make_pair(x: Base->getCanonicalDecl(), y: &BI)) |
15432 | .first->second; |
15433 | if (Existing && Existing != &BI) { |
15434 | S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) |
15435 | << Class << Base; |
15436 | S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) |
15437 | << (Base->getCanonicalDecl() == |
15438 | Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) |
15439 | << Base << Existing->getType() << Existing->getSourceRange(); |
15440 | S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) |
15441 | << (Base->getCanonicalDecl() == |
15442 | BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) |
15443 | << Base << BI.getType() << BaseSpec->getSourceRange(); |
15444 | |
15445 | // Only diagnose each vbase once. |
15446 | Existing = nullptr; |
15447 | } |
15448 | } else { |
15449 | // Only walk over bases that have defaulted move assignment operators. |
15450 | // We assume that any user-provided move assignment operator handles |
15451 | // the multiple-moves-of-vbase case itself somehow. |
15452 | if (!SMOR.getMethod()->isDefaulted()) |
15453 | continue; |
15454 | |
15455 | // We're going to move the base classes of Base. Add them to the list. |
15456 | llvm::append_range(C&: Worklist, R: llvm::make_pointer_range(Range: Base->bases())); |
15457 | } |
15458 | } |
15459 | } |
15460 | } |
15461 | |
15462 | void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, |
15463 | CXXMethodDecl *MoveAssignOperator) { |
15464 | assert((MoveAssignOperator->isDefaulted() && |
15465 | MoveAssignOperator->isOverloadedOperator() && |
15466 | MoveAssignOperator->getOverloadedOperator() == OO_Equal && |
15467 | !MoveAssignOperator->doesThisDeclarationHaveABody() && |
15468 | !MoveAssignOperator->isDeleted()) && |
15469 | "DefineImplicitMoveAssignment called for wrong function" ); |
15470 | if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) |
15471 | return; |
15472 | |
15473 | CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); |
15474 | if (ClassDecl->isInvalidDecl()) { |
15475 | MoveAssignOperator->setInvalidDecl(); |
15476 | return; |
15477 | } |
15478 | |
15479 | // C++0x [class.copy]p28: |
15480 | // The implicitly-defined or move assignment operator for a non-union class |
15481 | // X performs memberwise move assignment of its subobjects. The direct base |
15482 | // classes of X are assigned first, in the order of their declaration in the |
15483 | // base-specifier-list, and then the immediate non-static data members of X |
15484 | // are assigned, in the order in which they were declared in the class |
15485 | // definition. |
15486 | |
15487 | // Issue a warning if our implicit move assignment operator will move |
15488 | // from a virtual base more than once. |
15489 | checkMoveAssignmentForRepeatedMove(S&: *this, Class: ClassDecl, CurrentLocation); |
15490 | |
15491 | SynthesizedFunctionScope Scope(*this, MoveAssignOperator); |
15492 | |
15493 | // The exception specification is needed because we are defining the |
15494 | // function. |
15495 | ResolveExceptionSpec(Loc: CurrentLocation, |
15496 | FPT: MoveAssignOperator->getType()->castAs<FunctionProtoType>()); |
15497 | |
15498 | // Add a context note for diagnostics produced after this point. |
15499 | Scope.addContextNote(UseLoc: CurrentLocation); |
15500 | |
15501 | // The statements that form the synthesized function body. |
15502 | SmallVector<Stmt*, 8> Statements; |
15503 | |
15504 | // The parameter for the "other" object, which we are move from. |
15505 | ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(0); |
15506 | QualType OtherRefType = |
15507 | Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); |
15508 | |
15509 | // Our location for everything implicitly-generated. |
15510 | SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() |
15511 | ? MoveAssignOperator->getEndLoc() |
15512 | : MoveAssignOperator->getLocation(); |
15513 | |
15514 | // Builds a reference to the "other" object. |
15515 | RefBuilder OtherRef(Other, OtherRefType); |
15516 | // Cast to rvalue. |
15517 | MoveCastBuilder MoveOther(OtherRef); |
15518 | |
15519 | // Builds the function object parameter. |
15520 | std::optional<ThisBuilder> This; |
15521 | std::optional<DerefBuilder> DerefThis; |
15522 | std::optional<RefBuilder> ExplicitObject; |
15523 | QualType ObjectType; |
15524 | if (MoveAssignOperator->isExplicitObjectMemberFunction()) { |
15525 | ObjectType = MoveAssignOperator->getParamDecl(0)->getType(); |
15526 | if (ObjectType->isReferenceType()) |
15527 | ObjectType = ObjectType->getPointeeType(); |
15528 | ExplicitObject.emplace(MoveAssignOperator->getParamDecl(0), ObjectType); |
15529 | } else { |
15530 | ObjectType = getCurrentThisType(); |
15531 | This.emplace(); |
15532 | DerefThis.emplace(args&: *This); |
15533 | } |
15534 | ExprBuilder &ObjectParameter = |
15535 | ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This); |
15536 | |
15537 | // Assign base classes. |
15538 | bool Invalid = false; |
15539 | for (auto &Base : ClassDecl->bases()) { |
15540 | // C++11 [class.copy]p28: |
15541 | // It is unspecified whether subobjects representing virtual base classes |
15542 | // are assigned more than once by the implicitly-defined copy assignment |
15543 | // operator. |
15544 | // FIXME: Do not assign to a vbase that will be assigned by some other base |
15545 | // class. For a move-assignment, this can result in the vbase being moved |
15546 | // multiple times. |
15547 | |
15548 | // Form the assignment: |
15549 | // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); |
15550 | QualType BaseType = Base.getType().getUnqualifiedType(); |
15551 | if (!BaseType->isRecordType()) { |
15552 | Invalid = true; |
15553 | continue; |
15554 | } |
15555 | |
15556 | CXXCastPath BasePath; |
15557 | BasePath.push_back(Elt: &Base); |
15558 | |
15559 | // Construct the "from" expression, which is an implicit cast to the |
15560 | // appropriately-qualified base type. |
15561 | CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); |
15562 | |
15563 | // Implicitly cast "this" to the appropriately-qualified base type. |
15564 | // Dereference "this". |
15565 | CastBuilder To( |
15566 | ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject) |
15567 | : static_cast<ExprBuilder &>(*DerefThis), |
15568 | Context.getQualifiedType(BaseType, ObjectType.getQualifiers()), |
15569 | VK_LValue, BasePath); |
15570 | |
15571 | // Build the move. |
15572 | StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, |
15573 | To, From, |
15574 | /*CopyingBaseSubobject=*/true, |
15575 | /*Copying=*/false); |
15576 | if (Move.isInvalid()) { |
15577 | MoveAssignOperator->setInvalidDecl(); |
15578 | return; |
15579 | } |
15580 | |
15581 | // Success! Record the move. |
15582 | Statements.push_back(Move.getAs<Expr>()); |
15583 | } |
15584 | |
15585 | // Assign non-static members. |
15586 | for (auto *Field : ClassDecl->fields()) { |
15587 | // FIXME: We should form some kind of AST representation for the implied |
15588 | // memcpy in a union copy operation. |
15589 | if (Field->isUnnamedBitField() || Field->getParent()->isUnion()) |
15590 | continue; |
15591 | |
15592 | if (Field->isInvalidDecl()) { |
15593 | Invalid = true; |
15594 | continue; |
15595 | } |
15596 | |
15597 | // Check for members of reference type; we can't move those. |
15598 | if (Field->getType()->isReferenceType()) { |
15599 | Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) |
15600 | << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); |
15601 | Diag(Field->getLocation(), diag::note_declared_at); |
15602 | Invalid = true; |
15603 | continue; |
15604 | } |
15605 | |
15606 | // Check for members of const-qualified, non-class type. |
15607 | QualType BaseType = Context.getBaseElementType(Field->getType()); |
15608 | if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { |
15609 | Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) |
15610 | << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); |
15611 | Diag(Field->getLocation(), diag::note_declared_at); |
15612 | Invalid = true; |
15613 | continue; |
15614 | } |
15615 | |
15616 | // Suppress assigning zero-width bitfields. |
15617 | if (Field->isZeroLengthBitField(Context)) |
15618 | continue; |
15619 | |
15620 | QualType FieldType = Field->getType().getNonReferenceType(); |
15621 | if (FieldType->isIncompleteArrayType()) { |
15622 | assert(ClassDecl->hasFlexibleArrayMember() && |
15623 | "Incomplete array type is not valid" ); |
15624 | continue; |
15625 | } |
15626 | |
15627 | // Build references to the field in the object we're copying from and to. |
15628 | LookupResult MemberLookup(*this, Field->getDeclName(), Loc, |
15629 | LookupMemberName); |
15630 | MemberLookup.addDecl(Field); |
15631 | MemberLookup.resolveKind(); |
15632 | MemberBuilder From(MoveOther, OtherRefType, |
15633 | /*IsArrow=*/false, MemberLookup); |
15634 | MemberBuilder To(ObjectParameter, ObjectType, /*IsArrow=*/!ExplicitObject, |
15635 | MemberLookup); |
15636 | |
15637 | assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue |
15638 | "Member reference with rvalue base must be rvalue except for reference " |
15639 | "members, which aren't allowed for move assignment." ); |
15640 | |
15641 | // Build the move of this field. |
15642 | StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, |
15643 | To, From, |
15644 | /*CopyingBaseSubobject=*/false, |
15645 | /*Copying=*/false); |
15646 | if (Move.isInvalid()) { |
15647 | MoveAssignOperator->setInvalidDecl(); |
15648 | return; |
15649 | } |
15650 | |
15651 | // Success! Record the copy. |
15652 | Statements.push_back(Move.getAs<Stmt>()); |
15653 | } |
15654 | |
15655 | if (!Invalid) { |
15656 | // Add a "return *this;" |
15657 | Expr *ThisExpr = |
15658 | (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject) |
15659 | : static_cast<ExprBuilder &>(*DerefThis)) |
15660 | .build(S&: *this, Loc); |
15661 | |
15662 | StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr); |
15663 | if (Return.isInvalid()) |
15664 | Invalid = true; |
15665 | else |
15666 | Statements.push_back(Elt: Return.getAs<Stmt>()); |
15667 | } |
15668 | |
15669 | if (Invalid) { |
15670 | MoveAssignOperator->setInvalidDecl(); |
15671 | return; |
15672 | } |
15673 | |
15674 | StmtResult Body; |
15675 | { |
15676 | CompoundScopeRAII CompoundScope(*this); |
15677 | Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements, |
15678 | /*isStmtExpr=*/false); |
15679 | assert(!Body.isInvalid() && "Compound statement creation cannot fail" ); |
15680 | } |
15681 | MoveAssignOperator->setBody(Body.getAs<Stmt>()); |
15682 | MoveAssignOperator->markUsed(Context); |
15683 | |
15684 | if (ASTMutationListener *L = getASTMutationListener()) { |
15685 | L->CompletedImplicitDefinition(MoveAssignOperator); |
15686 | } |
15687 | } |
15688 | |
15689 | CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( |
15690 | CXXRecordDecl *ClassDecl) { |
15691 | // C++ [class.copy]p4: |
15692 | // If the class definition does not explicitly declare a copy |
15693 | // constructor, one is declared implicitly. |
15694 | assert(ClassDecl->needsImplicitCopyConstructor()); |
15695 | |
15696 | DeclaringSpecialMember DSM(*this, ClassDecl, |
15697 | CXXSpecialMemberKind::CopyConstructor); |
15698 | if (DSM.isAlreadyBeingDeclared()) |
15699 | return nullptr; |
15700 | |
15701 | QualType ClassType = Context.getTypeDeclType(ClassDecl); |
15702 | QualType ArgType = ClassType; |
15703 | ArgType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr, |
15704 | NamedType: ArgType, OwnedTagDecl: nullptr); |
15705 | bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); |
15706 | if (Const) |
15707 | ArgType = ArgType.withConst(); |
15708 | |
15709 | LangAS AS = getDefaultCXXMethodAddrSpace(); |
15710 | if (AS != LangAS::Default) |
15711 | ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS); |
15712 | |
15713 | ArgType = Context.getLValueReferenceType(T: ArgType); |
15714 | |
15715 | bool Constexpr = defaultedSpecialMemberIsConstexpr( |
15716 | S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, ConstArg: Const); |
15717 | |
15718 | DeclarationName Name |
15719 | = Context.DeclarationNames.getCXXConstructorName( |
15720 | Ty: Context.getCanonicalType(T: ClassType)); |
15721 | SourceLocation ClassLoc = ClassDecl->getLocation(); |
15722 | DeclarationNameInfo NameInfo(Name, ClassLoc); |
15723 | |
15724 | // An implicitly-declared copy constructor is an inline public |
15725 | // member of its class. |
15726 | CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( |
15727 | C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr, |
15728 | ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(), |
15729 | /*isInline=*/true, |
15730 | /*isImplicitlyDeclared=*/true, |
15731 | ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr |
15732 | : ConstexprSpecKind::Unspecified); |
15733 | CopyConstructor->setAccess(AS_public); |
15734 | CopyConstructor->setDefaulted(); |
15735 | |
15736 | setupImplicitSpecialMemberType(SpecialMem: CopyConstructor, ResultTy: Context.VoidTy, Args: ArgType); |
15737 | |
15738 | if (getLangOpts().CUDA) |
15739 | CUDA().inferTargetForImplicitSpecialMember( |
15740 | ClassDecl, CXXSpecialMemberKind::CopyConstructor, CopyConstructor, |
15741 | /* ConstRHS */ Const, |
15742 | /* Diagnose */ false); |
15743 | |
15744 | // During template instantiation of special member functions we need a |
15745 | // reliable TypeSourceInfo for the parameter types in order to allow functions |
15746 | // to be substituted. |
15747 | TypeSourceInfo *TSI = nullptr; |
15748 | if (inTemplateInstantiation() && ClassDecl->isLambda()) |
15749 | TSI = Context.getTrivialTypeSourceInfo(T: ArgType); |
15750 | |
15751 | // Add the parameter to the constructor. |
15752 | ParmVarDecl *FromParam = |
15753 | ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc, |
15754 | /*IdentifierInfo=*/nullptr, ArgType, |
15755 | /*TInfo=*/TSI, SC_None, nullptr); |
15756 | CopyConstructor->setParams(FromParam); |
15757 | |
15758 | CopyConstructor->setTrivial( |
15759 | ClassDecl->needsOverloadResolutionForCopyConstructor() |
15760 | ? SpecialMemberIsTrivial(CopyConstructor, |
15761 | CXXSpecialMemberKind::CopyConstructor) |
15762 | : ClassDecl->hasTrivialCopyConstructor()); |
15763 | |
15764 | CopyConstructor->setTrivialForCall( |
15765 | ClassDecl->hasAttr<TrivialABIAttr>() || |
15766 | (ClassDecl->needsOverloadResolutionForCopyConstructor() |
15767 | ? SpecialMemberIsTrivial(CopyConstructor, |
15768 | CXXSpecialMemberKind::CopyConstructor, |
15769 | TAH_ConsiderTrivialABI) |
15770 | : ClassDecl->hasTrivialCopyConstructorForCall())); |
15771 | |
15772 | // Note that we have declared this constructor. |
15773 | ++getASTContext().NumImplicitCopyConstructorsDeclared; |
15774 | |
15775 | Scope *S = getScopeForContext(ClassDecl); |
15776 | CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); |
15777 | |
15778 | if (ShouldDeleteSpecialMember(CopyConstructor, |
15779 | CXXSpecialMemberKind::CopyConstructor)) { |
15780 | ClassDecl->setImplicitCopyConstructorIsDeleted(); |
15781 | SetDeclDeleted(CopyConstructor, ClassLoc); |
15782 | } |
15783 | |
15784 | if (S) |
15785 | PushOnScopeChains(CopyConstructor, S, false); |
15786 | ClassDecl->addDecl(CopyConstructor); |
15787 | |
15788 | return CopyConstructor; |
15789 | } |
15790 | |
15791 | void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, |
15792 | CXXConstructorDecl *CopyConstructor) { |
15793 | assert((CopyConstructor->isDefaulted() && |
15794 | CopyConstructor->isCopyConstructor() && |
15795 | !CopyConstructor->doesThisDeclarationHaveABody() && |
15796 | !CopyConstructor->isDeleted()) && |
15797 | "DefineImplicitCopyConstructor - call it for implicit copy ctor" ); |
15798 | if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) |
15799 | return; |
15800 | |
15801 | CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); |
15802 | assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor" ); |
15803 | |
15804 | SynthesizedFunctionScope Scope(*this, CopyConstructor); |
15805 | |
15806 | // The exception specification is needed because we are defining the |
15807 | // function. |
15808 | ResolveExceptionSpec(Loc: CurrentLocation, |
15809 | FPT: CopyConstructor->getType()->castAs<FunctionProtoType>()); |
15810 | MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl); |
15811 | |
15812 | // Add a context note for diagnostics produced after this point. |
15813 | Scope.addContextNote(UseLoc: CurrentLocation); |
15814 | |
15815 | // C++11 [class.copy]p7: |
15816 | // The [definition of an implicitly declared copy constructor] is |
15817 | // deprecated if the class has a user-declared copy assignment operator |
15818 | // or a user-declared destructor. |
15819 | if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) |
15820 | diagnoseDeprecatedCopyOperation(*this, CopyConstructor); |
15821 | |
15822 | if (SetCtorInitializers(Constructor: CopyConstructor, /*AnyErrors=*/false)) { |
15823 | CopyConstructor->setInvalidDecl(); |
15824 | } else { |
15825 | SourceLocation Loc = CopyConstructor->getEndLoc().isValid() |
15826 | ? CopyConstructor->getEndLoc() |
15827 | : CopyConstructor->getLocation(); |
15828 | Sema::CompoundScopeRAII CompoundScope(*this); |
15829 | CopyConstructor->setBody( |
15830 | ActOnCompoundStmt(L: Loc, R: Loc, Elts: std::nullopt, /*isStmtExpr=*/false) |
15831 | .getAs<Stmt>()); |
15832 | CopyConstructor->markUsed(Context); |
15833 | } |
15834 | |
15835 | if (ASTMutationListener *L = getASTMutationListener()) { |
15836 | L->CompletedImplicitDefinition(CopyConstructor); |
15837 | } |
15838 | } |
15839 | |
15840 | CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( |
15841 | CXXRecordDecl *ClassDecl) { |
15842 | assert(ClassDecl->needsImplicitMoveConstructor()); |
15843 | |
15844 | DeclaringSpecialMember DSM(*this, ClassDecl, |
15845 | CXXSpecialMemberKind::MoveConstructor); |
15846 | if (DSM.isAlreadyBeingDeclared()) |
15847 | return nullptr; |
15848 | |
15849 | QualType ClassType = Context.getTypeDeclType(ClassDecl); |
15850 | |
15851 | QualType ArgType = ClassType; |
15852 | ArgType = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::None, NNS: nullptr, |
15853 | NamedType: ArgType, OwnedTagDecl: nullptr); |
15854 | LangAS AS = getDefaultCXXMethodAddrSpace(); |
15855 | if (AS != LangAS::Default) |
15856 | ArgType = Context.getAddrSpaceQualType(T: ClassType, AddressSpace: AS); |
15857 | ArgType = Context.getRValueReferenceType(T: ArgType); |
15858 | |
15859 | bool Constexpr = defaultedSpecialMemberIsConstexpr( |
15860 | S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, ConstArg: false); |
15861 | |
15862 | DeclarationName Name |
15863 | = Context.DeclarationNames.getCXXConstructorName( |
15864 | Ty: Context.getCanonicalType(T: ClassType)); |
15865 | SourceLocation ClassLoc = ClassDecl->getLocation(); |
15866 | DeclarationNameInfo NameInfo(Name, ClassLoc); |
15867 | |
15868 | // C++11 [class.copy]p11: |
15869 | // An implicitly-declared copy/move constructor is an inline public |
15870 | // member of its class. |
15871 | CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( |
15872 | C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr, |
15873 | ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(), |
15874 | /*isInline=*/true, |
15875 | /*isImplicitlyDeclared=*/true, |
15876 | ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr |
15877 | : ConstexprSpecKind::Unspecified); |
15878 | MoveConstructor->setAccess(AS_public); |
15879 | MoveConstructor->setDefaulted(); |
15880 | |
15881 | setupImplicitSpecialMemberType(SpecialMem: MoveConstructor, ResultTy: Context.VoidTy, Args: ArgType); |
15882 | |
15883 | if (getLangOpts().CUDA) |
15884 | CUDA().inferTargetForImplicitSpecialMember( |
15885 | ClassDecl, CXXSpecialMemberKind::MoveConstructor, MoveConstructor, |
15886 | /* ConstRHS */ false, |
15887 | /* Diagnose */ false); |
15888 | |
15889 | // Add the parameter to the constructor. |
15890 | ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, |
15891 | ClassLoc, ClassLoc, |
15892 | /*IdentifierInfo=*/nullptr, |
15893 | ArgType, /*TInfo=*/nullptr, |
15894 | SC_None, nullptr); |
15895 | MoveConstructor->setParams(FromParam); |
15896 | |
15897 | MoveConstructor->setTrivial( |
15898 | ClassDecl->needsOverloadResolutionForMoveConstructor() |
15899 | ? SpecialMemberIsTrivial(MoveConstructor, |
15900 | CXXSpecialMemberKind::MoveConstructor) |
15901 | : ClassDecl->hasTrivialMoveConstructor()); |
15902 | |
15903 | MoveConstructor->setTrivialForCall( |
15904 | ClassDecl->hasAttr<TrivialABIAttr>() || |
15905 | (ClassDecl->needsOverloadResolutionForMoveConstructor() |
15906 | ? SpecialMemberIsTrivial(MoveConstructor, |
15907 | CXXSpecialMemberKind::MoveConstructor, |
15908 | TAH_ConsiderTrivialABI) |
15909 | : ClassDecl->hasTrivialMoveConstructorForCall())); |
15910 | |
15911 | // Note that we have declared this constructor. |
15912 | ++getASTContext().NumImplicitMoveConstructorsDeclared; |
15913 | |
15914 | Scope *S = getScopeForContext(ClassDecl); |
15915 | CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); |
15916 | |
15917 | if (ShouldDeleteSpecialMember(MoveConstructor, |
15918 | CXXSpecialMemberKind::MoveConstructor)) { |
15919 | ClassDecl->setImplicitMoveConstructorIsDeleted(); |
15920 | SetDeclDeleted(MoveConstructor, ClassLoc); |
15921 | } |
15922 | |
15923 | if (S) |
15924 | PushOnScopeChains(MoveConstructor, S, false); |
15925 | ClassDecl->addDecl(MoveConstructor); |
15926 | |
15927 | return MoveConstructor; |
15928 | } |
15929 | |
15930 | void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, |
15931 | CXXConstructorDecl *MoveConstructor) { |
15932 | assert((MoveConstructor->isDefaulted() && |
15933 | MoveConstructor->isMoveConstructor() && |
15934 | !MoveConstructor->doesThisDeclarationHaveABody() && |
15935 | !MoveConstructor->isDeleted()) && |
15936 | "DefineImplicitMoveConstructor - call it for implicit move ctor" ); |
15937 | if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) |
15938 | return; |
15939 | |
15940 | CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); |
15941 | assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor" ); |
15942 | |
15943 | SynthesizedFunctionScope Scope(*this, MoveConstructor); |
15944 | |
15945 | // The exception specification is needed because we are defining the |
15946 | // function. |
15947 | ResolveExceptionSpec(Loc: CurrentLocation, |
15948 | FPT: MoveConstructor->getType()->castAs<FunctionProtoType>()); |
15949 | MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl); |
15950 | |
15951 | // Add a context note for diagnostics produced after this point. |
15952 | Scope.addContextNote(UseLoc: CurrentLocation); |
15953 | |
15954 | if (SetCtorInitializers(Constructor: MoveConstructor, /*AnyErrors=*/false)) { |
15955 | MoveConstructor->setInvalidDecl(); |
15956 | } else { |
15957 | SourceLocation Loc = MoveConstructor->getEndLoc().isValid() |
15958 | ? MoveConstructor->getEndLoc() |
15959 | : MoveConstructor->getLocation(); |
15960 | Sema::CompoundScopeRAII CompoundScope(*this); |
15961 | MoveConstructor->setBody( |
15962 | ActOnCompoundStmt(L: Loc, R: Loc, Elts: std::nullopt, /*isStmtExpr=*/false) |
15963 | .getAs<Stmt>()); |
15964 | MoveConstructor->markUsed(Context); |
15965 | } |
15966 | |
15967 | if (ASTMutationListener *L = getASTMutationListener()) { |
15968 | L->CompletedImplicitDefinition(MoveConstructor); |
15969 | } |
15970 | } |
15971 | |
15972 | bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { |
15973 | return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(Val: FD); |
15974 | } |
15975 | |
15976 | void Sema::DefineImplicitLambdaToFunctionPointerConversion( |
15977 | SourceLocation CurrentLocation, |
15978 | CXXConversionDecl *Conv) { |
15979 | SynthesizedFunctionScope Scope(*this, Conv); |
15980 | assert(!Conv->getReturnType()->isUndeducedType()); |
15981 | |
15982 | QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType(); |
15983 | CallingConv CC = |
15984 | ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv(); |
15985 | |
15986 | CXXRecordDecl *Lambda = Conv->getParent(); |
15987 | FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); |
15988 | FunctionDecl *Invoker = |
15989 | CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic() |
15990 | ? CallOp |
15991 | : Lambda->getLambdaStaticInvoker(CC); |
15992 | |
15993 | if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { |
15994 | CallOp = InstantiateFunctionDeclaration( |
15995 | FTD: CallOp->getDescribedFunctionTemplate(), Args: TemplateArgs, Loc: CurrentLocation); |
15996 | if (!CallOp) |
15997 | return; |
15998 | |
15999 | if (CallOp != Invoker) { |
16000 | Invoker = InstantiateFunctionDeclaration( |
16001 | FTD: Invoker->getDescribedFunctionTemplate(), Args: TemplateArgs, |
16002 | Loc: CurrentLocation); |
16003 | if (!Invoker) |
16004 | return; |
16005 | } |
16006 | } |
16007 | |
16008 | if (CallOp->isInvalidDecl()) |
16009 | return; |
16010 | |
16011 | // Mark the call operator referenced (and add to pending instantiations |
16012 | // if necessary). |
16013 | // For both the conversion and static-invoker template specializations |
16014 | // we construct their body's in this function, so no need to add them |
16015 | // to the PendingInstantiations. |
16016 | MarkFunctionReferenced(Loc: CurrentLocation, Func: CallOp); |
16017 | |
16018 | if (Invoker != CallOp) { |
16019 | // Fill in the __invoke function with a dummy implementation. IR generation |
16020 | // will fill in the actual details. Update its type in case it contained |
16021 | // an 'auto'. |
16022 | Invoker->markUsed(Context); |
16023 | Invoker->setReferenced(); |
16024 | Invoker->setType(Conv->getReturnType()->getPointeeType()); |
16025 | Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); |
16026 | } |
16027 | |
16028 | // Construct the body of the conversion function { return __invoke; }. |
16029 | Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), VK_LValue, |
16030 | Conv->getLocation()); |
16031 | assert(FunctionRef && "Can't refer to __invoke function?" ); |
16032 | Stmt *Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: FunctionRef).get(); |
16033 | Conv->setBody(CompoundStmt::Create(C: Context, Stmts: Return, FPFeatures: FPOptionsOverride(), |
16034 | LB: Conv->getLocation(), RB: Conv->getLocation())); |
16035 | Conv->markUsed(Context); |
16036 | Conv->setReferenced(); |
16037 | |
16038 | if (ASTMutationListener *L = getASTMutationListener()) { |
16039 | L->CompletedImplicitDefinition(Conv); |
16040 | if (Invoker != CallOp) |
16041 | L->CompletedImplicitDefinition(D: Invoker); |
16042 | } |
16043 | } |
16044 | |
16045 | void Sema::DefineImplicitLambdaToBlockPointerConversion( |
16046 | SourceLocation CurrentLocation, CXXConversionDecl *Conv) { |
16047 | assert(!Conv->getParent()->isGenericLambda()); |
16048 | |
16049 | SynthesizedFunctionScope Scope(*this, Conv); |
16050 | |
16051 | // Copy-initialize the lambda object as needed to capture it. |
16052 | Expr *This = ActOnCXXThis(Loc: CurrentLocation).get(); |
16053 | Expr *DerefThis =CreateBuiltinUnaryOp(OpLoc: CurrentLocation, Opc: UO_Deref, InputExpr: This).get(); |
16054 | |
16055 | ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, |
16056 | ConvLocation: Conv->getLocation(), |
16057 | Conv, Src: DerefThis); |
16058 | |
16059 | // If we're not under ARC, make sure we still get the _Block_copy/autorelease |
16060 | // behavior. Note that only the general conversion function does this |
16061 | // (since it's unusable otherwise); in the case where we inline the |
16062 | // block literal, it has block literal lifetime semantics. |
16063 | if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) |
16064 | BuildBlock = ImplicitCastExpr::Create( |
16065 | Context, T: BuildBlock.get()->getType(), Kind: CK_CopyAndAutoreleaseBlockObject, |
16066 | Operand: BuildBlock.get(), BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()); |
16067 | |
16068 | if (BuildBlock.isInvalid()) { |
16069 | Diag(CurrentLocation, diag::note_lambda_to_block_conv); |
16070 | Conv->setInvalidDecl(); |
16071 | return; |
16072 | } |
16073 | |
16074 | // Create the return statement that returns the block from the conversion |
16075 | // function. |
16076 | StmtResult Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: BuildBlock.get()); |
16077 | if (Return.isInvalid()) { |
16078 | Diag(CurrentLocation, diag::note_lambda_to_block_conv); |
16079 | Conv->setInvalidDecl(); |
16080 | return; |
16081 | } |
16082 | |
16083 | // Set the body of the conversion function. |
16084 | Stmt *ReturnS = Return.get(); |
16085 | Conv->setBody(CompoundStmt::Create(C: Context, Stmts: ReturnS, FPFeatures: FPOptionsOverride(), |
16086 | LB: Conv->getLocation(), RB: Conv->getLocation())); |
16087 | Conv->markUsed(Context); |
16088 | |
16089 | // We're done; notify the mutation listener, if any. |
16090 | if (ASTMutationListener *L = getASTMutationListener()) { |
16091 | L->CompletedImplicitDefinition(Conv); |
16092 | } |
16093 | } |
16094 | |
16095 | /// Determine whether the given list arguments contains exactly one |
16096 | /// "real" (non-default) argument. |
16097 | static bool hasOneRealArgument(MultiExprArg Args) { |
16098 | switch (Args.size()) { |
16099 | case 0: |
16100 | return false; |
16101 | |
16102 | default: |
16103 | if (!Args[1]->isDefaultArgument()) |
16104 | return false; |
16105 | |
16106 | [[fallthrough]]; |
16107 | case 1: |
16108 | return !Args[0]->isDefaultArgument(); |
16109 | } |
16110 | |
16111 | return false; |
16112 | } |
16113 | |
16114 | ExprResult Sema::BuildCXXConstructExpr( |
16115 | SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, |
16116 | CXXConstructorDecl *Constructor, MultiExprArg ExprArgs, |
16117 | bool HadMultipleCandidates, bool IsListInitialization, |
16118 | bool IsStdInitListInitialization, bool RequiresZeroInit, |
16119 | CXXConstructionKind ConstructKind, SourceRange ParenRange) { |
16120 | bool Elidable = false; |
16121 | |
16122 | // C++0x [class.copy]p34: |
16123 | // When certain criteria are met, an implementation is allowed to |
16124 | // omit the copy/move construction of a class object, even if the |
16125 | // copy/move constructor and/or destructor for the object have |
16126 | // side effects. [...] |
16127 | // - when a temporary class object that has not been bound to a |
16128 | // reference (12.2) would be copied/moved to a class object |
16129 | // with the same cv-unqualified type, the copy/move operation |
16130 | // can be omitted by constructing the temporary object |
16131 | // directly into the target of the omitted copy/move |
16132 | if (ConstructKind == CXXConstructionKind::Complete && Constructor && |
16133 | // FIXME: Converting constructors should also be accepted. |
16134 | // But to fix this, the logic that digs down into a CXXConstructExpr |
16135 | // to find the source object needs to handle it. |
16136 | // Right now it assumes the source object is passed directly as the |
16137 | // first argument. |
16138 | Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(Args: ExprArgs)) { |
16139 | Expr *SubExpr = ExprArgs[0]; |
16140 | // FIXME: Per above, this is also incorrect if we want to accept |
16141 | // converting constructors, as isTemporaryObject will |
16142 | // reject temporaries with different type from the |
16143 | // CXXRecord itself. |
16144 | Elidable = SubExpr->isTemporaryObject( |
16145 | Ctx&: Context, TempTy: cast<CXXRecordDecl>(FoundDecl->getDeclContext())); |
16146 | } |
16147 | |
16148 | return BuildCXXConstructExpr(ConstructLoc, DeclInitType, |
16149 | FoundDecl, Constructor, |
16150 | Elidable, Exprs: ExprArgs, HadMultipleCandidates, |
16151 | IsListInitialization, |
16152 | IsStdInitListInitialization, RequiresZeroInit, |
16153 | ConstructKind, ParenRange); |
16154 | } |
16155 | |
16156 | ExprResult Sema::BuildCXXConstructExpr( |
16157 | SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, |
16158 | CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs, |
16159 | bool HadMultipleCandidates, bool IsListInitialization, |
16160 | bool IsStdInitListInitialization, bool RequiresZeroInit, |
16161 | CXXConstructionKind ConstructKind, SourceRange ParenRange) { |
16162 | if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl)) { |
16163 | Constructor = findInheritingConstructor(Loc: ConstructLoc, BaseCtor: Constructor, Shadow); |
16164 | // The only way to get here is if we did overlaod resolution to find the |
16165 | // shadow decl, so we don't need to worry about re-checking the trailing |
16166 | // requires clause. |
16167 | if (DiagnoseUseOfOverloadedDecl(Constructor, ConstructLoc)) |
16168 | return ExprError(); |
16169 | } |
16170 | |
16171 | return BuildCXXConstructExpr( |
16172 | ConstructLoc, DeclInitType, Constructor, Elidable, Exprs: ExprArgs, |
16173 | HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, |
16174 | RequiresZeroInit, ConstructKind, ParenRange); |
16175 | } |
16176 | |
16177 | /// BuildCXXConstructExpr - Creates a complete call to a constructor, |
16178 | /// including handling of its default argument expressions. |
16179 | ExprResult Sema::BuildCXXConstructExpr( |
16180 | SourceLocation ConstructLoc, QualType DeclInitType, |
16181 | CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs, |
16182 | bool HadMultipleCandidates, bool IsListInitialization, |
16183 | bool IsStdInitListInitialization, bool RequiresZeroInit, |
16184 | CXXConstructionKind ConstructKind, SourceRange ParenRange) { |
16185 | assert(declaresSameEntity( |
16186 | Constructor->getParent(), |
16187 | DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && |
16188 | "given constructor for wrong type" ); |
16189 | MarkFunctionReferenced(ConstructLoc, Constructor); |
16190 | if (getLangOpts().CUDA && !CUDA().CheckCall(ConstructLoc, Constructor)) |
16191 | return ExprError(); |
16192 | |
16193 | return CheckForImmediateInvocation( |
16194 | CXXConstructExpr::Create( |
16195 | Ctx: Context, Ty: DeclInitType, Loc: ConstructLoc, Ctor: Constructor, Elidable, Args: ExprArgs, |
16196 | HadMultipleCandidates, ListInitialization: IsListInitialization, |
16197 | StdInitListInitialization: IsStdInitListInitialization, ZeroInitialization: RequiresZeroInit, |
16198 | ConstructKind: static_cast<CXXConstructionKind>(ConstructKind), ParenOrBraceRange: ParenRange), |
16199 | Constructor); |
16200 | } |
16201 | |
16202 | void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { |
16203 | if (VD->isInvalidDecl()) return; |
16204 | // If initializing the variable failed, don't also diagnose problems with |
16205 | // the destructor, they're likely related. |
16206 | if (VD->getInit() && VD->getInit()->containsErrors()) |
16207 | return; |
16208 | |
16209 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: Record->getDecl()); |
16210 | if (ClassDecl->isInvalidDecl()) return; |
16211 | if (ClassDecl->hasIrrelevantDestructor()) return; |
16212 | if (ClassDecl->isDependentContext()) return; |
16213 | |
16214 | if (VD->isNoDestroy(getASTContext())) |
16215 | return; |
16216 | |
16217 | CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl); |
16218 | // The result of `LookupDestructor` might be nullptr if the destructor is |
16219 | // invalid, in which case it is marked as `IneligibleOrNotSelected` and |
16220 | // will not be selected by `CXXRecordDecl::getDestructor()`. |
16221 | if (!Destructor) |
16222 | return; |
16223 | // If this is an array, we'll require the destructor during initialization, so |
16224 | // we can skip over this. We still want to emit exit-time destructor warnings |
16225 | // though. |
16226 | if (!VD->getType()->isArrayType()) { |
16227 | MarkFunctionReferenced(Loc: VD->getLocation(), Func: Destructor); |
16228 | CheckDestructorAccess(VD->getLocation(), Destructor, |
16229 | PDiag(diag::err_access_dtor_var) |
16230 | << VD->getDeclName() << VD->getType()); |
16231 | DiagnoseUseOfDecl(D: Destructor, Locs: VD->getLocation()); |
16232 | } |
16233 | |
16234 | if (Destructor->isTrivial()) return; |
16235 | |
16236 | // If the destructor is constexpr, check whether the variable has constant |
16237 | // destruction now. |
16238 | if (Destructor->isConstexpr()) { |
16239 | bool HasConstantInit = false; |
16240 | if (VD->getInit() && !VD->getInit()->isValueDependent()) |
16241 | HasConstantInit = VD->evaluateValue(); |
16242 | SmallVector<PartialDiagnosticAt, 8> Notes; |
16243 | if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && |
16244 | HasConstantInit) { |
16245 | Diag(VD->getLocation(), |
16246 | diag::err_constexpr_var_requires_const_destruction) << VD; |
16247 | for (unsigned I = 0, N = Notes.size(); I != N; ++I) |
16248 | Diag(Notes[I].first, Notes[I].second); |
16249 | } |
16250 | } |
16251 | |
16252 | if (!VD->hasGlobalStorage() || !VD->needsDestruction(Ctx: Context)) |
16253 | return; |
16254 | |
16255 | // Emit warning for non-trivial dtor in global scope (a real global, |
16256 | // class-static, function-static). |
16257 | if (!VD->hasAttr<AlwaysDestroyAttr>()) |
16258 | Diag(VD->getLocation(), diag::warn_exit_time_destructor); |
16259 | |
16260 | // TODO: this should be re-enabled for static locals by !CXAAtExit |
16261 | if (!VD->isStaticLocal()) |
16262 | Diag(VD->getLocation(), diag::warn_global_destructor); |
16263 | } |
16264 | |
16265 | /// Given a constructor and the set of arguments provided for the |
16266 | /// constructor, convert the arguments and add any required default arguments |
16267 | /// to form a proper call to this constructor. |
16268 | /// |
16269 | /// \returns true if an error occurred, false otherwise. |
16270 | bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, |
16271 | QualType DeclInitType, MultiExprArg ArgsPtr, |
16272 | SourceLocation Loc, |
16273 | SmallVectorImpl<Expr *> &ConvertedArgs, |
16274 | bool AllowExplicit, |
16275 | bool IsListInitialization) { |
16276 | // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. |
16277 | unsigned NumArgs = ArgsPtr.size(); |
16278 | Expr **Args = ArgsPtr.data(); |
16279 | |
16280 | const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); |
16281 | unsigned NumParams = Proto->getNumParams(); |
16282 | |
16283 | // If too few arguments are available, we'll fill in the rest with defaults. |
16284 | if (NumArgs < NumParams) |
16285 | ConvertedArgs.reserve(N: NumParams); |
16286 | else |
16287 | ConvertedArgs.reserve(N: NumArgs); |
16288 | |
16289 | VariadicCallType CallType = |
16290 | Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; |
16291 | SmallVector<Expr *, 8> AllArgs; |
16292 | bool Invalid = GatherArgumentsForCall( |
16293 | CallLoc: Loc, FDecl: Constructor, Proto: Proto, FirstParam: 0, Args: llvm::ArrayRef(Args, NumArgs), AllArgs, |
16294 | CallType, AllowExplicit, IsListInitialization); |
16295 | ConvertedArgs.append(in_start: AllArgs.begin(), in_end: AllArgs.end()); |
16296 | |
16297 | DiagnoseSentinelCalls(Constructor, Loc, AllArgs); |
16298 | |
16299 | CheckConstructorCall(FDecl: Constructor, ThisType: DeclInitType, |
16300 | Args: llvm::ArrayRef(AllArgs.data(), AllArgs.size()), Proto: Proto, |
16301 | Loc); |
16302 | |
16303 | return Invalid; |
16304 | } |
16305 | |
16306 | static inline bool |
16307 | CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, |
16308 | const FunctionDecl *FnDecl) { |
16309 | const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); |
16310 | if (isa<NamespaceDecl>(Val: DC)) { |
16311 | return SemaRef.Diag(FnDecl->getLocation(), |
16312 | diag::err_operator_new_delete_declared_in_namespace) |
16313 | << FnDecl->getDeclName(); |
16314 | } |
16315 | |
16316 | if (isa<TranslationUnitDecl>(Val: DC) && |
16317 | FnDecl->getStorageClass() == SC_Static) { |
16318 | return SemaRef.Diag(FnDecl->getLocation(), |
16319 | diag::err_operator_new_delete_declared_static) |
16320 | << FnDecl->getDeclName(); |
16321 | } |
16322 | |
16323 | return false; |
16324 | } |
16325 | |
16326 | static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, |
16327 | const PointerType *PtrTy) { |
16328 | auto &Ctx = SemaRef.Context; |
16329 | Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers(); |
16330 | PtrQuals.removeAddressSpace(); |
16331 | return Ctx.getPointerType(T: Ctx.getCanonicalType(T: Ctx.getQualifiedType( |
16332 | T: PtrTy->getPointeeType().getUnqualifiedType(), Qs: PtrQuals))); |
16333 | } |
16334 | |
16335 | static inline bool |
16336 | CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, |
16337 | CanQualType ExpectedResultType, |
16338 | CanQualType ExpectedFirstParamType, |
16339 | unsigned DependentParamTypeDiag, |
16340 | unsigned InvalidParamTypeDiag) { |
16341 | QualType ResultType = |
16342 | FnDecl->getType()->castAs<FunctionType>()->getReturnType(); |
16343 | |
16344 | if (SemaRef.getLangOpts().OpenCLCPlusPlus) { |
16345 | // The operator is valid on any address space for OpenCL. |
16346 | // Drop address space from actual and expected result types. |
16347 | if (const auto *PtrTy = ResultType->getAs<PointerType>()) |
16348 | ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); |
16349 | |
16350 | if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>()) |
16351 | ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); |
16352 | } |
16353 | |
16354 | // Check that the result type is what we expect. |
16355 | if (SemaRef.Context.getCanonicalType(T: ResultType) != ExpectedResultType) { |
16356 | // Reject even if the type is dependent; an operator delete function is |
16357 | // required to have a non-dependent result type. |
16358 | return SemaRef.Diag( |
16359 | FnDecl->getLocation(), |
16360 | ResultType->isDependentType() |
16361 | ? diag::err_operator_new_delete_dependent_result_type |
16362 | : diag::err_operator_new_delete_invalid_result_type) |
16363 | << FnDecl->getDeclName() << ExpectedResultType; |
16364 | } |
16365 | |
16366 | // A function template must have at least 2 parameters. |
16367 | if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) |
16368 | return SemaRef.Diag(FnDecl->getLocation(), |
16369 | diag::err_operator_new_delete_template_too_few_parameters) |
16370 | << FnDecl->getDeclName(); |
16371 | |
16372 | // The function decl must have at least 1 parameter. |
16373 | if (FnDecl->getNumParams() == 0) |
16374 | return SemaRef.Diag(FnDecl->getLocation(), |
16375 | diag::err_operator_new_delete_too_few_parameters) |
16376 | << FnDecl->getDeclName(); |
16377 | |
16378 | QualType FirstParamType = FnDecl->getParamDecl(i: 0)->getType(); |
16379 | if (SemaRef.getLangOpts().OpenCLCPlusPlus) { |
16380 | // The operator is valid on any address space for OpenCL. |
16381 | // Drop address space from actual and expected first parameter types. |
16382 | if (const auto *PtrTy = |
16383 | FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) |
16384 | FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); |
16385 | |
16386 | if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>()) |
16387 | ExpectedFirstParamType = |
16388 | RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); |
16389 | } |
16390 | |
16391 | // Check that the first parameter type is what we expect. |
16392 | if (SemaRef.Context.getCanonicalType(T: FirstParamType).getUnqualifiedType() != |
16393 | ExpectedFirstParamType) { |
16394 | // The first parameter type is not allowed to be dependent. As a tentative |
16395 | // DR resolution, we allow a dependent parameter type if it is the right |
16396 | // type anyway, to allow destroying operator delete in class templates. |
16397 | return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() |
16398 | ? DependentParamTypeDiag |
16399 | : InvalidParamTypeDiag) |
16400 | << FnDecl->getDeclName() << ExpectedFirstParamType; |
16401 | } |
16402 | |
16403 | return false; |
16404 | } |
16405 | |
16406 | static bool |
16407 | CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { |
16408 | // C++ [basic.stc.dynamic.allocation]p1: |
16409 | // A program is ill-formed if an allocation function is declared in a |
16410 | // namespace scope other than global scope or declared static in global |
16411 | // scope. |
16412 | if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) |
16413 | return true; |
16414 | |
16415 | CanQualType SizeTy = |
16416 | SemaRef.Context.getCanonicalType(T: SemaRef.Context.getSizeType()); |
16417 | |
16418 | // C++ [basic.stc.dynamic.allocation]p1: |
16419 | // The return type shall be void*. The first parameter shall have type |
16420 | // std::size_t. |
16421 | if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, |
16422 | SizeTy, |
16423 | diag::err_operator_new_dependent_param_type, |
16424 | diag::err_operator_new_param_type)) |
16425 | return true; |
16426 | |
16427 | // C++ [basic.stc.dynamic.allocation]p1: |
16428 | // The first parameter shall not have an associated default argument. |
16429 | if (FnDecl->getParamDecl(0)->hasDefaultArg()) |
16430 | return SemaRef.Diag(FnDecl->getLocation(), |
16431 | diag::err_operator_new_default_arg) |
16432 | << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); |
16433 | |
16434 | return false; |
16435 | } |
16436 | |
16437 | static bool |
16438 | CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { |
16439 | // C++ [basic.stc.dynamic.deallocation]p1: |
16440 | // A program is ill-formed if deallocation functions are declared in a |
16441 | // namespace scope other than global scope or declared static in global |
16442 | // scope. |
16443 | if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) |
16444 | return true; |
16445 | |
16446 | auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl); |
16447 | |
16448 | // C++ P0722: |
16449 | // Within a class C, the first parameter of a destroying operator delete |
16450 | // shall be of type C *. The first parameter of any other deallocation |
16451 | // function shall be of type void *. |
16452 | CanQualType ExpectedFirstParamType = |
16453 | MD && MD->isDestroyingOperatorDelete() |
16454 | ? SemaRef.Context.getCanonicalType(T: SemaRef.Context.getPointerType( |
16455 | T: SemaRef.Context.getRecordType(MD->getParent()))) |
16456 | : SemaRef.Context.VoidPtrTy; |
16457 | |
16458 | // C++ [basic.stc.dynamic.deallocation]p2: |
16459 | // Each deallocation function shall return void |
16460 | if (CheckOperatorNewDeleteTypes( |
16461 | SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, |
16462 | diag::err_operator_delete_dependent_param_type, |
16463 | diag::err_operator_delete_param_type)) |
16464 | return true; |
16465 | |
16466 | // C++ P0722: |
16467 | // A destroying operator delete shall be a usual deallocation function. |
16468 | if (MD && !MD->getParent()->isDependentContext() && |
16469 | MD->isDestroyingOperatorDelete() && |
16470 | !SemaRef.isUsualDeallocationFunction(FD: MD)) { |
16471 | SemaRef.Diag(MD->getLocation(), |
16472 | diag::err_destroying_operator_delete_not_usual); |
16473 | return true; |
16474 | } |
16475 | |
16476 | return false; |
16477 | } |
16478 | |
16479 | /// CheckOverloadedOperatorDeclaration - Check whether the declaration |
16480 | /// of this overloaded operator is well-formed. If so, returns false; |
16481 | /// otherwise, emits appropriate diagnostics and returns true. |
16482 | bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { |
16483 | assert(FnDecl && FnDecl->isOverloadedOperator() && |
16484 | "Expected an overloaded operator declaration" ); |
16485 | |
16486 | OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); |
16487 | |
16488 | // C++ [over.oper]p5: |
16489 | // The allocation and deallocation functions, operator new, |
16490 | // operator new[], operator delete and operator delete[], are |
16491 | // described completely in 3.7.3. The attributes and restrictions |
16492 | // found in the rest of this subclause do not apply to them unless |
16493 | // explicitly stated in 3.7.3. |
16494 | if (Op == OO_Delete || Op == OO_Array_Delete) |
16495 | return CheckOperatorDeleteDeclaration(SemaRef&: *this, FnDecl); |
16496 | |
16497 | if (Op == OO_New || Op == OO_Array_New) |
16498 | return CheckOperatorNewDeclaration(SemaRef&: *this, FnDecl); |
16499 | |
16500 | // C++ [over.oper]p7: |
16501 | // An operator function shall either be a member function or |
16502 | // be a non-member function and have at least one parameter |
16503 | // whose type is a class, a reference to a class, an enumeration, |
16504 | // or a reference to an enumeration. |
16505 | // Note: Before C++23, a member function could not be static. The only member |
16506 | // function allowed to be static is the call operator function. |
16507 | if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: FnDecl)) { |
16508 | if (MethodDecl->isStatic()) { |
16509 | if (Op == OO_Call || Op == OO_Subscript) |
16510 | Diag(FnDecl->getLocation(), |
16511 | (LangOpts.CPlusPlus23 |
16512 | ? diag::warn_cxx20_compat_operator_overload_static |
16513 | : diag::ext_operator_overload_static)) |
16514 | << FnDecl; |
16515 | else |
16516 | return Diag(FnDecl->getLocation(), diag::err_operator_overload_static) |
16517 | << FnDecl; |
16518 | } |
16519 | } else { |
16520 | bool ClassOrEnumParam = false; |
16521 | for (auto *Param : FnDecl->parameters()) { |
16522 | QualType ParamType = Param->getType().getNonReferenceType(); |
16523 | if (ParamType->isDependentType() || ParamType->isRecordType() || |
16524 | ParamType->isEnumeralType()) { |
16525 | ClassOrEnumParam = true; |
16526 | break; |
16527 | } |
16528 | } |
16529 | |
16530 | if (!ClassOrEnumParam) |
16531 | return Diag(FnDecl->getLocation(), |
16532 | diag::err_operator_overload_needs_class_or_enum) |
16533 | << FnDecl->getDeclName(); |
16534 | } |
16535 | |
16536 | // C++ [over.oper]p8: |
16537 | // An operator function cannot have default arguments (8.3.6), |
16538 | // except where explicitly stated below. |
16539 | // |
16540 | // Only the function-call operator (C++ [over.call]p1) and the subscript |
16541 | // operator (CWG2507) allow default arguments. |
16542 | if (Op != OO_Call) { |
16543 | ParmVarDecl *FirstDefaultedParam = nullptr; |
16544 | for (auto *Param : FnDecl->parameters()) { |
16545 | if (Param->hasDefaultArg()) { |
16546 | FirstDefaultedParam = Param; |
16547 | break; |
16548 | } |
16549 | } |
16550 | if (FirstDefaultedParam) { |
16551 | if (Op == OO_Subscript) { |
16552 | Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23 |
16553 | ? diag::ext_subscript_overload |
16554 | : diag::error_subscript_overload) |
16555 | << FnDecl->getDeclName() << 1 |
16556 | << FirstDefaultedParam->getDefaultArgRange(); |
16557 | } else { |
16558 | return Diag(FirstDefaultedParam->getLocation(), |
16559 | diag::err_operator_overload_default_arg) |
16560 | << FnDecl->getDeclName() |
16561 | << FirstDefaultedParam->getDefaultArgRange(); |
16562 | } |
16563 | } |
16564 | } |
16565 | |
16566 | static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { |
16567 | { false, false, false } |
16568 | #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ |
16569 | , { Unary, Binary, MemberOnly } |
16570 | #include "clang/Basic/OperatorKinds.def" |
16571 | }; |
16572 | |
16573 | bool CanBeUnaryOperator = OperatorUses[Op][0]; |
16574 | bool CanBeBinaryOperator = OperatorUses[Op][1]; |
16575 | bool MustBeMemberOperator = OperatorUses[Op][2]; |
16576 | |
16577 | // C++ [over.oper]p8: |
16578 | // [...] Operator functions cannot have more or fewer parameters |
16579 | // than the number required for the corresponding operator, as |
16580 | // described in the rest of this subclause. |
16581 | unsigned NumParams = FnDecl->getNumParams() + |
16582 | (isa<CXXMethodDecl>(Val: FnDecl) && |
16583 | !FnDecl->hasCXXExplicitFunctionObjectParameter() |
16584 | ? 1 |
16585 | : 0); |
16586 | if (Op != OO_Call && Op != OO_Subscript && |
16587 | ((NumParams == 1 && !CanBeUnaryOperator) || |
16588 | (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) || |
16589 | (NumParams > 2))) { |
16590 | // We have the wrong number of parameters. |
16591 | unsigned ErrorKind; |
16592 | if (CanBeUnaryOperator && CanBeBinaryOperator) { |
16593 | ErrorKind = 2; // 2 -> unary or binary. |
16594 | } else if (CanBeUnaryOperator) { |
16595 | ErrorKind = 0; // 0 -> unary |
16596 | } else { |
16597 | assert(CanBeBinaryOperator && |
16598 | "All non-call overloaded operators are unary or binary!" ); |
16599 | ErrorKind = 1; // 1 -> binary |
16600 | } |
16601 | return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) |
16602 | << FnDecl->getDeclName() << NumParams << ErrorKind; |
16603 | } |
16604 | |
16605 | if (Op == OO_Subscript && NumParams != 2) { |
16606 | Diag(FnDecl->getLocation(), LangOpts.CPlusPlus23 |
16607 | ? diag::ext_subscript_overload |
16608 | : diag::error_subscript_overload) |
16609 | << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2); |
16610 | } |
16611 | |
16612 | // Overloaded operators other than operator() and operator[] cannot be |
16613 | // variadic. |
16614 | if (Op != OO_Call && |
16615 | FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { |
16616 | return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) |
16617 | << FnDecl->getDeclName(); |
16618 | } |
16619 | |
16620 | // Some operators must be member functions. |
16621 | if (MustBeMemberOperator && !isa<CXXMethodDecl>(Val: FnDecl)) { |
16622 | return Diag(FnDecl->getLocation(), |
16623 | diag::err_operator_overload_must_be_member) |
16624 | << FnDecl->getDeclName(); |
16625 | } |
16626 | |
16627 | // C++ [over.inc]p1: |
16628 | // The user-defined function called operator++ implements the |
16629 | // prefix and postfix ++ operator. If this function is a member |
16630 | // function with no parameters, or a non-member function with one |
16631 | // parameter of class or enumeration type, it defines the prefix |
16632 | // increment operator ++ for objects of that type. If the function |
16633 | // is a member function with one parameter (which shall be of type |
16634 | // int) or a non-member function with two parameters (the second |
16635 | // of which shall be of type int), it defines the postfix |
16636 | // increment operator ++ for objects of that type. |
16637 | if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { |
16638 | ParmVarDecl *LastParam = FnDecl->getParamDecl(i: FnDecl->getNumParams() - 1); |
16639 | QualType ParamType = LastParam->getType(); |
16640 | |
16641 | if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && |
16642 | !ParamType->isDependentType()) |
16643 | return Diag(LastParam->getLocation(), |
16644 | diag::err_operator_overload_post_incdec_must_be_int) |
16645 | << LastParam->getType() << (Op == OO_MinusMinus); |
16646 | } |
16647 | |
16648 | return false; |
16649 | } |
16650 | |
16651 | static bool |
16652 | checkLiteralOperatorTemplateParameterList(Sema &SemaRef, |
16653 | FunctionTemplateDecl *TpDecl) { |
16654 | TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); |
16655 | |
16656 | // Must have one or two template parameters. |
16657 | if (TemplateParams->size() == 1) { |
16658 | NonTypeTemplateParmDecl *PmDecl = |
16659 | dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 0)); |
16660 | |
16661 | // The template parameter must be a char parameter pack. |
16662 | if (PmDecl && PmDecl->isTemplateParameterPack() && |
16663 | SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) |
16664 | return false; |
16665 | |
16666 | // C++20 [over.literal]p5: |
16667 | // A string literal operator template is a literal operator template |
16668 | // whose template-parameter-list comprises a single non-type |
16669 | // template-parameter of class type. |
16670 | // |
16671 | // As a DR resolution, we also allow placeholders for deduced class |
16672 | // template specializations. |
16673 | if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl && |
16674 | !PmDecl->isTemplateParameterPack() && |
16675 | (PmDecl->getType()->isRecordType() || |
16676 | PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) |
16677 | return false; |
16678 | } else if (TemplateParams->size() == 2) { |
16679 | TemplateTypeParmDecl *PmType = |
16680 | dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->getParam(Idx: 0)); |
16681 | NonTypeTemplateParmDecl *PmArgs = |
16682 | dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 1)); |
16683 | |
16684 | // The second template parameter must be a parameter pack with the |
16685 | // first template parameter as its type. |
16686 | if (PmType && PmArgs && !PmType->isTemplateParameterPack() && |
16687 | PmArgs->isTemplateParameterPack()) { |
16688 | const TemplateTypeParmType *TArgs = |
16689 | PmArgs->getType()->getAs<TemplateTypeParmType>(); |
16690 | if (TArgs && TArgs->getDepth() == PmType->getDepth() && |
16691 | TArgs->getIndex() == PmType->getIndex()) { |
16692 | if (!SemaRef.inTemplateInstantiation()) |
16693 | SemaRef.Diag(TpDecl->getLocation(), |
16694 | diag::ext_string_literal_operator_template); |
16695 | return false; |
16696 | } |
16697 | } |
16698 | } |
16699 | |
16700 | SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), |
16701 | diag::err_literal_operator_template) |
16702 | << TpDecl->getTemplateParameters()->getSourceRange(); |
16703 | return true; |
16704 | } |
16705 | |
16706 | /// CheckLiteralOperatorDeclaration - Check whether the declaration |
16707 | /// of this literal operator function is well-formed. If so, returns |
16708 | /// false; otherwise, emits appropriate diagnostics and returns true. |
16709 | bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { |
16710 | if (isa<CXXMethodDecl>(Val: FnDecl)) { |
16711 | Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) |
16712 | << FnDecl->getDeclName(); |
16713 | return true; |
16714 | } |
16715 | |
16716 | if (FnDecl->isExternC()) { |
16717 | Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); |
16718 | if (const LinkageSpecDecl *LSD = |
16719 | FnDecl->getDeclContext()->getExternCContext()) |
16720 | Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); |
16721 | return true; |
16722 | } |
16723 | |
16724 | // This might be the definition of a literal operator template. |
16725 | FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); |
16726 | |
16727 | // This might be a specialization of a literal operator template. |
16728 | if (!TpDecl) |
16729 | TpDecl = FnDecl->getPrimaryTemplate(); |
16730 | |
16731 | // template <char...> type operator "" name() and |
16732 | // template <class T, T...> type operator "" name() are the only valid |
16733 | // template signatures, and the only valid signatures with no parameters. |
16734 | // |
16735 | // C++20 also allows template <SomeClass T> type operator "" name(). |
16736 | if (TpDecl) { |
16737 | if (FnDecl->param_size() != 0) { |
16738 | Diag(FnDecl->getLocation(), |
16739 | diag::err_literal_operator_template_with_params); |
16740 | return true; |
16741 | } |
16742 | |
16743 | if (checkLiteralOperatorTemplateParameterList(SemaRef&: *this, TpDecl)) |
16744 | return true; |
16745 | |
16746 | } else if (FnDecl->param_size() == 1) { |
16747 | const ParmVarDecl *Param = FnDecl->getParamDecl(i: 0); |
16748 | |
16749 | QualType ParamType = Param->getType().getUnqualifiedType(); |
16750 | |
16751 | // Only unsigned long long int, long double, any character type, and const |
16752 | // char * are allowed as the only parameters. |
16753 | if (ParamType->isSpecificBuiltinType(K: BuiltinType::ULongLong) || |
16754 | ParamType->isSpecificBuiltinType(K: BuiltinType::LongDouble) || |
16755 | Context.hasSameType(ParamType, Context.CharTy) || |
16756 | Context.hasSameType(ParamType, Context.WideCharTy) || |
16757 | Context.hasSameType(ParamType, Context.Char8Ty) || |
16758 | Context.hasSameType(ParamType, Context.Char16Ty) || |
16759 | Context.hasSameType(ParamType, Context.Char32Ty)) { |
16760 | } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { |
16761 | QualType InnerType = Ptr->getPointeeType(); |
16762 | |
16763 | // Pointer parameter must be a const char *. |
16764 | if (!(Context.hasSameType(InnerType.getUnqualifiedType(), |
16765 | Context.CharTy) && |
16766 | InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { |
16767 | Diag(Param->getSourceRange().getBegin(), |
16768 | diag::err_literal_operator_param) |
16769 | << ParamType << "'const char *'" << Param->getSourceRange(); |
16770 | return true; |
16771 | } |
16772 | |
16773 | } else if (ParamType->isRealFloatingType()) { |
16774 | Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) |
16775 | << ParamType << Context.LongDoubleTy << Param->getSourceRange(); |
16776 | return true; |
16777 | |
16778 | } else if (ParamType->isIntegerType()) { |
16779 | Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) |
16780 | << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); |
16781 | return true; |
16782 | |
16783 | } else { |
16784 | Diag(Param->getSourceRange().getBegin(), |
16785 | diag::err_literal_operator_invalid_param) |
16786 | << ParamType << Param->getSourceRange(); |
16787 | return true; |
16788 | } |
16789 | |
16790 | } else if (FnDecl->param_size() == 2) { |
16791 | FunctionDecl::param_iterator Param = FnDecl->param_begin(); |
16792 | |
16793 | // First, verify that the first parameter is correct. |
16794 | |
16795 | QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); |
16796 | |
16797 | // Two parameter function must have a pointer to const as a |
16798 | // first parameter; let's strip those qualifiers. |
16799 | const PointerType *PT = FirstParamType->getAs<PointerType>(); |
16800 | |
16801 | if (!PT) { |
16802 | Diag((*Param)->getSourceRange().getBegin(), |
16803 | diag::err_literal_operator_param) |
16804 | << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); |
16805 | return true; |
16806 | } |
16807 | |
16808 | QualType PointeeType = PT->getPointeeType(); |
16809 | // First parameter must be const |
16810 | if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { |
16811 | Diag((*Param)->getSourceRange().getBegin(), |
16812 | diag::err_literal_operator_param) |
16813 | << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); |
16814 | return true; |
16815 | } |
16816 | |
16817 | QualType InnerType = PointeeType.getUnqualifiedType(); |
16818 | // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and |
16819 | // const char32_t* are allowed as the first parameter to a two-parameter |
16820 | // function |
16821 | if (!(Context.hasSameType(InnerType, Context.CharTy) || |
16822 | Context.hasSameType(InnerType, Context.WideCharTy) || |
16823 | Context.hasSameType(InnerType, Context.Char8Ty) || |
16824 | Context.hasSameType(InnerType, Context.Char16Ty) || |
16825 | Context.hasSameType(InnerType, Context.Char32Ty))) { |
16826 | Diag((*Param)->getSourceRange().getBegin(), |
16827 | diag::err_literal_operator_param) |
16828 | << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); |
16829 | return true; |
16830 | } |
16831 | |
16832 | // Move on to the second and final parameter. |
16833 | ++Param; |
16834 | |
16835 | // The second parameter must be a std::size_t. |
16836 | QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); |
16837 | if (!Context.hasSameType(T1: SecondParamType, T2: Context.getSizeType())) { |
16838 | Diag((*Param)->getSourceRange().getBegin(), |
16839 | diag::err_literal_operator_param) |
16840 | << SecondParamType << Context.getSizeType() |
16841 | << (*Param)->getSourceRange(); |
16842 | return true; |
16843 | } |
16844 | } else { |
16845 | Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); |
16846 | return true; |
16847 | } |
16848 | |
16849 | // Parameters are good. |
16850 | |
16851 | // A parameter-declaration-clause containing a default argument is not |
16852 | // equivalent to any of the permitted forms. |
16853 | for (auto *Param : FnDecl->parameters()) { |
16854 | if (Param->hasDefaultArg()) { |
16855 | Diag(Param->getDefaultArgRange().getBegin(), |
16856 | diag::err_literal_operator_default_argument) |
16857 | << Param->getDefaultArgRange(); |
16858 | break; |
16859 | } |
16860 | } |
16861 | |
16862 | const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier(); |
16863 | ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId(); |
16864 | if (Status != ReservedLiteralSuffixIdStatus::NotReserved && |
16865 | !getSourceManager().isInSystemHeader(Loc: FnDecl->getLocation())) { |
16866 | // C++23 [usrlit.suffix]p1: |
16867 | // Literal suffix identifiers that do not start with an underscore are |
16868 | // reserved for future standardization. Literal suffix identifiers that |
16869 | // contain a double underscore __ are reserved for use by C++ |
16870 | // implementations. |
16871 | Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) |
16872 | << static_cast<int>(Status) |
16873 | << StringLiteralParser::isValidUDSuffix(getLangOpts(), II->getName()); |
16874 | } |
16875 | |
16876 | return false; |
16877 | } |
16878 | |
16879 | /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ |
16880 | /// linkage specification, including the language and (if present) |
16881 | /// the '{'. ExternLoc is the location of the 'extern', Lang is the |
16882 | /// language string literal. LBraceLoc, if valid, provides the location of |
16883 | /// the '{' brace. Otherwise, this linkage specification does not |
16884 | /// have any braces. |
16885 | Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, |
16886 | Expr *LangStr, |
16887 | SourceLocation LBraceLoc) { |
16888 | StringLiteral *Lit = cast<StringLiteral>(Val: LangStr); |
16889 | assert(Lit->isUnevaluated() && "Unexpected string literal kind" ); |
16890 | |
16891 | StringRef Lang = Lit->getString(); |
16892 | LinkageSpecLanguageIDs Language; |
16893 | if (Lang == "C" ) |
16894 | Language = LinkageSpecLanguageIDs::C; |
16895 | else if (Lang == "C++" ) |
16896 | Language = LinkageSpecLanguageIDs::CXX; |
16897 | else { |
16898 | Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) |
16899 | << LangStr->getSourceRange(); |
16900 | return nullptr; |
16901 | } |
16902 | |
16903 | // FIXME: Add all the various semantics of linkage specifications |
16904 | |
16905 | LinkageSpecDecl *D = LinkageSpecDecl::Create(C&: Context, DC: CurContext, ExternLoc, |
16906 | LangLoc: LangStr->getExprLoc(), Lang: Language, |
16907 | HasBraces: LBraceLoc.isValid()); |
16908 | |
16909 | /// C++ [module.unit]p7.2.3 |
16910 | /// - Otherwise, if the declaration |
16911 | /// - ... |
16912 | /// - ... |
16913 | /// - appears within a linkage-specification, |
16914 | /// it is attached to the global module. |
16915 | /// |
16916 | /// If the declaration is already in global module fragment, we don't |
16917 | /// need to attach it again. |
16918 | if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) { |
16919 | Module *GlobalModule = PushImplicitGlobalModuleFragment(BeginLoc: ExternLoc); |
16920 | D->setLocalOwningModule(GlobalModule); |
16921 | } |
16922 | |
16923 | CurContext->addDecl(D); |
16924 | PushDeclContext(S, D); |
16925 | return D; |
16926 | } |
16927 | |
16928 | /// ActOnFinishLinkageSpecification - Complete the definition of |
16929 | /// the C++ linkage specification LinkageSpec. If RBraceLoc is |
16930 | /// valid, it's the position of the closing '}' brace in a linkage |
16931 | /// specification that uses braces. |
16932 | Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, |
16933 | Decl *LinkageSpec, |
16934 | SourceLocation RBraceLoc) { |
16935 | if (RBraceLoc.isValid()) { |
16936 | LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(Val: LinkageSpec); |
16937 | LSDecl->setRBraceLoc(RBraceLoc); |
16938 | } |
16939 | |
16940 | // If the current module doesn't has Parent, it implies that the |
16941 | // LinkageSpec isn't in the module created by itself. So we don't |
16942 | // need to pop it. |
16943 | if (getLangOpts().CPlusPlusModules && getCurrentModule() && |
16944 | getCurrentModule()->isImplicitGlobalModule() && |
16945 | getCurrentModule()->Parent) |
16946 | PopImplicitGlobalModuleFragment(); |
16947 | |
16948 | PopDeclContext(); |
16949 | return LinkageSpec; |
16950 | } |
16951 | |
16952 | Decl *Sema::ActOnEmptyDeclaration(Scope *S, |
16953 | const ParsedAttributesView &AttrList, |
16954 | SourceLocation SemiLoc) { |
16955 | Decl *ED = EmptyDecl::Create(C&: Context, DC: CurContext, L: SemiLoc); |
16956 | // Attribute declarations appertain to empty declaration so we handle |
16957 | // them here. |
16958 | ProcessDeclAttributeList(S, D: ED, AttrList); |
16959 | |
16960 | CurContext->addDecl(D: ED); |
16961 | return ED; |
16962 | } |
16963 | |
16964 | /// Perform semantic analysis for the variable declaration that |
16965 | /// occurs within a C++ catch clause, returning the newly-created |
16966 | /// variable. |
16967 | VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, |
16968 | SourceLocation StartLoc, |
16969 | SourceLocation Loc, |
16970 | const IdentifierInfo *Name) { |
16971 | bool Invalid = false; |
16972 | QualType ExDeclType = TInfo->getType(); |
16973 | |
16974 | // Arrays and functions decay. |
16975 | if (ExDeclType->isArrayType()) |
16976 | ExDeclType = Context.getArrayDecayedType(T: ExDeclType); |
16977 | else if (ExDeclType->isFunctionType()) |
16978 | ExDeclType = Context.getPointerType(T: ExDeclType); |
16979 | |
16980 | // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. |
16981 | // The exception-declaration shall not denote a pointer or reference to an |
16982 | // incomplete type, other than [cv] void*. |
16983 | // N2844 forbids rvalue references. |
16984 | if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { |
16985 | Diag(Loc, diag::err_catch_rvalue_ref); |
16986 | Invalid = true; |
16987 | } |
16988 | |
16989 | if (ExDeclType->isVariablyModifiedType()) { |
16990 | Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; |
16991 | Invalid = true; |
16992 | } |
16993 | |
16994 | QualType BaseType = ExDeclType; |
16995 | int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference |
16996 | unsigned DK = diag::err_catch_incomplete; |
16997 | if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { |
16998 | BaseType = Ptr->getPointeeType(); |
16999 | Mode = 1; |
17000 | DK = diag::err_catch_incomplete_ptr; |
17001 | } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { |
17002 | // For the purpose of error recovery, we treat rvalue refs like lvalue refs. |
17003 | BaseType = Ref->getPointeeType(); |
17004 | Mode = 2; |
17005 | DK = diag::err_catch_incomplete_ref; |
17006 | } |
17007 | if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && |
17008 | !BaseType->isDependentType() && RequireCompleteType(Loc, T: BaseType, DiagID: DK)) |
17009 | Invalid = true; |
17010 | |
17011 | if (!Invalid && BaseType.isWebAssemblyReferenceType()) { |
17012 | Diag(Loc, diag::err_wasm_reftype_tc) << 1; |
17013 | Invalid = true; |
17014 | } |
17015 | |
17016 | if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { |
17017 | Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; |
17018 | Invalid = true; |
17019 | } |
17020 | |
17021 | if (!Invalid && !ExDeclType->isDependentType() && |
17022 | RequireNonAbstractType(Loc, ExDeclType, |
17023 | diag::err_abstract_type_in_decl, |
17024 | AbstractVariableType)) |
17025 | Invalid = true; |
17026 | |
17027 | // Only the non-fragile NeXT runtime currently supports C++ catches |
17028 | // of ObjC types, and no runtime supports catching ObjC types by value. |
17029 | if (!Invalid && getLangOpts().ObjC) { |
17030 | QualType T = ExDeclType; |
17031 | if (const ReferenceType *RT = T->getAs<ReferenceType>()) |
17032 | T = RT->getPointeeType(); |
17033 | |
17034 | if (T->isObjCObjectType()) { |
17035 | Diag(Loc, diag::err_objc_object_catch); |
17036 | Invalid = true; |
17037 | } else if (T->isObjCObjectPointerType()) { |
17038 | // FIXME: should this be a test for macosx-fragile specifically? |
17039 | if (getLangOpts().ObjCRuntime.isFragile()) |
17040 | Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); |
17041 | } |
17042 | } |
17043 | |
17044 | VarDecl *ExDecl = VarDecl::Create(C&: Context, DC: CurContext, StartLoc, IdLoc: Loc, Id: Name, |
17045 | T: ExDeclType, TInfo, S: SC_None); |
17046 | ExDecl->setExceptionVariable(true); |
17047 | |
17048 | // In ARC, infer 'retaining' for variables of retainable type. |
17049 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) |
17050 | Invalid = true; |
17051 | |
17052 | if (!Invalid && !ExDeclType->isDependentType()) { |
17053 | if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { |
17054 | // Insulate this from anything else we might currently be parsing. |
17055 | EnterExpressionEvaluationContext scope( |
17056 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); |
17057 | |
17058 | // C++ [except.handle]p16: |
17059 | // The object declared in an exception-declaration or, if the |
17060 | // exception-declaration does not specify a name, a temporary (12.2) is |
17061 | // copy-initialized (8.5) from the exception object. [...] |
17062 | // The object is destroyed when the handler exits, after the destruction |
17063 | // of any automatic objects initialized within the handler. |
17064 | // |
17065 | // We just pretend to initialize the object with itself, then make sure |
17066 | // it can be destroyed later. |
17067 | QualType initType = Context.getExceptionObjectType(T: ExDeclType); |
17068 | |
17069 | InitializedEntity entity = |
17070 | InitializedEntity::InitializeVariable(Var: ExDecl); |
17071 | InitializationKind initKind = |
17072 | InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: SourceLocation()); |
17073 | |
17074 | Expr *opaqueValue = |
17075 | new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); |
17076 | InitializationSequence sequence(*this, entity, initKind, opaqueValue); |
17077 | ExprResult result = sequence.Perform(S&: *this, Entity: entity, Kind: initKind, Args: opaqueValue); |
17078 | if (result.isInvalid()) |
17079 | Invalid = true; |
17080 | else { |
17081 | // If the constructor used was non-trivial, set this as the |
17082 | // "initializer". |
17083 | CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); |
17084 | if (!construct->getConstructor()->isTrivial()) { |
17085 | Expr *init = MaybeCreateExprWithCleanups(construct); |
17086 | ExDecl->setInit(init); |
17087 | } |
17088 | |
17089 | // And make sure it's destructable. |
17090 | FinalizeVarWithDestructor(VD: ExDecl, Record: recordType); |
17091 | } |
17092 | } |
17093 | } |
17094 | |
17095 | if (Invalid) |
17096 | ExDecl->setInvalidDecl(); |
17097 | |
17098 | return ExDecl; |
17099 | } |
17100 | |
17101 | /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch |
17102 | /// handler. |
17103 | Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { |
17104 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D); |
17105 | bool Invalid = D.isInvalidType(); |
17106 | |
17107 | // Check for unexpanded parameter packs. |
17108 | if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo, |
17109 | UPPC: UPPC_ExceptionType)) { |
17110 | TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy, |
17111 | Loc: D.getIdentifierLoc()); |
17112 | Invalid = true; |
17113 | } |
17114 | |
17115 | const IdentifierInfo *II = D.getIdentifier(); |
17116 | if (NamedDecl *PrevDecl = |
17117 | LookupSingleName(S, Name: II, Loc: D.getIdentifierLoc(), NameKind: LookupOrdinaryName, |
17118 | Redecl: RedeclarationKind::ForVisibleRedeclaration)) { |
17119 | // The scope should be freshly made just for us. There is just no way |
17120 | // it contains any previous declaration, except for function parameters in |
17121 | // a function-try-block's catch statement. |
17122 | assert(!S->isDeclScope(PrevDecl)); |
17123 | if (isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) { |
17124 | Diag(D.getIdentifierLoc(), diag::err_redefinition) |
17125 | << D.getIdentifier(); |
17126 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); |
17127 | Invalid = true; |
17128 | } else if (PrevDecl->isTemplateParameter()) |
17129 | // Maybe we will complain about the shadowed template parameter. |
17130 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); |
17131 | } |
17132 | |
17133 | if (D.getCXXScopeSpec().isSet() && !Invalid) { |
17134 | Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) |
17135 | << D.getCXXScopeSpec().getRange(); |
17136 | Invalid = true; |
17137 | } |
17138 | |
17139 | VarDecl *ExDecl = BuildExceptionDeclaration( |
17140 | S, TInfo, StartLoc: D.getBeginLoc(), Loc: D.getIdentifierLoc(), Name: D.getIdentifier()); |
17141 | if (Invalid) |
17142 | ExDecl->setInvalidDecl(); |
17143 | |
17144 | // Add the exception declaration into this scope. |
17145 | if (II) |
17146 | PushOnScopeChains(ExDecl, S); |
17147 | else |
17148 | CurContext->addDecl(ExDecl); |
17149 | |
17150 | ProcessDeclAttributes(S, ExDecl, D); |
17151 | return ExDecl; |
17152 | } |
17153 | |
17154 | Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, |
17155 | Expr *AssertExpr, |
17156 | Expr *AssertMessageExpr, |
17157 | SourceLocation RParenLoc) { |
17158 | if (DiagnoseUnexpandedParameterPack(E: AssertExpr, UPPC: UPPC_StaticAssertExpression)) |
17159 | return nullptr; |
17160 | |
17161 | return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, |
17162 | AssertMessageExpr, RParenLoc, Failed: false); |
17163 | } |
17164 | |
17165 | static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) { |
17166 | switch (BTK) { |
17167 | case BuiltinType::Char_S: |
17168 | case BuiltinType::Char_U: |
17169 | break; |
17170 | case BuiltinType::Char8: |
17171 | OS << "u8" ; |
17172 | break; |
17173 | case BuiltinType::Char16: |
17174 | OS << 'u'; |
17175 | break; |
17176 | case BuiltinType::Char32: |
17177 | OS << 'U'; |
17178 | break; |
17179 | case BuiltinType::WChar_S: |
17180 | case BuiltinType::WChar_U: |
17181 | OS << 'L'; |
17182 | break; |
17183 | default: |
17184 | llvm_unreachable("Non-character type" ); |
17185 | } |
17186 | } |
17187 | |
17188 | /// Convert character's value, interpreted as a code unit, to a string. |
17189 | /// The value needs to be zero-extended to 32-bits. |
17190 | /// FIXME: This assumes Unicode literal encodings |
17191 | static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy, |
17192 | unsigned TyWidth, |
17193 | SmallVectorImpl<char> &Str) { |
17194 | char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT]; |
17195 | char *Ptr = Arr; |
17196 | BuiltinType::Kind K = BTy->getKind(); |
17197 | llvm::raw_svector_ostream OS(Str); |
17198 | |
17199 | // This should catch Char_S, Char_U, Char8, and use of escaped characters in |
17200 | // other types. |
17201 | if (K == BuiltinType::Char_S || K == BuiltinType::Char_U || |
17202 | K == BuiltinType::Char8 || Value <= 0x7F) { |
17203 | StringRef Escaped = escapeCStyle<EscapeChar::Single>(Ch: Value); |
17204 | if (!Escaped.empty()) |
17205 | EscapeStringForDiagnostic(Str: Escaped, OutStr&: Str); |
17206 | else |
17207 | OS << static_cast<char>(Value); |
17208 | return; |
17209 | } |
17210 | |
17211 | switch (K) { |
17212 | case BuiltinType::Char16: |
17213 | case BuiltinType::Char32: |
17214 | case BuiltinType::WChar_S: |
17215 | case BuiltinType::WChar_U: { |
17216 | if (llvm::ConvertCodePointToUTF8(Source: Value, ResultPtr&: Ptr)) |
17217 | EscapeStringForDiagnostic(Str: StringRef(Arr, Ptr - Arr), OutStr&: Str); |
17218 | else |
17219 | OS << "\\x" |
17220 | << llvm::format_hex_no_prefix(N: Value, Width: TyWidth / 4, /*Upper=*/true); |
17221 | break; |
17222 | } |
17223 | default: |
17224 | llvm_unreachable("Non-character type is passed" ); |
17225 | } |
17226 | } |
17227 | |
17228 | /// Convert \V to a string we can present to the user in a diagnostic |
17229 | /// \T is the type of the expression that has been evaluated into \V |
17230 | static bool ConvertAPValueToString(const APValue &V, QualType T, |
17231 | SmallVectorImpl<char> &Str, |
17232 | ASTContext &Context) { |
17233 | if (!V.hasValue()) |
17234 | return false; |
17235 | |
17236 | switch (V.getKind()) { |
17237 | case APValue::ValueKind::Int: |
17238 | if (T->isBooleanType()) { |
17239 | // Bools are reduced to ints during evaluation, but for |
17240 | // diagnostic purposes we want to print them as |
17241 | // true or false. |
17242 | int64_t BoolValue = V.getInt().getExtValue(); |
17243 | assert((BoolValue == 0 || BoolValue == 1) && |
17244 | "Bool type, but value is not 0 or 1" ); |
17245 | llvm::raw_svector_ostream OS(Str); |
17246 | OS << (BoolValue ? "true" : "false" ); |
17247 | } else { |
17248 | llvm::raw_svector_ostream OS(Str); |
17249 | // Same is true for chars. |
17250 | // We want to print the character representation for textual types |
17251 | const auto *BTy = T->getAs<BuiltinType>(); |
17252 | if (BTy) { |
17253 | switch (BTy->getKind()) { |
17254 | case BuiltinType::Char_S: |
17255 | case BuiltinType::Char_U: |
17256 | case BuiltinType::Char8: |
17257 | case BuiltinType::Char16: |
17258 | case BuiltinType::Char32: |
17259 | case BuiltinType::WChar_S: |
17260 | case BuiltinType::WChar_U: { |
17261 | unsigned TyWidth = Context.getIntWidth(T); |
17262 | assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width" ); |
17263 | uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue()); |
17264 | WriteCharTypePrefix(BTK: BTy->getKind(), OS); |
17265 | OS << '\''; |
17266 | WriteCharValueForDiagnostic(Value: CodeUnit, BTy, TyWidth, Str); |
17267 | OS << "' (0x" |
17268 | << llvm::format_hex_no_prefix(N: CodeUnit, /*Width=*/2, |
17269 | /*Upper=*/true) |
17270 | << ", " << V.getInt() << ')'; |
17271 | return true; |
17272 | } |
17273 | default: |
17274 | break; |
17275 | } |
17276 | } |
17277 | V.getInt().toString(Str); |
17278 | } |
17279 | |
17280 | break; |
17281 | |
17282 | case APValue::ValueKind::Float: |
17283 | V.getFloat().toString(Str); |
17284 | break; |
17285 | |
17286 | case APValue::ValueKind::LValue: |
17287 | if (V.isNullPointer()) { |
17288 | llvm::raw_svector_ostream OS(Str); |
17289 | OS << "nullptr" ; |
17290 | } else |
17291 | return false; |
17292 | break; |
17293 | |
17294 | case APValue::ValueKind::ComplexFloat: { |
17295 | llvm::raw_svector_ostream OS(Str); |
17296 | OS << '('; |
17297 | V.getComplexFloatReal().toString(Str); |
17298 | OS << " + " ; |
17299 | V.getComplexFloatImag().toString(Str); |
17300 | OS << "i)" ; |
17301 | } break; |
17302 | |
17303 | case APValue::ValueKind::ComplexInt: { |
17304 | llvm::raw_svector_ostream OS(Str); |
17305 | OS << '('; |
17306 | V.getComplexIntReal().toString(Str); |
17307 | OS << " + " ; |
17308 | V.getComplexIntImag().toString(Str); |
17309 | OS << "i)" ; |
17310 | } break; |
17311 | |
17312 | default: |
17313 | return false; |
17314 | } |
17315 | |
17316 | return true; |
17317 | } |
17318 | |
17319 | /// Some Expression types are not useful to print notes about, |
17320 | /// e.g. literals and values that have already been expanded |
17321 | /// before such as int-valued template parameters. |
17322 | static bool UsefulToPrintExpr(const Expr *E) { |
17323 | E = E->IgnoreParenImpCasts(); |
17324 | // Literals are pretty easy for humans to understand. |
17325 | if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr, |
17326 | CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(Val: E)) |
17327 | return false; |
17328 | |
17329 | // These have been substituted from template parameters |
17330 | // and appear as literals in the static assert error. |
17331 | if (isa<SubstNonTypeTemplateParmExpr>(Val: E)) |
17332 | return false; |
17333 | |
17334 | // -5 is also simple to understand. |
17335 | if (const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: E)) |
17336 | return UsefulToPrintExpr(E: UnaryOp->getSubExpr()); |
17337 | |
17338 | // Only print nested arithmetic operators. |
17339 | if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) |
17340 | return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() || |
17341 | BO->isBitwiseOp()); |
17342 | |
17343 | return true; |
17344 | } |
17345 | |
17346 | /// Try to print more useful information about a failed static_assert |
17347 | /// with expression \E |
17348 | void Sema::DiagnoseStaticAssertDetails(const Expr *E) { |
17349 | if (const auto *Op = dyn_cast<BinaryOperator>(Val: E); |
17350 | Op && Op->getOpcode() != BO_LOr) { |
17351 | const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts(); |
17352 | const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts(); |
17353 | |
17354 | // Ignore comparisons of boolean expressions with a boolean literal. |
17355 | if ((isa<CXXBoolLiteralExpr>(Val: LHS) && RHS->getType()->isBooleanType()) || |
17356 | (isa<CXXBoolLiteralExpr>(Val: RHS) && LHS->getType()->isBooleanType())) |
17357 | return; |
17358 | |
17359 | // Don't print obvious expressions. |
17360 | if (!UsefulToPrintExpr(E: LHS) && !UsefulToPrintExpr(E: RHS)) |
17361 | return; |
17362 | |
17363 | struct { |
17364 | const clang::Expr *Cond; |
17365 | Expr::EvalResult Result; |
17366 | SmallString<12> ValueString; |
17367 | bool Print; |
17368 | } DiagSide[2] = {{.Cond: LHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false}, |
17369 | {.Cond: RHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false}}; |
17370 | for (unsigned I = 0; I < 2; I++) { |
17371 | const Expr *Side = DiagSide[I].Cond; |
17372 | |
17373 | Side->EvaluateAsRValue(Result&: DiagSide[I].Result, Ctx: Context, InConstantContext: true); |
17374 | |
17375 | DiagSide[I].Print = |
17376 | ConvertAPValueToString(V: DiagSide[I].Result.Val, T: Side->getType(), |
17377 | Str&: DiagSide[I].ValueString, Context); |
17378 | } |
17379 | if (DiagSide[0].Print && DiagSide[1].Print) { |
17380 | Diag(Op->getExprLoc(), diag::note_expr_evaluates_to) |
17381 | << DiagSide[0].ValueString << Op->getOpcodeStr() |
17382 | << DiagSide[1].ValueString << Op->getSourceRange(); |
17383 | } |
17384 | } |
17385 | } |
17386 | |
17387 | bool Sema::EvaluateStaticAssertMessageAsString(Expr *Message, |
17388 | std::string &Result, |
17389 | ASTContext &Ctx, |
17390 | bool ErrorOnInvalidMessage) { |
17391 | assert(Message); |
17392 | assert(!Message->isTypeDependent() && !Message->isValueDependent() && |
17393 | "can't evaluate a dependant static assert message" ); |
17394 | |
17395 | if (const auto *SL = dyn_cast<StringLiteral>(Val: Message)) { |
17396 | assert(SL->isUnevaluated() && "expected an unevaluated string" ); |
17397 | Result.assign(first: SL->getString().begin(), last: SL->getString().end()); |
17398 | return true; |
17399 | } |
17400 | |
17401 | SourceLocation Loc = Message->getBeginLoc(); |
17402 | QualType T = Message->getType().getNonReferenceType(); |
17403 | auto *RD = T->getAsCXXRecordDecl(); |
17404 | if (!RD) { |
17405 | Diag(Loc, diag::err_static_assert_invalid_message); |
17406 | return false; |
17407 | } |
17408 | |
17409 | auto FindMember = [&](StringRef Member, bool &Empty, |
17410 | bool Diag = false) -> std::optional<LookupResult> { |
17411 | DeclarationName DN = PP.getIdentifierInfo(Name: Member); |
17412 | LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName); |
17413 | LookupQualifiedName(MemberLookup, RD); |
17414 | Empty = MemberLookup.empty(); |
17415 | OverloadCandidateSet Candidates(MemberLookup.getNameLoc(), |
17416 | OverloadCandidateSet::CSK_Normal); |
17417 | if (MemberLookup.empty()) |
17418 | return std::nullopt; |
17419 | return std::move(MemberLookup); |
17420 | }; |
17421 | |
17422 | bool SizeNotFound, DataNotFound; |
17423 | std::optional<LookupResult> SizeMember = FindMember("size" , SizeNotFound); |
17424 | std::optional<LookupResult> DataMember = FindMember("data" , DataNotFound); |
17425 | if (SizeNotFound || DataNotFound) { |
17426 | Diag(Loc, diag::err_static_assert_missing_member_function) |
17427 | << ((SizeNotFound && DataNotFound) ? 2 |
17428 | : SizeNotFound ? 0 |
17429 | : 1); |
17430 | return false; |
17431 | } |
17432 | |
17433 | if (!SizeMember || !DataMember) { |
17434 | if (!SizeMember) |
17435 | FindMember("size" , SizeNotFound, /*Diag=*/true); |
17436 | if (!DataMember) |
17437 | FindMember("data" , DataNotFound, /*Diag=*/true); |
17438 | return false; |
17439 | } |
17440 | |
17441 | auto BuildExpr = [&](LookupResult &LR) { |
17442 | ExprResult Res = BuildMemberReferenceExpr( |
17443 | Message, Message->getType(), Message->getBeginLoc(), false, |
17444 | CXXScopeSpec(), SourceLocation(), nullptr, LR, nullptr, nullptr); |
17445 | if (Res.isInvalid()) |
17446 | return ExprError(); |
17447 | Res = BuildCallExpr(S: nullptr, Fn: Res.get(), LParenLoc: Loc, ArgExprs: std::nullopt, RParenLoc: Loc, ExecConfig: nullptr, |
17448 | IsExecConfig: false, AllowRecovery: true); |
17449 | if (Res.isInvalid()) |
17450 | return ExprError(); |
17451 | if (Res.get()->isTypeDependent() || Res.get()->isValueDependent()) |
17452 | return ExprError(); |
17453 | return TemporaryMaterializationConversion(Res.get()); |
17454 | }; |
17455 | |
17456 | ExprResult SizeE = BuildExpr(*SizeMember); |
17457 | ExprResult DataE = BuildExpr(*DataMember); |
17458 | |
17459 | QualType SizeT = Context.getSizeType(); |
17460 | QualType ConstCharPtr = |
17461 | Context.getPointerType(Context.getConstType(T: Context.CharTy)); |
17462 | |
17463 | ExprResult EvaluatedSize = |
17464 | SizeE.isInvalid() ? ExprError() |
17465 | : BuildConvertedConstantExpression( |
17466 | From: SizeE.get(), T: SizeT, CCE: CCEK_StaticAssertMessageSize); |
17467 | if (EvaluatedSize.isInvalid()) { |
17468 | Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*size*/ 0; |
17469 | return false; |
17470 | } |
17471 | |
17472 | ExprResult EvaluatedData = |
17473 | DataE.isInvalid() |
17474 | ? ExprError() |
17475 | : BuildConvertedConstantExpression(From: DataE.get(), T: ConstCharPtr, |
17476 | CCE: CCEK_StaticAssertMessageData); |
17477 | if (EvaluatedData.isInvalid()) { |
17478 | Diag(Loc, diag::err_static_assert_invalid_mem_fn_ret_ty) << /*data*/ 1; |
17479 | return false; |
17480 | } |
17481 | |
17482 | if (!ErrorOnInvalidMessage && |
17483 | Diags.isIgnored(diag::warn_static_assert_message_constexpr, Loc)) |
17484 | return true; |
17485 | |
17486 | Expr::EvalResult Status; |
17487 | SmallVector<PartialDiagnosticAt, 8> Notes; |
17488 | Status.Diag = &Notes; |
17489 | if (!Message->EvaluateCharRangeAsString(Result, SizeExpression: EvaluatedSize.get(), |
17490 | PtrExpression: EvaluatedData.get(), Ctx, Status) || |
17491 | !Notes.empty()) { |
17492 | Diag(Message->getBeginLoc(), |
17493 | ErrorOnInvalidMessage ? diag::err_static_assert_message_constexpr |
17494 | : diag::warn_static_assert_message_constexpr); |
17495 | for (const auto &Note : Notes) |
17496 | Diag(Note.first, Note.second); |
17497 | return !ErrorOnInvalidMessage; |
17498 | } |
17499 | return true; |
17500 | } |
17501 | |
17502 | Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, |
17503 | Expr *AssertExpr, Expr *AssertMessage, |
17504 | SourceLocation RParenLoc, |
17505 | bool Failed) { |
17506 | assert(AssertExpr != nullptr && "Expected non-null condition" ); |
17507 | if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && |
17508 | (!AssertMessage || (!AssertMessage->isTypeDependent() && |
17509 | !AssertMessage->isValueDependent())) && |
17510 | !Failed) { |
17511 | // In a static_assert-declaration, the constant-expression shall be a |
17512 | // constant expression that can be contextually converted to bool. |
17513 | ExprResult Converted = PerformContextuallyConvertToBool(From: AssertExpr); |
17514 | if (Converted.isInvalid()) |
17515 | Failed = true; |
17516 | |
17517 | ExprResult FullAssertExpr = |
17518 | ActOnFinishFullExpr(Expr: Converted.get(), CC: StaticAssertLoc, |
17519 | /*DiscardedValue*/ false, |
17520 | /*IsConstexpr*/ true); |
17521 | if (FullAssertExpr.isInvalid()) |
17522 | Failed = true; |
17523 | else |
17524 | AssertExpr = FullAssertExpr.get(); |
17525 | |
17526 | llvm::APSInt Cond; |
17527 | Expr *BaseExpr = AssertExpr; |
17528 | AllowFoldKind FoldKind = NoFold; |
17529 | |
17530 | if (!getLangOpts().CPlusPlus) { |
17531 | // In C mode, allow folding as an extension for better compatibility with |
17532 | // C++ in terms of expressions like static_assert("test") or |
17533 | // static_assert(nullptr). |
17534 | FoldKind = AllowFold; |
17535 | } |
17536 | |
17537 | if (!Failed && VerifyIntegerConstantExpression( |
17538 | BaseExpr, &Cond, |
17539 | diag::err_static_assert_expression_is_not_constant, |
17540 | FoldKind).isInvalid()) |
17541 | Failed = true; |
17542 | |
17543 | // If the static_assert passes, only verify that |
17544 | // the message is grammatically valid without evaluating it. |
17545 | if (!Failed && AssertMessage && Cond.getBoolValue()) { |
17546 | std::string Str; |
17547 | EvaluateStaticAssertMessageAsString(Message: AssertMessage, Result&: Str, Ctx&: Context, |
17548 | /*ErrorOnInvalidMessage=*/false); |
17549 | } |
17550 | |
17551 | // CWG2518 |
17552 | // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a |
17553 | // template definition, the declaration has no effect. |
17554 | bool InTemplateDefinition = |
17555 | getLangOpts().CPlusPlus && CurContext->isDependentContext(); |
17556 | |
17557 | if (!Failed && !Cond && !InTemplateDefinition) { |
17558 | SmallString<256> MsgBuffer; |
17559 | llvm::raw_svector_ostream Msg(MsgBuffer); |
17560 | bool HasMessage = AssertMessage; |
17561 | if (AssertMessage) { |
17562 | std::string Str; |
17563 | HasMessage = |
17564 | EvaluateStaticAssertMessageAsString( |
17565 | Message: AssertMessage, Result&: Str, Ctx&: Context, /*ErrorOnInvalidMessage=*/true) || |
17566 | !Str.empty(); |
17567 | Msg << Str; |
17568 | } |
17569 | Expr *InnerCond = nullptr; |
17570 | std::string InnerCondDescription; |
17571 | std::tie(args&: InnerCond, args&: InnerCondDescription) = |
17572 | findFailedBooleanCondition(Cond: Converted.get()); |
17573 | if (InnerCond && isa<ConceptSpecializationExpr>(Val: InnerCond)) { |
17574 | // Drill down into concept specialization expressions to see why they |
17575 | // weren't satisfied. |
17576 | Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed) |
17577 | << !HasMessage << Msg.str() << AssertExpr->getSourceRange(); |
17578 | ConstraintSatisfaction Satisfaction; |
17579 | if (!CheckConstraintSatisfaction(ConstraintExpr: InnerCond, Satisfaction)) |
17580 | DiagnoseUnsatisfiedConstraint(Satisfaction); |
17581 | } else if (InnerCond && !isa<CXXBoolLiteralExpr>(Val: InnerCond) |
17582 | && !isa<IntegerLiteral>(Val: InnerCond)) { |
17583 | Diag(InnerCond->getBeginLoc(), |
17584 | diag::err_static_assert_requirement_failed) |
17585 | << InnerCondDescription << !HasMessage << Msg.str() |
17586 | << InnerCond->getSourceRange(); |
17587 | DiagnoseStaticAssertDetails(E: InnerCond); |
17588 | } else { |
17589 | Diag(AssertExpr->getBeginLoc(), diag::err_static_assert_failed) |
17590 | << !HasMessage << Msg.str() << AssertExpr->getSourceRange(); |
17591 | PrintContextStack(); |
17592 | } |
17593 | Failed = true; |
17594 | } |
17595 | } else { |
17596 | ExprResult FullAssertExpr = ActOnFinishFullExpr(Expr: AssertExpr, CC: StaticAssertLoc, |
17597 | /*DiscardedValue*/false, |
17598 | /*IsConstexpr*/true); |
17599 | if (FullAssertExpr.isInvalid()) |
17600 | Failed = true; |
17601 | else |
17602 | AssertExpr = FullAssertExpr.get(); |
17603 | } |
17604 | |
17605 | Decl *Decl = StaticAssertDecl::Create(C&: Context, DC: CurContext, StaticAssertLoc, |
17606 | AssertExpr, Message: AssertMessage, RParenLoc, |
17607 | Failed); |
17608 | |
17609 | CurContext->addDecl(D: Decl); |
17610 | return Decl; |
17611 | } |
17612 | |
17613 | /// Handle a friend tag declaration where the scope specifier was |
17614 | /// templated. |
17615 | DeclResult Sema::ActOnTemplatedFriendTag( |
17616 | Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, |
17617 | CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, |
17618 | const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists) { |
17619 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec); |
17620 | |
17621 | bool IsMemberSpecialization = false; |
17622 | bool Invalid = false; |
17623 | |
17624 | if (TemplateParameterList *TemplateParams = |
17625 | MatchTemplateParametersToScopeSpecifier( |
17626 | DeclStartLoc: TagLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TempParamLists, /*friend*/ IsFriend: true, |
17627 | IsMemberSpecialization, Invalid)) { |
17628 | if (TemplateParams->size() > 0) { |
17629 | // This is a declaration of a class template. |
17630 | if (Invalid) |
17631 | return true; |
17632 | |
17633 | return CheckClassTemplate(S, TagSpec, TUK: TUK_Friend, KWLoc: TagLoc, SS, Name, |
17634 | NameLoc, Attr, TemplateParams, AS: AS_public, |
17635 | /*ModulePrivateLoc=*/SourceLocation(), |
17636 | FriendLoc, NumOuterTemplateParamLists: TempParamLists.size() - 1, |
17637 | OuterTemplateParamLists: TempParamLists.data()).get(); |
17638 | } else { |
17639 | // The "template<>" header is extraneous. |
17640 | Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) |
17641 | << TypeWithKeyword::getTagTypeKindName(Kind) << Name; |
17642 | IsMemberSpecialization = true; |
17643 | } |
17644 | } |
17645 | |
17646 | if (Invalid) return true; |
17647 | |
17648 | bool isAllExplicitSpecializations = true; |
17649 | for (unsigned I = TempParamLists.size(); I-- > 0; ) { |
17650 | if (TempParamLists[I]->size()) { |
17651 | isAllExplicitSpecializations = false; |
17652 | break; |
17653 | } |
17654 | } |
17655 | |
17656 | // FIXME: don't ignore attributes. |
17657 | |
17658 | // If it's explicit specializations all the way down, just forget |
17659 | // about the template header and build an appropriate non-templated |
17660 | // friend. TODO: for source fidelity, remember the headers. |
17661 | if (isAllExplicitSpecializations) { |
17662 | if (SS.isEmpty()) { |
17663 | bool Owned = false; |
17664 | bool IsDependent = false; |
17665 | return ActOnTag(S, TagSpec, TUK: TUK_Friend, KWLoc: TagLoc, SS, Name, NameLoc, Attr, |
17666 | AS: AS_public, |
17667 | /*ModulePrivateLoc=*/SourceLocation(), |
17668 | TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent, |
17669 | /*ScopedEnumKWLoc=*/SourceLocation(), |
17670 | /*ScopedEnumUsesClassTag=*/false, |
17671 | /*UnderlyingType=*/TypeResult(), |
17672 | /*IsTypeSpecifier=*/false, |
17673 | /*IsTemplateParamOrArg=*/false, /*OOK=*/OOK_Outside); |
17674 | } |
17675 | |
17676 | NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); |
17677 | ElaboratedTypeKeyword Keyword |
17678 | = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind); |
17679 | QualType T = CheckTypenameType(Keyword, KeywordLoc: TagLoc, QualifierLoc, |
17680 | II: *Name, IILoc: NameLoc); |
17681 | if (T.isNull()) |
17682 | return true; |
17683 | |
17684 | TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); |
17685 | if (isa<DependentNameType>(Val: T)) { |
17686 | DependentNameTypeLoc TL = |
17687 | TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); |
17688 | TL.setElaboratedKeywordLoc(TagLoc); |
17689 | TL.setQualifierLoc(QualifierLoc); |
17690 | TL.setNameLoc(NameLoc); |
17691 | } else { |
17692 | ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); |
17693 | TL.setElaboratedKeywordLoc(TagLoc); |
17694 | TL.setQualifierLoc(QualifierLoc); |
17695 | TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); |
17696 | } |
17697 | |
17698 | FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, |
17699 | Friend_: TSI, FriendL: FriendLoc, FriendTypeTPLists: TempParamLists); |
17700 | Friend->setAccess(AS_public); |
17701 | CurContext->addDecl(Friend); |
17702 | return Friend; |
17703 | } |
17704 | |
17705 | assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?" ); |
17706 | |
17707 | |
17708 | |
17709 | // Handle the case of a templated-scope friend class. e.g. |
17710 | // template <class T> class A<T>::B; |
17711 | // FIXME: we don't support these right now. |
17712 | Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) |
17713 | << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); |
17714 | ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind); |
17715 | QualType T = Context.getDependentNameType(Keyword: ETK, NNS: SS.getScopeRep(), Name); |
17716 | TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); |
17717 | DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); |
17718 | TL.setElaboratedKeywordLoc(TagLoc); |
17719 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); |
17720 | TL.setNameLoc(NameLoc); |
17721 | |
17722 | FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, |
17723 | Friend_: TSI, FriendL: FriendLoc, FriendTypeTPLists: TempParamLists); |
17724 | Friend->setAccess(AS_public); |
17725 | Friend->setUnsupportedFriend(true); |
17726 | CurContext->addDecl(Friend); |
17727 | return Friend; |
17728 | } |
17729 | |
17730 | /// Handle a friend type declaration. This works in tandem with |
17731 | /// ActOnTag. |
17732 | /// |
17733 | /// Notes on friend class templates: |
17734 | /// |
17735 | /// We generally treat friend class declarations as if they were |
17736 | /// declaring a class. So, for example, the elaborated type specifier |
17737 | /// in a friend declaration is required to obey the restrictions of a |
17738 | /// class-head (i.e. no typedefs in the scope chain), template |
17739 | /// parameters are required to match up with simple template-ids, &c. |
17740 | /// However, unlike when declaring a template specialization, it's |
17741 | /// okay to refer to a template specialization without an empty |
17742 | /// template parameter declaration, e.g. |
17743 | /// friend class A<T>::B<unsigned>; |
17744 | /// We permit this as a special case; if there are any template |
17745 | /// parameters present at all, require proper matching, i.e. |
17746 | /// template <> template \<class T> friend class A<int>::B; |
17747 | Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, |
17748 | MultiTemplateParamsArg TempParams) { |
17749 | SourceLocation Loc = DS.getBeginLoc(); |
17750 | SourceLocation FriendLoc = DS.getFriendSpecLoc(); |
17751 | |
17752 | assert(DS.isFriendSpecified()); |
17753 | assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); |
17754 | |
17755 | // C++ [class.friend]p3: |
17756 | // A friend declaration that does not declare a function shall have one of |
17757 | // the following forms: |
17758 | // friend elaborated-type-specifier ; |
17759 | // friend simple-type-specifier ; |
17760 | // friend typename-specifier ; |
17761 | // |
17762 | // If the friend keyword isn't first, or if the declarations has any type |
17763 | // qualifiers, then the declaration doesn't have that form. |
17764 | if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst()) |
17765 | Diag(FriendLoc, diag::err_friend_not_first_in_declaration); |
17766 | if (DS.getTypeQualifiers()) { |
17767 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) |
17768 | Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const" ; |
17769 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) |
17770 | Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile" ; |
17771 | if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) |
17772 | Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict" ; |
17773 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) |
17774 | Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic" ; |
17775 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) |
17776 | Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned" ; |
17777 | } |
17778 | |
17779 | // Try to convert the decl specifier to a type. This works for |
17780 | // friend templates because ActOnTag never produces a ClassTemplateDecl |
17781 | // for a TUK_Friend. |
17782 | Declarator TheDeclarator(DS, ParsedAttributesView::none(), |
17783 | DeclaratorContext::Member); |
17784 | TypeSourceInfo *TSI = GetTypeForDeclarator(D&: TheDeclarator); |
17785 | QualType T = TSI->getType(); |
17786 | if (TheDeclarator.isInvalidType()) |
17787 | return nullptr; |
17788 | |
17789 | if (DiagnoseUnexpandedParameterPack(Loc, T: TSI, UPPC: UPPC_FriendDeclaration)) |
17790 | return nullptr; |
17791 | |
17792 | if (!T->isElaboratedTypeSpecifier()) { |
17793 | if (TempParams.size()) { |
17794 | // C++23 [dcl.pre]p5: |
17795 | // In a simple-declaration, the optional init-declarator-list can be |
17796 | // omitted only when declaring a class or enumeration, that is, when |
17797 | // the decl-specifier-seq contains either a class-specifier, an |
17798 | // elaborated-type-specifier with a class-key, or an enum-specifier. |
17799 | // |
17800 | // The declaration of a template-declaration or explicit-specialization |
17801 | // is never a member-declaration, so this must be a simple-declaration |
17802 | // with no init-declarator-list. Therefore, this is ill-formed. |
17803 | Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange(); |
17804 | return nullptr; |
17805 | } else if (const RecordDecl *RD = T->getAsRecordDecl()) { |
17806 | SmallString<16> InsertionText(" " ); |
17807 | InsertionText += RD->getKindName(); |
17808 | |
17809 | Diag(Loc, getLangOpts().CPlusPlus11 |
17810 | ? diag::warn_cxx98_compat_unelaborated_friend_type |
17811 | : diag::ext_unelaborated_friend_type) |
17812 | << (unsigned)RD->getTagKind() << T |
17813 | << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), |
17814 | InsertionText); |
17815 | } else { |
17816 | Diag(FriendLoc, getLangOpts().CPlusPlus11 |
17817 | ? diag::warn_cxx98_compat_nonclass_type_friend |
17818 | : diag::ext_nonclass_type_friend) |
17819 | << T << DS.getSourceRange(); |
17820 | } |
17821 | } |
17822 | |
17823 | // C++98 [class.friend]p1: A friend of a class is a function |
17824 | // or class that is not a member of the class . . . |
17825 | // This is fixed in DR77, which just barely didn't make the C++03 |
17826 | // deadline. It's also a very silly restriction that seriously |
17827 | // affects inner classes and which nobody else seems to implement; |
17828 | // thus we never diagnose it, not even in -pedantic. |
17829 | // |
17830 | // But note that we could warn about it: it's always useless to |
17831 | // friend one of your own members (it's not, however, worthless to |
17832 | // friend a member of an arbitrary specialization of your template). |
17833 | |
17834 | Decl *D; |
17835 | if (!TempParams.empty()) |
17836 | D = FriendTemplateDecl::Create(Context, DC: CurContext, Loc, Params: TempParams, Friend: TSI, |
17837 | FriendLoc); |
17838 | else |
17839 | D = FriendDecl::Create(C&: Context, DC: CurContext, L: TSI->getTypeLoc().getBeginLoc(), |
17840 | Friend_: TSI, FriendL: FriendLoc); |
17841 | |
17842 | if (!D) |
17843 | return nullptr; |
17844 | |
17845 | D->setAccess(AS_public); |
17846 | CurContext->addDecl(D); |
17847 | |
17848 | return D; |
17849 | } |
17850 | |
17851 | NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, |
17852 | MultiTemplateParamsArg TemplateParams) { |
17853 | const DeclSpec &DS = D.getDeclSpec(); |
17854 | |
17855 | assert(DS.isFriendSpecified()); |
17856 | assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); |
17857 | |
17858 | SourceLocation Loc = D.getIdentifierLoc(); |
17859 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D); |
17860 | |
17861 | // C++ [class.friend]p1 |
17862 | // A friend of a class is a function or class.... |
17863 | // Note that this sees through typedefs, which is intended. |
17864 | // It *doesn't* see through dependent types, which is correct |
17865 | // according to [temp.arg.type]p3: |
17866 | // If a declaration acquires a function type through a |
17867 | // type dependent on a template-parameter and this causes |
17868 | // a declaration that does not use the syntactic form of a |
17869 | // function declarator to have a function type, the program |
17870 | // is ill-formed. |
17871 | if (!TInfo->getType()->isFunctionType()) { |
17872 | Diag(Loc, diag::err_unexpected_friend); |
17873 | |
17874 | // It might be worthwhile to try to recover by creating an |
17875 | // appropriate declaration. |
17876 | return nullptr; |
17877 | } |
17878 | |
17879 | // C++ [namespace.memdef]p3 |
17880 | // - If a friend declaration in a non-local class first declares a |
17881 | // class or function, the friend class or function is a member |
17882 | // of the innermost enclosing namespace. |
17883 | // - The name of the friend is not found by simple name lookup |
17884 | // until a matching declaration is provided in that namespace |
17885 | // scope (either before or after the class declaration granting |
17886 | // friendship). |
17887 | // - If a friend function is called, its name may be found by the |
17888 | // name lookup that considers functions from namespaces and |
17889 | // classes associated with the types of the function arguments. |
17890 | // - When looking for a prior declaration of a class or a function |
17891 | // declared as a friend, scopes outside the innermost enclosing |
17892 | // namespace scope are not considered. |
17893 | |
17894 | CXXScopeSpec &SS = D.getCXXScopeSpec(); |
17895 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); |
17896 | assert(NameInfo.getName()); |
17897 | |
17898 | // Check for unexpanded parameter packs. |
17899 | if (DiagnoseUnexpandedParameterPack(Loc, T: TInfo, UPPC: UPPC_FriendDeclaration) || |
17900 | DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_FriendDeclaration) || |
17901 | DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_FriendDeclaration)) |
17902 | return nullptr; |
17903 | |
17904 | // The context we found the declaration in, or in which we should |
17905 | // create the declaration. |
17906 | DeclContext *DC; |
17907 | Scope *DCScope = S; |
17908 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, |
17909 | RedeclarationKind::ForExternalRedeclaration); |
17910 | |
17911 | bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; |
17912 | |
17913 | // There are five cases here. |
17914 | // - There's no scope specifier and we're in a local class. Only look |
17915 | // for functions declared in the immediately-enclosing block scope. |
17916 | // We recover from invalid scope qualifiers as if they just weren't there. |
17917 | FunctionDecl *FunctionContainingLocalClass = nullptr; |
17918 | if ((SS.isInvalid() || !SS.isSet()) && |
17919 | (FunctionContainingLocalClass = |
17920 | cast<CXXRecordDecl>(Val: CurContext)->isLocalClass())) { |
17921 | // C++11 [class.friend]p11: |
17922 | // If a friend declaration appears in a local class and the name |
17923 | // specified is an unqualified name, a prior declaration is |
17924 | // looked up without considering scopes that are outside the |
17925 | // innermost enclosing non-class scope. For a friend function |
17926 | // declaration, if there is no prior declaration, the program is |
17927 | // ill-formed. |
17928 | |
17929 | // Find the innermost enclosing non-class scope. This is the block |
17930 | // scope containing the local class definition (or for a nested class, |
17931 | // the outer local class). |
17932 | DCScope = S->getFnParent(); |
17933 | |
17934 | // Look up the function name in the scope. |
17935 | Previous.clear(Kind: LookupLocalFriendName); |
17936 | LookupName(R&: Previous, S, /*AllowBuiltinCreation*/false); |
17937 | |
17938 | if (!Previous.empty()) { |
17939 | // All possible previous declarations must have the same context: |
17940 | // either they were declared at block scope or they are members of |
17941 | // one of the enclosing local classes. |
17942 | DC = Previous.getRepresentativeDecl()->getDeclContext(); |
17943 | } else { |
17944 | // This is ill-formed, but provide the context that we would have |
17945 | // declared the function in, if we were permitted to, for error recovery. |
17946 | DC = FunctionContainingLocalClass; |
17947 | } |
17948 | adjustContextForLocalExternDecl(DC); |
17949 | |
17950 | // - There's no scope specifier, in which case we just go to the |
17951 | // appropriate scope and look for a function or function template |
17952 | // there as appropriate. |
17953 | } else if (SS.isInvalid() || !SS.isSet()) { |
17954 | // C++11 [namespace.memdef]p3: |
17955 | // If the name in a friend declaration is neither qualified nor |
17956 | // a template-id and the declaration is a function or an |
17957 | // elaborated-type-specifier, the lookup to determine whether |
17958 | // the entity has been previously declared shall not consider |
17959 | // any scopes outside the innermost enclosing namespace. |
17960 | |
17961 | // Find the appropriate context according to the above. |
17962 | DC = CurContext; |
17963 | |
17964 | // Skip class contexts. If someone can cite chapter and verse |
17965 | // for this behavior, that would be nice --- it's what GCC and |
17966 | // EDG do, and it seems like a reasonable intent, but the spec |
17967 | // really only says that checks for unqualified existing |
17968 | // declarations should stop at the nearest enclosing namespace, |
17969 | // not that they should only consider the nearest enclosing |
17970 | // namespace. |
17971 | while (DC->isRecord()) |
17972 | DC = DC->getParent(); |
17973 | |
17974 | DeclContext *LookupDC = DC->getNonTransparentContext(); |
17975 | while (true) { |
17976 | LookupQualifiedName(R&: Previous, LookupCtx: LookupDC); |
17977 | |
17978 | if (!Previous.empty()) { |
17979 | DC = LookupDC; |
17980 | break; |
17981 | } |
17982 | |
17983 | if (isTemplateId) { |
17984 | if (isa<TranslationUnitDecl>(Val: LookupDC)) break; |
17985 | } else { |
17986 | if (LookupDC->isFileContext()) break; |
17987 | } |
17988 | LookupDC = LookupDC->getParent(); |
17989 | } |
17990 | |
17991 | DCScope = getScopeForDeclContext(S, DC); |
17992 | |
17993 | // - There's a non-dependent scope specifier, in which case we |
17994 | // compute it and do a previous lookup there for a function |
17995 | // or function template. |
17996 | } else if (!SS.getScopeRep()->isDependent()) { |
17997 | DC = computeDeclContext(SS); |
17998 | if (!DC) return nullptr; |
17999 | |
18000 | if (RequireCompleteDeclContext(SS, DC)) return nullptr; |
18001 | |
18002 | LookupQualifiedName(R&: Previous, LookupCtx: DC); |
18003 | |
18004 | // C++ [class.friend]p1: A friend of a class is a function or |
18005 | // class that is not a member of the class . . . |
18006 | if (DC->Equals(CurContext)) |
18007 | Diag(DS.getFriendSpecLoc(), |
18008 | getLangOpts().CPlusPlus11 ? |
18009 | diag::warn_cxx98_compat_friend_is_member : |
18010 | diag::err_friend_is_member); |
18011 | |
18012 | // - There's a scope specifier that does not match any template |
18013 | // parameter lists, in which case we use some arbitrary context, |
18014 | // create a method or method template, and wait for instantiation. |
18015 | // - There's a scope specifier that does match some template |
18016 | // parameter lists, which we don't handle right now. |
18017 | } else { |
18018 | DC = CurContext; |
18019 | assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?" ); |
18020 | } |
18021 | |
18022 | if (!DC->isRecord()) { |
18023 | int DiagArg = -1; |
18024 | switch (D.getName().getKind()) { |
18025 | case UnqualifiedIdKind::IK_ConstructorTemplateId: |
18026 | case UnqualifiedIdKind::IK_ConstructorName: |
18027 | DiagArg = 0; |
18028 | break; |
18029 | case UnqualifiedIdKind::IK_DestructorName: |
18030 | DiagArg = 1; |
18031 | break; |
18032 | case UnqualifiedIdKind::IK_ConversionFunctionId: |
18033 | DiagArg = 2; |
18034 | break; |
18035 | case UnqualifiedIdKind::IK_DeductionGuideName: |
18036 | DiagArg = 3; |
18037 | break; |
18038 | case UnqualifiedIdKind::IK_Identifier: |
18039 | case UnqualifiedIdKind::IK_ImplicitSelfParam: |
18040 | case UnqualifiedIdKind::IK_LiteralOperatorId: |
18041 | case UnqualifiedIdKind::IK_OperatorFunctionId: |
18042 | case UnqualifiedIdKind::IK_TemplateId: |
18043 | break; |
18044 | } |
18045 | // This implies that it has to be an operator or function. |
18046 | if (DiagArg >= 0) { |
18047 | Diag(Loc, diag::err_introducing_special_friend) << DiagArg; |
18048 | return nullptr; |
18049 | } |
18050 | } |
18051 | |
18052 | // FIXME: This is an egregious hack to cope with cases where the scope stack |
18053 | // does not contain the declaration context, i.e., in an out-of-line |
18054 | // definition of a class. |
18055 | Scope FakeDCScope(S, Scope::DeclScope, Diags); |
18056 | if (!DCScope) { |
18057 | FakeDCScope.setEntity(DC); |
18058 | DCScope = &FakeDCScope; |
18059 | } |
18060 | |
18061 | bool AddToScope = true; |
18062 | NamedDecl *ND = ActOnFunctionDeclarator(S: DCScope, D, DC, TInfo, Previous, |
18063 | TemplateParamLists: TemplateParams, AddToScope); |
18064 | if (!ND) return nullptr; |
18065 | |
18066 | assert(ND->getLexicalDeclContext() == CurContext); |
18067 | |
18068 | // If we performed typo correction, we might have added a scope specifier |
18069 | // and changed the decl context. |
18070 | DC = ND->getDeclContext(); |
18071 | |
18072 | // Add the function declaration to the appropriate lookup tables, |
18073 | // adjusting the redeclarations list as necessary. We don't |
18074 | // want to do this yet if the friending class is dependent. |
18075 | // |
18076 | // Also update the scope-based lookup if the target context's |
18077 | // lookup context is in lexical scope. |
18078 | if (!CurContext->isDependentContext()) { |
18079 | DC = DC->getRedeclContext(); |
18080 | DC->makeDeclVisibleInContext(D: ND); |
18081 | if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) |
18082 | PushOnScopeChains(D: ND, S: EnclosingScope, /*AddToContext=*/ false); |
18083 | } |
18084 | |
18085 | FriendDecl *FrD = FriendDecl::Create(C&: Context, DC: CurContext, |
18086 | L: D.getIdentifierLoc(), Friend_: ND, |
18087 | FriendL: DS.getFriendSpecLoc()); |
18088 | FrD->setAccess(AS_public); |
18089 | CurContext->addDecl(FrD); |
18090 | |
18091 | if (ND->isInvalidDecl()) { |
18092 | FrD->setInvalidDecl(); |
18093 | } else { |
18094 | if (DC->isRecord()) CheckFriendAccess(D: ND); |
18095 | |
18096 | FunctionDecl *FD; |
18097 | if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: ND)) |
18098 | FD = FTD->getTemplatedDecl(); |
18099 | else |
18100 | FD = cast<FunctionDecl>(Val: ND); |
18101 | |
18102 | // C++ [class.friend]p6: |
18103 | // A function may be defined in a friend declaration of a class if and |
18104 | // only if the class is a non-local class, and the function name is |
18105 | // unqualified. |
18106 | if (D.isFunctionDefinition()) { |
18107 | // Qualified friend function definition. |
18108 | if (SS.isNotEmpty()) { |
18109 | // FIXME: We should only do this if the scope specifier names the |
18110 | // innermost enclosing namespace; otherwise the fixit changes the |
18111 | // meaning of the code. |
18112 | SemaDiagnosticBuilder DB = |
18113 | Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); |
18114 | |
18115 | DB << SS.getScopeRep(); |
18116 | if (DC->isFileContext()) |
18117 | DB << FixItHint::CreateRemoval(RemoveRange: SS.getRange()); |
18118 | |
18119 | // Friend function defined in a local class. |
18120 | } else if (FunctionContainingLocalClass) { |
18121 | Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); |
18122 | |
18123 | // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have |
18124 | // a template-id, the function name is not unqualified because these is |
18125 | // no name. While the wording requires some reading in-between the |
18126 | // lines, GCC, MSVC, and EDG all consider a friend function |
18127 | // specialization definitions // to be de facto explicit specialization |
18128 | // and diagnose them as such. |
18129 | } else if (isTemplateId) { |
18130 | Diag(NameInfo.getBeginLoc(), diag::err_friend_specialization_def); |
18131 | } |
18132 | } |
18133 | |
18134 | // C++11 [dcl.fct.default]p4: If a friend declaration specifies a |
18135 | // default argument expression, that declaration shall be a definition |
18136 | // and shall be the only declaration of the function or function |
18137 | // template in the translation unit. |
18138 | if (functionDeclHasDefaultArgument(FD)) { |
18139 | // We can't look at FD->getPreviousDecl() because it may not have been set |
18140 | // if we're in a dependent context. If the function is known to be a |
18141 | // redeclaration, we will have narrowed Previous down to the right decl. |
18142 | if (D.isRedeclaration()) { |
18143 | Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); |
18144 | Diag(Previous.getRepresentativeDecl()->getLocation(), |
18145 | diag::note_previous_declaration); |
18146 | } else if (!D.isFunctionDefinition()) |
18147 | Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); |
18148 | } |
18149 | |
18150 | // Mark templated-scope function declarations as unsupported. |
18151 | if (FD->getNumTemplateParameterLists() && SS.isValid()) { |
18152 | Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) |
18153 | << SS.getScopeRep() << SS.getRange() |
18154 | << cast<CXXRecordDecl>(CurContext); |
18155 | FrD->setUnsupportedFriend(true); |
18156 | } |
18157 | } |
18158 | |
18159 | warnOnReservedIdentifier(D: ND); |
18160 | |
18161 | return ND; |
18162 | } |
18163 | |
18164 | void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc, |
18165 | StringLiteral *Message) { |
18166 | AdjustDeclIfTemplate(Decl&: Dcl); |
18167 | |
18168 | FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Val: Dcl); |
18169 | if (!Fn) { |
18170 | Diag(DelLoc, diag::err_deleted_non_function); |
18171 | return; |
18172 | } |
18173 | |
18174 | // Deleted function does not have a body. |
18175 | Fn->setWillHaveBody(false); |
18176 | |
18177 | if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { |
18178 | // Don't consider the implicit declaration we generate for explicit |
18179 | // specializations. FIXME: Do not generate these implicit declarations. |
18180 | if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || |
18181 | Prev->getPreviousDecl()) && |
18182 | !Prev->isDefined()) { |
18183 | Diag(DelLoc, diag::err_deleted_decl_not_first); |
18184 | Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), |
18185 | Prev->isImplicit() ? diag::note_previous_implicit_declaration |
18186 | : diag::note_previous_declaration); |
18187 | // We can't recover from this; the declaration might have already |
18188 | // been used. |
18189 | Fn->setInvalidDecl(); |
18190 | return; |
18191 | } |
18192 | |
18193 | // To maintain the invariant that functions are only deleted on their first |
18194 | // declaration, mark the implicitly-instantiated declaration of the |
18195 | // explicitly-specialized function as deleted instead of marking the |
18196 | // instantiated redeclaration. |
18197 | Fn = Fn->getCanonicalDecl(); |
18198 | } |
18199 | |
18200 | // dllimport/dllexport cannot be deleted. |
18201 | if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { |
18202 | Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; |
18203 | Fn->setInvalidDecl(); |
18204 | } |
18205 | |
18206 | // C++11 [basic.start.main]p3: |
18207 | // A program that defines main as deleted [...] is ill-formed. |
18208 | if (Fn->isMain()) |
18209 | Diag(DelLoc, diag::err_deleted_main); |
18210 | |
18211 | // C++11 [dcl.fct.def.delete]p4: |
18212 | // A deleted function is implicitly inline. |
18213 | Fn->setImplicitlyInline(); |
18214 | Fn->setDeletedAsWritten(D: true, Message); |
18215 | } |
18216 | |
18217 | void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { |
18218 | if (!Dcl || Dcl->isInvalidDecl()) |
18219 | return; |
18220 | |
18221 | auto *FD = dyn_cast<FunctionDecl>(Val: Dcl); |
18222 | if (!FD) { |
18223 | if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Dcl)) { |
18224 | if (getDefaultedFunctionKind(FD: FTD->getTemplatedDecl()).isComparison()) { |
18225 | Diag(DefaultLoc, diag::err_defaulted_comparison_template); |
18226 | return; |
18227 | } |
18228 | } |
18229 | |
18230 | Diag(DefaultLoc, diag::err_default_special_members) |
18231 | << getLangOpts().CPlusPlus20; |
18232 | return; |
18233 | } |
18234 | |
18235 | // Reject if this can't possibly be a defaultable function. |
18236 | DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); |
18237 | if (!DefKind && |
18238 | // A dependent function that doesn't locally look defaultable can |
18239 | // still instantiate to a defaultable function if it's a constructor |
18240 | // or assignment operator. |
18241 | (!FD->isDependentContext() || |
18242 | (!isa<CXXConstructorDecl>(Val: FD) && |
18243 | FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { |
18244 | Diag(DefaultLoc, diag::err_default_special_members) |
18245 | << getLangOpts().CPlusPlus20; |
18246 | return; |
18247 | } |
18248 | |
18249 | // Issue compatibility warning. We already warned if the operator is |
18250 | // 'operator<=>' when parsing the '<=>' token. |
18251 | if (DefKind.isComparison() && |
18252 | DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { |
18253 | Diag(DefaultLoc, getLangOpts().CPlusPlus20 |
18254 | ? diag::warn_cxx17_compat_defaulted_comparison |
18255 | : diag::ext_defaulted_comparison); |
18256 | } |
18257 | |
18258 | FD->setDefaulted(); |
18259 | FD->setExplicitlyDefaulted(); |
18260 | FD->setDefaultLoc(DefaultLoc); |
18261 | |
18262 | // Defer checking functions that are defaulted in a dependent context. |
18263 | if (FD->isDependentContext()) |
18264 | return; |
18265 | |
18266 | // Unset that we will have a body for this function. We might not, |
18267 | // if it turns out to be trivial, and we don't need this marking now |
18268 | // that we've marked it as defaulted. |
18269 | FD->setWillHaveBody(false); |
18270 | |
18271 | if (DefKind.isComparison()) { |
18272 | // If this comparison's defaulting occurs within the definition of its |
18273 | // lexical class context, we have to do the checking when complete. |
18274 | if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext())) |
18275 | if (!RD->isCompleteDefinition()) |
18276 | return; |
18277 | } |
18278 | |
18279 | // If this member fn was defaulted on its first declaration, we will have |
18280 | // already performed the checking in CheckCompletedCXXClass. Such a |
18281 | // declaration doesn't trigger an implicit definition. |
18282 | if (isa<CXXMethodDecl>(Val: FD)) { |
18283 | const FunctionDecl *Primary = FD; |
18284 | if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) |
18285 | // Ask the template instantiation pattern that actually had the |
18286 | // '= default' on it. |
18287 | Primary = Pattern; |
18288 | if (Primary->getCanonicalDecl()->isDefaulted()) |
18289 | return; |
18290 | } |
18291 | |
18292 | if (DefKind.isComparison()) { |
18293 | if (CheckExplicitlyDefaultedComparison(S: nullptr, FD, DCK: DefKind.asComparison())) |
18294 | FD->setInvalidDecl(); |
18295 | else |
18296 | DefineDefaultedComparison(UseLoc: DefaultLoc, FD, DCK: DefKind.asComparison()); |
18297 | } else { |
18298 | auto *MD = cast<CXXMethodDecl>(Val: FD); |
18299 | |
18300 | if (CheckExplicitlyDefaultedSpecialMember(MD, CSM: DefKind.asSpecialMember(), |
18301 | DefaultLoc)) |
18302 | MD->setInvalidDecl(); |
18303 | else |
18304 | DefineDefaultedFunction(*this, MD, DefaultLoc); |
18305 | } |
18306 | } |
18307 | |
18308 | static void SearchForReturnInStmt(Sema &Self, Stmt *S) { |
18309 | for (Stmt *SubStmt : S->children()) { |
18310 | if (!SubStmt) |
18311 | continue; |
18312 | if (isa<ReturnStmt>(SubStmt)) |
18313 | Self.Diag(SubStmt->getBeginLoc(), |
18314 | diag::err_return_in_constructor_handler); |
18315 | if (!isa<Expr>(Val: SubStmt)) |
18316 | SearchForReturnInStmt(Self, S: SubStmt); |
18317 | } |
18318 | } |
18319 | |
18320 | void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { |
18321 | for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { |
18322 | CXXCatchStmt *Handler = TryBlock->getHandler(i: I); |
18323 | SearchForReturnInStmt(Self&: *this, S: Handler); |
18324 | } |
18325 | } |
18326 | |
18327 | void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind, |
18328 | StringLiteral *DeletedMessage) { |
18329 | switch (BodyKind) { |
18330 | case FnBodyKind::Delete: |
18331 | SetDeclDeleted(Dcl: D, DelLoc: Loc, Message: DeletedMessage); |
18332 | break; |
18333 | case FnBodyKind::Default: |
18334 | SetDeclDefaulted(Dcl: D, DefaultLoc: Loc); |
18335 | break; |
18336 | case FnBodyKind::Other: |
18337 | llvm_unreachable( |
18338 | "Parsed function body should be '= delete;' or '= default;'" ); |
18339 | } |
18340 | } |
18341 | |
18342 | bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, |
18343 | const CXXMethodDecl *Old) { |
18344 | const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); |
18345 | const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); |
18346 | |
18347 | if (OldFT->hasExtParameterInfos()) { |
18348 | for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) |
18349 | // A parameter of the overriding method should be annotated with noescape |
18350 | // if the corresponding parameter of the overridden method is annotated. |
18351 | if (OldFT->getExtParameterInfo(I).isNoEscape() && |
18352 | !NewFT->getExtParameterInfo(I).isNoEscape()) { |
18353 | Diag(New->getParamDecl(I)->getLocation(), |
18354 | diag::warn_overriding_method_missing_noescape); |
18355 | Diag(Old->getParamDecl(I)->getLocation(), |
18356 | diag::note_overridden_marked_noescape); |
18357 | } |
18358 | } |
18359 | |
18360 | // SME attributes must match when overriding a function declaration. |
18361 | if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) { |
18362 | Diag(New->getLocation(), diag::err_conflicting_overriding_attributes) |
18363 | << New << New->getType() << Old->getType(); |
18364 | Diag(Old->getLocation(), diag::note_overridden_virtual_function); |
18365 | return true; |
18366 | } |
18367 | |
18368 | // Virtual overrides must have the same code_seg. |
18369 | const auto *OldCSA = Old->getAttr<CodeSegAttr>(); |
18370 | const auto *NewCSA = New->getAttr<CodeSegAttr>(); |
18371 | if ((NewCSA || OldCSA) && |
18372 | (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { |
18373 | Diag(New->getLocation(), diag::err_mismatched_code_seg_override); |
18374 | Diag(Old->getLocation(), diag::note_previous_declaration); |
18375 | return true; |
18376 | } |
18377 | |
18378 | CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); |
18379 | |
18380 | // If the calling conventions match, everything is fine |
18381 | if (NewCC == OldCC) |
18382 | return false; |
18383 | |
18384 | // If the calling conventions mismatch because the new function is static, |
18385 | // suppress the calling convention mismatch error; the error about static |
18386 | // function override (err_static_overrides_virtual from |
18387 | // Sema::CheckFunctionDeclaration) is more clear. |
18388 | if (New->getStorageClass() == SC_Static) |
18389 | return false; |
18390 | |
18391 | Diag(New->getLocation(), |
18392 | diag::err_conflicting_overriding_cc_attributes) |
18393 | << New->getDeclName() << New->getType() << Old->getType(); |
18394 | Diag(Old->getLocation(), diag::note_overridden_virtual_function); |
18395 | return true; |
18396 | } |
18397 | |
18398 | bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New, |
18399 | const CXXMethodDecl *Old) { |
18400 | // CWG2553 |
18401 | // A virtual function shall not be an explicit object member function. |
18402 | if (!New->isExplicitObjectMemberFunction()) |
18403 | return true; |
18404 | Diag(New->getParamDecl(0)->getBeginLoc(), |
18405 | diag::err_explicit_object_parameter_nonmember) |
18406 | << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false; |
18407 | Diag(Old->getLocation(), diag::note_overridden_virtual_function); |
18408 | New->setInvalidDecl(); |
18409 | return false; |
18410 | } |
18411 | |
18412 | bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, |
18413 | const CXXMethodDecl *Old) { |
18414 | QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); |
18415 | QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); |
18416 | |
18417 | if (Context.hasSameType(T1: NewTy, T2: OldTy) || |
18418 | NewTy->isDependentType() || OldTy->isDependentType()) |
18419 | return false; |
18420 | |
18421 | // Check if the return types are covariant |
18422 | QualType NewClassTy, OldClassTy; |
18423 | |
18424 | /// Both types must be pointers or references to classes. |
18425 | if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { |
18426 | if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { |
18427 | NewClassTy = NewPT->getPointeeType(); |
18428 | OldClassTy = OldPT->getPointeeType(); |
18429 | } |
18430 | } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { |
18431 | if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { |
18432 | if (NewRT->getTypeClass() == OldRT->getTypeClass()) { |
18433 | NewClassTy = NewRT->getPointeeType(); |
18434 | OldClassTy = OldRT->getPointeeType(); |
18435 | } |
18436 | } |
18437 | } |
18438 | |
18439 | // The return types aren't either both pointers or references to a class type. |
18440 | if (NewClassTy.isNull()) { |
18441 | Diag(New->getLocation(), |
18442 | diag::err_different_return_type_for_overriding_virtual_function) |
18443 | << New->getDeclName() << NewTy << OldTy |
18444 | << New->getReturnTypeSourceRange(); |
18445 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) |
18446 | << Old->getReturnTypeSourceRange(); |
18447 | |
18448 | return true; |
18449 | } |
18450 | |
18451 | if (!Context.hasSameUnqualifiedType(T1: NewClassTy, T2: OldClassTy)) { |
18452 | // C++14 [class.virtual]p8: |
18453 | // If the class type in the covariant return type of D::f differs from |
18454 | // that of B::f, the class type in the return type of D::f shall be |
18455 | // complete at the point of declaration of D::f or shall be the class |
18456 | // type D. |
18457 | if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { |
18458 | if (!RT->isBeingDefined() && |
18459 | RequireCompleteType(New->getLocation(), NewClassTy, |
18460 | diag::err_covariant_return_incomplete, |
18461 | New->getDeclName())) |
18462 | return true; |
18463 | } |
18464 | |
18465 | // Check if the new class derives from the old class. |
18466 | if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { |
18467 | Diag(New->getLocation(), diag::err_covariant_return_not_derived) |
18468 | << New->getDeclName() << NewTy << OldTy |
18469 | << New->getReturnTypeSourceRange(); |
18470 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) |
18471 | << Old->getReturnTypeSourceRange(); |
18472 | return true; |
18473 | } |
18474 | |
18475 | // Check if we the conversion from derived to base is valid. |
18476 | if (CheckDerivedToBaseConversion( |
18477 | NewClassTy, OldClassTy, |
18478 | diag::err_covariant_return_inaccessible_base, |
18479 | diag::err_covariant_return_ambiguous_derived_to_base_conv, |
18480 | New->getLocation(), New->getReturnTypeSourceRange(), |
18481 | New->getDeclName(), nullptr)) { |
18482 | // FIXME: this note won't trigger for delayed access control |
18483 | // diagnostics, and it's impossible to get an undelayed error |
18484 | // here from access control during the original parse because |
18485 | // the ParsingDeclSpec/ParsingDeclarator are still in scope. |
18486 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) |
18487 | << Old->getReturnTypeSourceRange(); |
18488 | return true; |
18489 | } |
18490 | } |
18491 | |
18492 | // The qualifiers of the return types must be the same. |
18493 | if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { |
18494 | Diag(New->getLocation(), |
18495 | diag::err_covariant_return_type_different_qualifications) |
18496 | << New->getDeclName() << NewTy << OldTy |
18497 | << New->getReturnTypeSourceRange(); |
18498 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) |
18499 | << Old->getReturnTypeSourceRange(); |
18500 | return true; |
18501 | } |
18502 | |
18503 | |
18504 | // The new class type must have the same or less qualifiers as the old type. |
18505 | if (NewClassTy.isMoreQualifiedThan(other: OldClassTy)) { |
18506 | Diag(New->getLocation(), |
18507 | diag::err_covariant_return_type_class_type_more_qualified) |
18508 | << New->getDeclName() << NewTy << OldTy |
18509 | << New->getReturnTypeSourceRange(); |
18510 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) |
18511 | << Old->getReturnTypeSourceRange(); |
18512 | return true; |
18513 | } |
18514 | |
18515 | return false; |
18516 | } |
18517 | |
18518 | /// Mark the given method pure. |
18519 | /// |
18520 | /// \param Method the method to be marked pure. |
18521 | /// |
18522 | /// \param InitRange the source range that covers the "0" initializer. |
18523 | bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { |
18524 | SourceLocation EndLoc = InitRange.getEnd(); |
18525 | if (EndLoc.isValid()) |
18526 | Method->setRangeEnd(EndLoc); |
18527 | |
18528 | if (Method->isVirtual() || Method->getParent()->isDependentContext()) { |
18529 | Method->setIsPureVirtual(); |
18530 | return false; |
18531 | } |
18532 | |
18533 | if (!Method->isInvalidDecl()) |
18534 | Diag(Method->getLocation(), diag::err_non_virtual_pure) |
18535 | << Method->getDeclName() << InitRange; |
18536 | return true; |
18537 | } |
18538 | |
18539 | void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { |
18540 | if (D->getFriendObjectKind()) |
18541 | Diag(D->getLocation(), diag::err_pure_friend); |
18542 | else if (auto *M = dyn_cast<CXXMethodDecl>(Val: D)) |
18543 | CheckPureMethod(Method: M, InitRange: ZeroLoc); |
18544 | else |
18545 | Diag(D->getLocation(), diag::err_illegal_initializer); |
18546 | } |
18547 | |
18548 | /// Determine whether the given declaration is a global variable or |
18549 | /// static data member. |
18550 | static bool isNonlocalVariable(const Decl *D) { |
18551 | if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(Val: D)) |
18552 | return Var->hasGlobalStorage(); |
18553 | |
18554 | return false; |
18555 | } |
18556 | |
18557 | /// Invoked when we are about to parse an initializer for the declaration |
18558 | /// 'Dcl'. |
18559 | /// |
18560 | /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a |
18561 | /// static data member of class X, names should be looked up in the scope of |
18562 | /// class X. If the declaration had a scope specifier, a scope will have |
18563 | /// been created and passed in for this purpose. Otherwise, S will be null. |
18564 | void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { |
18565 | // If there is no declaration, there was an error parsing it. |
18566 | if (!D || D->isInvalidDecl()) |
18567 | return; |
18568 | |
18569 | // We will always have a nested name specifier here, but this declaration |
18570 | // might not be out of line if the specifier names the current namespace: |
18571 | // extern int n; |
18572 | // int ::n = 0; |
18573 | if (S && D->isOutOfLine()) |
18574 | EnterDeclaratorContext(S, DC: D->getDeclContext()); |
18575 | |
18576 | // If we are parsing the initializer for a static data member, push a |
18577 | // new expression evaluation context that is associated with this static |
18578 | // data member. |
18579 | if (isNonlocalVariable(D)) |
18580 | PushExpressionEvaluationContext( |
18581 | NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, LambdaContextDecl: D); |
18582 | } |
18583 | |
18584 | /// Invoked after we are finished parsing an initializer for the declaration D. |
18585 | void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { |
18586 | // If there is no declaration, there was an error parsing it. |
18587 | if (!D || D->isInvalidDecl()) |
18588 | return; |
18589 | |
18590 | if (isNonlocalVariable(D)) |
18591 | PopExpressionEvaluationContext(); |
18592 | |
18593 | if (S && D->isOutOfLine()) |
18594 | ExitDeclaratorContext(S); |
18595 | } |
18596 | |
18597 | /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a |
18598 | /// C++ if/switch/while/for statement. |
18599 | /// e.g: "if (int x = f()) {...}" |
18600 | DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { |
18601 | // C++ 6.4p2: |
18602 | // The declarator shall not specify a function or an array. |
18603 | // The type-specifier-seq shall not contain typedef and shall not declare a |
18604 | // new class or enumeration. |
18605 | assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && |
18606 | "Parser allowed 'typedef' as storage class of condition decl." ); |
18607 | |
18608 | Decl *Dcl = ActOnDeclarator(S, D); |
18609 | if (!Dcl) |
18610 | return true; |
18611 | |
18612 | if (isa<FunctionDecl>(Val: Dcl)) { // The declarator shall not specify a function. |
18613 | Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) |
18614 | << D.getSourceRange(); |
18615 | return true; |
18616 | } |
18617 | |
18618 | if (auto *VD = dyn_cast<VarDecl>(Val: Dcl)) |
18619 | VD->setCXXCondDecl(); |
18620 | |
18621 | return Dcl; |
18622 | } |
18623 | |
18624 | void Sema::LoadExternalVTableUses() { |
18625 | if (!ExternalSource) |
18626 | return; |
18627 | |
18628 | SmallVector<ExternalVTableUse, 4> VTables; |
18629 | ExternalSource->ReadUsedVTables(VTables); |
18630 | SmallVector<VTableUse, 4> NewUses; |
18631 | for (unsigned I = 0, N = VTables.size(); I != N; ++I) { |
18632 | llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos |
18633 | = VTablesUsed.find(Val: VTables[I].Record); |
18634 | // Even if a definition wasn't required before, it may be required now. |
18635 | if (Pos != VTablesUsed.end()) { |
18636 | if (!Pos->second && VTables[I].DefinitionRequired) |
18637 | Pos->second = true; |
18638 | continue; |
18639 | } |
18640 | |
18641 | VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; |
18642 | NewUses.push_back(Elt: VTableUse(VTables[I].Record, VTables[I].Location)); |
18643 | } |
18644 | |
18645 | VTableUses.insert(I: VTableUses.begin(), From: NewUses.begin(), To: NewUses.end()); |
18646 | } |
18647 | |
18648 | void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, |
18649 | bool DefinitionRequired) { |
18650 | // Ignore any vtable uses in unevaluated operands or for classes that do |
18651 | // not have a vtable. |
18652 | if (!Class->isDynamicClass() || Class->isDependentContext() || |
18653 | CurContext->isDependentContext() || isUnevaluatedContext()) |
18654 | return; |
18655 | // Do not mark as used if compiling for the device outside of the target |
18656 | // region. |
18657 | if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice && |
18658 | !OpenMP().isInOpenMPDeclareTargetContext() && |
18659 | !OpenMP().isInOpenMPTargetExecutionDirective()) { |
18660 | if (!DefinitionRequired) |
18661 | MarkVirtualMembersReferenced(Loc, RD: Class); |
18662 | return; |
18663 | } |
18664 | |
18665 | // Try to insert this class into the map. |
18666 | LoadExternalVTableUses(); |
18667 | Class = Class->getCanonicalDecl(); |
18668 | std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> |
18669 | Pos = VTablesUsed.insert(KV: std::make_pair(x&: Class, y&: DefinitionRequired)); |
18670 | if (!Pos.second) { |
18671 | // If we already had an entry, check to see if we are promoting this vtable |
18672 | // to require a definition. If so, we need to reappend to the VTableUses |
18673 | // list, since we may have already processed the first entry. |
18674 | if (DefinitionRequired && !Pos.first->second) { |
18675 | Pos.first->second = true; |
18676 | } else { |
18677 | // Otherwise, we can early exit. |
18678 | return; |
18679 | } |
18680 | } else { |
18681 | // The Microsoft ABI requires that we perform the destructor body |
18682 | // checks (i.e. operator delete() lookup) when the vtable is marked used, as |
18683 | // the deleting destructor is emitted with the vtable, not with the |
18684 | // destructor definition as in the Itanium ABI. |
18685 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
18686 | CXXDestructorDecl *DD = Class->getDestructor(); |
18687 | if (DD && DD->isVirtual() && !DD->isDeleted()) { |
18688 | if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { |
18689 | // If this is an out-of-line declaration, marking it referenced will |
18690 | // not do anything. Manually call CheckDestructor to look up operator |
18691 | // delete(). |
18692 | ContextRAII SavedContext(*this, DD); |
18693 | CheckDestructor(Destructor: DD); |
18694 | } else { |
18695 | MarkFunctionReferenced(Loc, Class->getDestructor()); |
18696 | } |
18697 | } |
18698 | } |
18699 | } |
18700 | |
18701 | // Local classes need to have their virtual members marked |
18702 | // immediately. For all other classes, we mark their virtual members |
18703 | // at the end of the translation unit. |
18704 | if (Class->isLocalClass()) |
18705 | MarkVirtualMembersReferenced(Loc, RD: Class->getDefinition()); |
18706 | else |
18707 | VTableUses.push_back(Elt: std::make_pair(x&: Class, y&: Loc)); |
18708 | } |
18709 | |
18710 | bool Sema::DefineUsedVTables() { |
18711 | LoadExternalVTableUses(); |
18712 | if (VTableUses.empty()) |
18713 | return false; |
18714 | |
18715 | // Note: The VTableUses vector could grow as a result of marking |
18716 | // the members of a class as "used", so we check the size each |
18717 | // time through the loop and prefer indices (which are stable) to |
18718 | // iterators (which are not). |
18719 | bool DefinedAnything = false; |
18720 | for (unsigned I = 0; I != VTableUses.size(); ++I) { |
18721 | CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); |
18722 | if (!Class) |
18723 | continue; |
18724 | TemplateSpecializationKind ClassTSK = |
18725 | Class->getTemplateSpecializationKind(); |
18726 | |
18727 | SourceLocation Loc = VTableUses[I].second; |
18728 | |
18729 | bool DefineVTable = true; |
18730 | |
18731 | // If this class has a key function, but that key function is |
18732 | // defined in another translation unit, we don't need to emit the |
18733 | // vtable even though we're using it. |
18734 | const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(RD: Class); |
18735 | if (KeyFunction && !KeyFunction->hasBody()) { |
18736 | // The key function is in another translation unit. |
18737 | DefineVTable = false; |
18738 | TemplateSpecializationKind TSK = |
18739 | KeyFunction->getTemplateSpecializationKind(); |
18740 | assert(TSK != TSK_ExplicitInstantiationDefinition && |
18741 | TSK != TSK_ImplicitInstantiation && |
18742 | "Instantiations don't have key functions" ); |
18743 | (void)TSK; |
18744 | } else if (!KeyFunction) { |
18745 | // If we have a class with no key function that is the subject |
18746 | // of an explicit instantiation declaration, suppress the |
18747 | // vtable; it will live with the explicit instantiation |
18748 | // definition. |
18749 | bool IsExplicitInstantiationDeclaration = |
18750 | ClassTSK == TSK_ExplicitInstantiationDeclaration; |
18751 | for (auto *R : Class->redecls()) { |
18752 | TemplateSpecializationKind TSK |
18753 | = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); |
18754 | if (TSK == TSK_ExplicitInstantiationDeclaration) |
18755 | IsExplicitInstantiationDeclaration = true; |
18756 | else if (TSK == TSK_ExplicitInstantiationDefinition) { |
18757 | IsExplicitInstantiationDeclaration = false; |
18758 | break; |
18759 | } |
18760 | } |
18761 | |
18762 | if (IsExplicitInstantiationDeclaration) |
18763 | DefineVTable = false; |
18764 | } |
18765 | |
18766 | // The exception specifications for all virtual members may be needed even |
18767 | // if we are not providing an authoritative form of the vtable in this TU. |
18768 | // We may choose to emit it available_externally anyway. |
18769 | if (!DefineVTable) { |
18770 | MarkVirtualMemberExceptionSpecsNeeded(Loc, RD: Class); |
18771 | continue; |
18772 | } |
18773 | |
18774 | // Mark all of the virtual members of this class as referenced, so |
18775 | // that we can build a vtable. Then, tell the AST consumer that a |
18776 | // vtable for this class is required. |
18777 | DefinedAnything = true; |
18778 | MarkVirtualMembersReferenced(Loc, RD: Class); |
18779 | CXXRecordDecl *Canonical = Class->getCanonicalDecl(); |
18780 | if (VTablesUsed[Canonical]) |
18781 | Consumer.HandleVTable(RD: Class); |
18782 | |
18783 | // Warn if we're emitting a weak vtable. The vtable will be weak if there is |
18784 | // no key function or the key function is inlined. Don't warn in C++ ABIs |
18785 | // that lack key functions, since the user won't be able to make one. |
18786 | if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && |
18787 | Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation && |
18788 | ClassTSK != TSK_ExplicitInstantiationDefinition) { |
18789 | const FunctionDecl *KeyFunctionDef = nullptr; |
18790 | if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && |
18791 | KeyFunctionDef->isInlined())) |
18792 | Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; |
18793 | } |
18794 | } |
18795 | VTableUses.clear(); |
18796 | |
18797 | return DefinedAnything; |
18798 | } |
18799 | |
18800 | void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, |
18801 | const CXXRecordDecl *RD) { |
18802 | for (const auto *I : RD->methods()) |
18803 | if (I->isVirtual() && !I->isPureVirtual()) |
18804 | ResolveExceptionSpec(Loc, FPT: I->getType()->castAs<FunctionProtoType>()); |
18805 | } |
18806 | |
18807 | void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, |
18808 | const CXXRecordDecl *RD, |
18809 | bool ConstexprOnly) { |
18810 | // Mark all functions which will appear in RD's vtable as used. |
18811 | CXXFinalOverriderMap FinalOverriders; |
18812 | RD->getFinalOverriders(FinaOverriders&: FinalOverriders); |
18813 | for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), |
18814 | E = FinalOverriders.end(); |
18815 | I != E; ++I) { |
18816 | for (OverridingMethods::const_iterator OI = I->second.begin(), |
18817 | OE = I->second.end(); |
18818 | OI != OE; ++OI) { |
18819 | assert(OI->second.size() > 0 && "no final overrider" ); |
18820 | CXXMethodDecl *Overrider = OI->second.front().Method; |
18821 | |
18822 | // C++ [basic.def.odr]p2: |
18823 | // [...] A virtual member function is used if it is not pure. [...] |
18824 | if (!Overrider->isPureVirtual() && |
18825 | (!ConstexprOnly || Overrider->isConstexpr())) |
18826 | MarkFunctionReferenced(Loc, Overrider); |
18827 | } |
18828 | } |
18829 | |
18830 | // Only classes that have virtual bases need a VTT. |
18831 | if (RD->getNumVBases() == 0) |
18832 | return; |
18833 | |
18834 | for (const auto &I : RD->bases()) { |
18835 | const auto *Base = |
18836 | cast<CXXRecordDecl>(Val: I.getType()->castAs<RecordType>()->getDecl()); |
18837 | if (Base->getNumVBases() == 0) |
18838 | continue; |
18839 | MarkVirtualMembersReferenced(Loc, RD: Base); |
18840 | } |
18841 | } |
18842 | |
18843 | /// SetIvarInitializers - This routine builds initialization ASTs for the |
18844 | /// Objective-C implementation whose ivars need be initialized. |
18845 | void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { |
18846 | if (!getLangOpts().CPlusPlus) |
18847 | return; |
18848 | if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { |
18849 | SmallVector<ObjCIvarDecl*, 8> ivars; |
18850 | CollectIvarsToConstructOrDestruct(OI: OID, Ivars&: ivars); |
18851 | if (ivars.empty()) |
18852 | return; |
18853 | SmallVector<CXXCtorInitializer*, 32> AllToInit; |
18854 | for (unsigned i = 0; i < ivars.size(); i++) { |
18855 | FieldDecl *Field = ivars[i]; |
18856 | if (Field->isInvalidDecl()) |
18857 | continue; |
18858 | |
18859 | CXXCtorInitializer *Member; |
18860 | InitializedEntity InitEntity = InitializedEntity::InitializeMember(Member: Field); |
18861 | InitializationKind InitKind = |
18862 | InitializationKind::CreateDefault(InitLoc: ObjCImplementation->getLocation()); |
18863 | |
18864 | InitializationSequence InitSeq(*this, InitEntity, InitKind, std::nullopt); |
18865 | ExprResult MemberInit = |
18866 | InitSeq.Perform(S&: *this, Entity: InitEntity, Kind: InitKind, Args: std::nullopt); |
18867 | MemberInit = MaybeCreateExprWithCleanups(SubExpr: MemberInit); |
18868 | // Note, MemberInit could actually come back empty if no initialization |
18869 | // is required (e.g., because it would call a trivial default constructor) |
18870 | if (!MemberInit.get() || MemberInit.isInvalid()) |
18871 | continue; |
18872 | |
18873 | Member = |
18874 | new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), |
18875 | SourceLocation(), |
18876 | MemberInit.getAs<Expr>(), |
18877 | SourceLocation()); |
18878 | AllToInit.push_back(Elt: Member); |
18879 | |
18880 | // Be sure that the destructor is accessible and is marked as referenced. |
18881 | if (const RecordType *RecordTy = |
18882 | Context.getBaseElementType(Field->getType()) |
18883 | ->getAs<RecordType>()) { |
18884 | CXXRecordDecl *RD = cast<CXXRecordDecl>(Val: RecordTy->getDecl()); |
18885 | if (CXXDestructorDecl *Destructor = LookupDestructor(Class: RD)) { |
18886 | MarkFunctionReferenced(Loc: Field->getLocation(), Func: Destructor); |
18887 | CheckDestructorAccess(Field->getLocation(), Destructor, |
18888 | PDiag(diag::err_access_dtor_ivar) |
18889 | << Context.getBaseElementType(Field->getType())); |
18890 | } |
18891 | } |
18892 | } |
18893 | ObjCImplementation->setIvarInitializers(C&: Context, |
18894 | initializers: AllToInit.data(), numInitializers: AllToInit.size()); |
18895 | } |
18896 | } |
18897 | |
18898 | static |
18899 | void DelegatingCycleHelper(CXXConstructorDecl* Ctor, |
18900 | llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, |
18901 | llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, |
18902 | llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, |
18903 | Sema &S) { |
18904 | if (Ctor->isInvalidDecl()) |
18905 | return; |
18906 | |
18907 | CXXConstructorDecl *Target = Ctor->getTargetConstructor(); |
18908 | |
18909 | // Target may not be determinable yet, for instance if this is a dependent |
18910 | // call in an uninstantiated template. |
18911 | if (Target) { |
18912 | const FunctionDecl *FNTarget = nullptr; |
18913 | (void)Target->hasBody(FNTarget); |
18914 | Target = const_cast<CXXConstructorDecl*>( |
18915 | cast_or_null<CXXConstructorDecl>(Val: FNTarget)); |
18916 | } |
18917 | |
18918 | CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), |
18919 | // Avoid dereferencing a null pointer here. |
18920 | *TCanonical = Target? Target->getCanonicalDecl() : nullptr; |
18921 | |
18922 | if (!Current.insert(Ptr: Canonical).second) |
18923 | return; |
18924 | |
18925 | // We know that beyond here, we aren't chaining into a cycle. |
18926 | if (!Target || !Target->isDelegatingConstructor() || |
18927 | Target->isInvalidDecl() || Valid.count(Ptr: TCanonical)) { |
18928 | Valid.insert(I: Current.begin(), E: Current.end()); |
18929 | Current.clear(); |
18930 | // We've hit a cycle. |
18931 | } else if (TCanonical == Canonical || Invalid.count(Ptr: TCanonical) || |
18932 | Current.count(Ptr: TCanonical)) { |
18933 | // If we haven't diagnosed this cycle yet, do so now. |
18934 | if (!Invalid.count(Ptr: TCanonical)) { |
18935 | S.Diag((*Ctor->init_begin())->getSourceLocation(), |
18936 | diag::warn_delegating_ctor_cycle) |
18937 | << Ctor; |
18938 | |
18939 | // Don't add a note for a function delegating directly to itself. |
18940 | if (TCanonical != Canonical) |
18941 | S.Diag(Target->getLocation(), diag::note_it_delegates_to); |
18942 | |
18943 | CXXConstructorDecl *C = Target; |
18944 | while (C->getCanonicalDecl() != Canonical) { |
18945 | const FunctionDecl *FNTarget = nullptr; |
18946 | (void)C->getTargetConstructor()->hasBody(FNTarget); |
18947 | assert(FNTarget && "Ctor cycle through bodiless function" ); |
18948 | |
18949 | C = const_cast<CXXConstructorDecl*>( |
18950 | cast<CXXConstructorDecl>(Val: FNTarget)); |
18951 | S.Diag(C->getLocation(), diag::note_which_delegates_to); |
18952 | } |
18953 | } |
18954 | |
18955 | Invalid.insert(I: Current.begin(), E: Current.end()); |
18956 | Current.clear(); |
18957 | } else { |
18958 | DelegatingCycleHelper(Ctor: Target, Valid, Invalid, Current, S); |
18959 | } |
18960 | } |
18961 | |
18962 | |
18963 | void Sema::CheckDelegatingCtorCycles() { |
18964 | llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; |
18965 | |
18966 | for (DelegatingCtorDeclsType::iterator |
18967 | I = DelegatingCtorDecls.begin(source: ExternalSource.get()), |
18968 | E = DelegatingCtorDecls.end(); |
18969 | I != E; ++I) |
18970 | DelegatingCycleHelper(Ctor: *I, Valid, Invalid, Current, S&: *this); |
18971 | |
18972 | for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) |
18973 | (*CI)->setInvalidDecl(); |
18974 | } |
18975 | |
18976 | namespace { |
18977 | /// AST visitor that finds references to the 'this' expression. |
18978 | class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { |
18979 | Sema &S; |
18980 | |
18981 | public: |
18982 | explicit FindCXXThisExpr(Sema &S) : S(S) { } |
18983 | |
18984 | bool VisitCXXThisExpr(CXXThisExpr *E) { |
18985 | S.Diag(E->getLocation(), diag::err_this_static_member_func) |
18986 | << E->isImplicit(); |
18987 | return false; |
18988 | } |
18989 | }; |
18990 | } |
18991 | |
18992 | bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { |
18993 | TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); |
18994 | if (!TSInfo) |
18995 | return false; |
18996 | |
18997 | TypeLoc TL = TSInfo->getTypeLoc(); |
18998 | FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); |
18999 | if (!ProtoTL) |
19000 | return false; |
19001 | |
19002 | // C++11 [expr.prim.general]p3: |
19003 | // [The expression this] shall not appear before the optional |
19004 | // cv-qualifier-seq and it shall not appear within the declaration of a |
19005 | // static member function (although its type and value category are defined |
19006 | // within a static member function as they are within a non-static member |
19007 | // function). [ Note: this is because declaration matching does not occur |
19008 | // until the complete declarator is known. - end note ] |
19009 | const FunctionProtoType *Proto = ProtoTL.getTypePtr(); |
19010 | FindCXXThisExpr Finder(*this); |
19011 | |
19012 | // If the return type came after the cv-qualifier-seq, check it now. |
19013 | if (Proto->hasTrailingReturn() && |
19014 | !Finder.TraverseTypeLoc(TL: ProtoTL.getReturnLoc())) |
19015 | return true; |
19016 | |
19017 | // Check the exception specification. |
19018 | if (checkThisInStaticMemberFunctionExceptionSpec(Method)) |
19019 | return true; |
19020 | |
19021 | // Check the trailing requires clause |
19022 | if (Expr *E = Method->getTrailingRequiresClause()) |
19023 | if (!Finder.TraverseStmt(E)) |
19024 | return true; |
19025 | |
19026 | return checkThisInStaticMemberFunctionAttributes(Method); |
19027 | } |
19028 | |
19029 | bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { |
19030 | TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); |
19031 | if (!TSInfo) |
19032 | return false; |
19033 | |
19034 | TypeLoc TL = TSInfo->getTypeLoc(); |
19035 | FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); |
19036 | if (!ProtoTL) |
19037 | return false; |
19038 | |
19039 | const FunctionProtoType *Proto = ProtoTL.getTypePtr(); |
19040 | FindCXXThisExpr Finder(*this); |
19041 | |
19042 | switch (Proto->getExceptionSpecType()) { |
19043 | case EST_Unparsed: |
19044 | case EST_Uninstantiated: |
19045 | case EST_Unevaluated: |
19046 | case EST_BasicNoexcept: |
19047 | case EST_NoThrow: |
19048 | case EST_DynamicNone: |
19049 | case EST_MSAny: |
19050 | case EST_None: |
19051 | break; |
19052 | |
19053 | case EST_DependentNoexcept: |
19054 | case EST_NoexceptFalse: |
19055 | case EST_NoexceptTrue: |
19056 | if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) |
19057 | return true; |
19058 | [[fallthrough]]; |
19059 | |
19060 | case EST_Dynamic: |
19061 | for (const auto &E : Proto->exceptions()) { |
19062 | if (!Finder.TraverseType(E)) |
19063 | return true; |
19064 | } |
19065 | break; |
19066 | } |
19067 | |
19068 | return false; |
19069 | } |
19070 | |
19071 | bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { |
19072 | FindCXXThisExpr Finder(*this); |
19073 | |
19074 | // Check attributes. |
19075 | for (const auto *A : Method->attrs()) { |
19076 | // FIXME: This should be emitted by tblgen. |
19077 | Expr *Arg = nullptr; |
19078 | ArrayRef<Expr *> Args; |
19079 | if (const auto *G = dyn_cast<GuardedByAttr>(A)) |
19080 | Arg = G->getArg(); |
19081 | else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) |
19082 | Arg = G->getArg(); |
19083 | else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) |
19084 | Args = llvm::ArrayRef(AA->args_begin(), AA->args_size()); |
19085 | else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) |
19086 | Args = llvm::ArrayRef(AB->args_begin(), AB->args_size()); |
19087 | else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { |
19088 | Arg = ETLF->getSuccessValue(); |
19089 | Args = llvm::ArrayRef(ETLF->args_begin(), ETLF->args_size()); |
19090 | } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { |
19091 | Arg = STLF->getSuccessValue(); |
19092 | Args = llvm::ArrayRef(STLF->args_begin(), STLF->args_size()); |
19093 | } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) |
19094 | Arg = LR->getArg(); |
19095 | else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) |
19096 | Args = llvm::ArrayRef(LE->args_begin(), LE->args_size()); |
19097 | else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) |
19098 | Args = llvm::ArrayRef(RC->args_begin(), RC->args_size()); |
19099 | else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) |
19100 | Args = llvm::ArrayRef(AC->args_begin(), AC->args_size()); |
19101 | else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) |
19102 | Args = llvm::ArrayRef(AC->args_begin(), AC->args_size()); |
19103 | else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) |
19104 | Args = llvm::ArrayRef(RC->args_begin(), RC->args_size()); |
19105 | |
19106 | if (Arg && !Finder.TraverseStmt(Arg)) |
19107 | return true; |
19108 | |
19109 | for (unsigned I = 0, N = Args.size(); I != N; ++I) { |
19110 | if (!Finder.TraverseStmt(Args[I])) |
19111 | return true; |
19112 | } |
19113 | } |
19114 | |
19115 | return false; |
19116 | } |
19117 | |
19118 | void Sema::checkExceptionSpecification( |
19119 | bool IsTopLevel, ExceptionSpecificationType EST, |
19120 | ArrayRef<ParsedType> DynamicExceptions, |
19121 | ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, |
19122 | SmallVectorImpl<QualType> &Exceptions, |
19123 | FunctionProtoType::ExceptionSpecInfo &ESI) { |
19124 | Exceptions.clear(); |
19125 | ESI.Type = EST; |
19126 | if (EST == EST_Dynamic) { |
19127 | Exceptions.reserve(N: DynamicExceptions.size()); |
19128 | for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { |
19129 | // FIXME: Preserve type source info. |
19130 | QualType ET = GetTypeFromParser(Ty: DynamicExceptions[ei]); |
19131 | |
19132 | if (IsTopLevel) { |
19133 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
19134 | collectUnexpandedParameterPacks(T: ET, Unexpanded); |
19135 | if (!Unexpanded.empty()) { |
19136 | DiagnoseUnexpandedParameterPacks( |
19137 | Loc: DynamicExceptionRanges[ei].getBegin(), UPPC: UPPC_ExceptionType, |
19138 | Unexpanded); |
19139 | continue; |
19140 | } |
19141 | } |
19142 | |
19143 | // Check that the type is valid for an exception spec, and |
19144 | // drop it if not. |
19145 | if (!CheckSpecifiedExceptionType(T&: ET, Range: DynamicExceptionRanges[ei])) |
19146 | Exceptions.push_back(Elt: ET); |
19147 | } |
19148 | ESI.Exceptions = Exceptions; |
19149 | return; |
19150 | } |
19151 | |
19152 | if (isComputedNoexcept(ESpecType: EST)) { |
19153 | assert((NoexceptExpr->isTypeDependent() || |
19154 | NoexceptExpr->getType()->getCanonicalTypeUnqualified() == |
19155 | Context.BoolTy) && |
19156 | "Parser should have made sure that the expression is boolean" ); |
19157 | if (IsTopLevel && DiagnoseUnexpandedParameterPack(E: NoexceptExpr)) { |
19158 | ESI.Type = EST_BasicNoexcept; |
19159 | return; |
19160 | } |
19161 | |
19162 | ESI.NoexceptExpr = NoexceptExpr; |
19163 | return; |
19164 | } |
19165 | } |
19166 | |
19167 | void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, |
19168 | ExceptionSpecificationType EST, |
19169 | SourceRange SpecificationRange, |
19170 | ArrayRef<ParsedType> DynamicExceptions, |
19171 | ArrayRef<SourceRange> DynamicExceptionRanges, |
19172 | Expr *NoexceptExpr) { |
19173 | if (!MethodD) |
19174 | return; |
19175 | |
19176 | // Dig out the method we're referring to. |
19177 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: MethodD)) |
19178 | MethodD = FunTmpl->getTemplatedDecl(); |
19179 | |
19180 | CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: MethodD); |
19181 | if (!Method) |
19182 | return; |
19183 | |
19184 | // Check the exception specification. |
19185 | llvm::SmallVector<QualType, 4> Exceptions; |
19186 | FunctionProtoType::ExceptionSpecInfo ESI; |
19187 | checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, |
19188 | DynamicExceptionRanges, NoexceptExpr, Exceptions, |
19189 | ESI); |
19190 | |
19191 | // Update the exception specification on the function type. |
19192 | Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); |
19193 | |
19194 | if (Method->isStatic()) |
19195 | checkThisInStaticMemberFunctionExceptionSpec(Method); |
19196 | |
19197 | if (Method->isVirtual()) { |
19198 | // Check overrides, which we previously had to delay. |
19199 | for (const CXXMethodDecl *O : Method->overridden_methods()) |
19200 | CheckOverridingFunctionExceptionSpec(New: Method, Old: O); |
19201 | } |
19202 | } |
19203 | |
19204 | /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. |
19205 | /// |
19206 | MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, |
19207 | SourceLocation DeclStart, Declarator &D, |
19208 | Expr *BitWidth, |
19209 | InClassInitStyle InitStyle, |
19210 | AccessSpecifier AS, |
19211 | const ParsedAttr &MSPropertyAttr) { |
19212 | const IdentifierInfo *II = D.getIdentifier(); |
19213 | if (!II) { |
19214 | Diag(DeclStart, diag::err_anonymous_property); |
19215 | return nullptr; |
19216 | } |
19217 | SourceLocation Loc = D.getIdentifierLoc(); |
19218 | |
19219 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D); |
19220 | QualType T = TInfo->getType(); |
19221 | if (getLangOpts().CPlusPlus) { |
19222 | CheckExtraCXXDefaultArguments(D); |
19223 | |
19224 | if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo, |
19225 | UPPC: UPPC_DataMemberType)) { |
19226 | D.setInvalidType(); |
19227 | T = Context.IntTy; |
19228 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc); |
19229 | } |
19230 | } |
19231 | |
19232 | DiagnoseFunctionSpecifiers(DS: D.getDeclSpec()); |
19233 | |
19234 | if (D.getDeclSpec().isInlineSpecified()) |
19235 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) |
19236 | << getLangOpts().CPlusPlus17; |
19237 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) |
19238 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), |
19239 | diag::err_invalid_thread) |
19240 | << DeclSpec::getSpecifierName(TSCS); |
19241 | |
19242 | // Check to see if this name was declared as a member previously |
19243 | NamedDecl *PrevDecl = nullptr; |
19244 | LookupResult Previous(*this, II, Loc, LookupMemberName, |
19245 | RedeclarationKind::ForVisibleRedeclaration); |
19246 | LookupName(R&: Previous, S); |
19247 | switch (Previous.getResultKind()) { |
19248 | case LookupResult::Found: |
19249 | case LookupResult::FoundUnresolvedValue: |
19250 | PrevDecl = Previous.getAsSingle<NamedDecl>(); |
19251 | break; |
19252 | |
19253 | case LookupResult::FoundOverloaded: |
19254 | PrevDecl = Previous.getRepresentativeDecl(); |
19255 | break; |
19256 | |
19257 | case LookupResult::NotFound: |
19258 | case LookupResult::NotFoundInCurrentInstantiation: |
19259 | case LookupResult::Ambiguous: |
19260 | break; |
19261 | } |
19262 | |
19263 | if (PrevDecl && PrevDecl->isTemplateParameter()) { |
19264 | // Maybe we will complain about the shadowed template parameter. |
19265 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); |
19266 | // Just pretend that we didn't see the previous declaration. |
19267 | PrevDecl = nullptr; |
19268 | } |
19269 | |
19270 | if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) |
19271 | PrevDecl = nullptr; |
19272 | |
19273 | SourceLocation TSSL = D.getBeginLoc(); |
19274 | MSPropertyDecl *NewPD = |
19275 | MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, |
19276 | MSPropertyAttr.getPropertyDataGetter(), |
19277 | MSPropertyAttr.getPropertyDataSetter()); |
19278 | ProcessDeclAttributes(TUScope, NewPD, D); |
19279 | NewPD->setAccess(AS); |
19280 | |
19281 | if (NewPD->isInvalidDecl()) |
19282 | Record->setInvalidDecl(); |
19283 | |
19284 | if (D.getDeclSpec().isModulePrivateSpecified()) |
19285 | NewPD->setModulePrivate(); |
19286 | |
19287 | if (NewPD->isInvalidDecl() && PrevDecl) { |
19288 | // Don't introduce NewFD into scope; there's already something |
19289 | // with the same name in the same scope. |
19290 | } else if (II) { |
19291 | PushOnScopeChains(NewPD, S); |
19292 | } else |
19293 | Record->addDecl(NewPD); |
19294 | |
19295 | return NewPD; |
19296 | } |
19297 | |
19298 | void Sema::ActOnStartFunctionDeclarationDeclarator( |
19299 | Declarator &Declarator, unsigned TemplateParameterDepth) { |
19300 | auto &Info = InventedParameterInfos.emplace_back(); |
19301 | TemplateParameterList *ExplicitParams = nullptr; |
19302 | ArrayRef<TemplateParameterList *> ExplicitLists = |
19303 | Declarator.getTemplateParameterLists(); |
19304 | if (!ExplicitLists.empty()) { |
19305 | bool IsMemberSpecialization, IsInvalid; |
19306 | ExplicitParams = MatchTemplateParametersToScopeSpecifier( |
19307 | DeclStartLoc: Declarator.getBeginLoc(), DeclLoc: Declarator.getIdentifierLoc(), |
19308 | SS: Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, |
19309 | ParamLists: ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, Invalid&: IsInvalid, |
19310 | /*SuppressDiagnostic=*/true); |
19311 | } |
19312 | // C++23 [dcl.fct]p23: |
19313 | // An abbreviated function template can have a template-head. The invented |
19314 | // template-parameters are appended to the template-parameter-list after |
19315 | // the explicitly declared template-parameters. |
19316 | // |
19317 | // A template-head must have one or more template-parameters (read: |
19318 | // 'template<>' is *not* a template-head). Only append the invented |
19319 | // template parameters if we matched the nested-name-specifier to a non-empty |
19320 | // TemplateParameterList. |
19321 | if (ExplicitParams && !ExplicitParams->empty()) { |
19322 | Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); |
19323 | llvm::append_range(C&: Info.TemplateParams, R&: *ExplicitParams); |
19324 | Info.NumExplicitTemplateParams = ExplicitParams->size(); |
19325 | } else { |
19326 | Info.AutoTemplateParameterDepth = TemplateParameterDepth; |
19327 | Info.NumExplicitTemplateParams = 0; |
19328 | } |
19329 | } |
19330 | |
19331 | void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { |
19332 | auto &FSI = InventedParameterInfos.back(); |
19333 | if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { |
19334 | if (FSI.NumExplicitTemplateParams != 0) { |
19335 | TemplateParameterList *ExplicitParams = |
19336 | Declarator.getTemplateParameterLists().back(); |
19337 | Declarator.setInventedTemplateParameterList( |
19338 | TemplateParameterList::Create( |
19339 | C: Context, TemplateLoc: ExplicitParams->getTemplateLoc(), |
19340 | LAngleLoc: ExplicitParams->getLAngleLoc(), Params: FSI.TemplateParams, |
19341 | RAngleLoc: ExplicitParams->getRAngleLoc(), |
19342 | RequiresClause: ExplicitParams->getRequiresClause())); |
19343 | } else { |
19344 | Declarator.setInventedTemplateParameterList( |
19345 | TemplateParameterList::Create( |
19346 | C: Context, TemplateLoc: SourceLocation(), LAngleLoc: SourceLocation(), Params: FSI.TemplateParams, |
19347 | RAngleLoc: SourceLocation(), /*RequiresClause=*/nullptr)); |
19348 | } |
19349 | } |
19350 | InventedParameterInfos.pop_back(); |
19351 | } |
19352 | |