File: | clang/lib/Sema/SemaDeclCXX.cpp |
Warning: | line 10031, column 41 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// | ||||
2 | // | ||||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||||
4 | // See https://llvm.org/LICENSE.txt for license information. | ||||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||||
6 | // | ||||
7 | //===----------------------------------------------------------------------===// | ||||
8 | // | ||||
9 | // This file implements semantic analysis for C++ declarations. | ||||
10 | // | ||||
11 | //===----------------------------------------------------------------------===// | ||||
12 | |||||
13 | #include "clang/AST/ASTConsumer.h" | ||||
14 | #include "clang/AST/ASTContext.h" | ||||
15 | #include "clang/AST/ASTLambda.h" | ||||
16 | #include "clang/AST/ASTMutationListener.h" | ||||
17 | #include "clang/AST/CXXInheritance.h" | ||||
18 | #include "clang/AST/CharUnits.h" | ||||
19 | #include "clang/AST/ComparisonCategories.h" | ||||
20 | #include "clang/AST/EvaluatedExprVisitor.h" | ||||
21 | #include "clang/AST/ExprCXX.h" | ||||
22 | #include "clang/AST/RecordLayout.h" | ||||
23 | #include "clang/AST/RecursiveASTVisitor.h" | ||||
24 | #include "clang/AST/StmtVisitor.h" | ||||
25 | #include "clang/AST/TypeLoc.h" | ||||
26 | #include "clang/AST/TypeOrdering.h" | ||||
27 | #include "clang/Basic/AttributeCommonInfo.h" | ||||
28 | #include "clang/Basic/PartialDiagnostic.h" | ||||
29 | #include "clang/Basic/TargetInfo.h" | ||||
30 | #include "clang/Lex/LiteralSupport.h" | ||||
31 | #include "clang/Lex/Preprocessor.h" | ||||
32 | #include "clang/Sema/CXXFieldCollector.h" | ||||
33 | #include "clang/Sema/DeclSpec.h" | ||||
34 | #include "clang/Sema/Initialization.h" | ||||
35 | #include "clang/Sema/Lookup.h" | ||||
36 | #include "clang/Sema/ParsedTemplate.h" | ||||
37 | #include "clang/Sema/Scope.h" | ||||
38 | #include "clang/Sema/ScopeInfo.h" | ||||
39 | #include "clang/Sema/SemaInternal.h" | ||||
40 | #include "clang/Sema/Template.h" | ||||
41 | #include "llvm/ADT/STLExtras.h" | ||||
42 | #include "llvm/ADT/SmallString.h" | ||||
43 | #include "llvm/ADT/StringExtras.h" | ||||
44 | #include <map> | ||||
45 | #include <set> | ||||
46 | |||||
47 | using namespace clang; | ||||
48 | |||||
49 | //===----------------------------------------------------------------------===// | ||||
50 | // CheckDefaultArgumentVisitor | ||||
51 | //===----------------------------------------------------------------------===// | ||||
52 | |||||
53 | namespace { | ||||
54 | /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses | ||||
55 | /// the default argument of a parameter to determine whether it | ||||
56 | /// contains any ill-formed subexpressions. For example, this will | ||||
57 | /// diagnose the use of local variables or parameters within the | ||||
58 | /// default argument expression. | ||||
59 | class CheckDefaultArgumentVisitor | ||||
60 | : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { | ||||
61 | Expr *DefaultArg; | ||||
62 | Sema *S; | ||||
63 | |||||
64 | public: | ||||
65 | CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) | ||||
66 | : DefaultArg(defarg), S(s) {} | ||||
67 | |||||
68 | bool VisitExpr(Expr *Node); | ||||
69 | bool VisitDeclRefExpr(DeclRefExpr *DRE); | ||||
70 | bool VisitCXXThisExpr(CXXThisExpr *ThisE); | ||||
71 | bool VisitLambdaExpr(LambdaExpr *Lambda); | ||||
72 | bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); | ||||
73 | }; | ||||
74 | |||||
75 | /// VisitExpr - Visit all of the children of this expression. | ||||
76 | bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { | ||||
77 | bool IsInvalid = false; | ||||
78 | for (Stmt *SubStmt : Node->children()) | ||||
79 | IsInvalid |= Visit(SubStmt); | ||||
80 | return IsInvalid; | ||||
81 | } | ||||
82 | |||||
83 | /// VisitDeclRefExpr - Visit a reference to a declaration, to | ||||
84 | /// determine whether this declaration can be used in the default | ||||
85 | /// argument expression. | ||||
86 | bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { | ||||
87 | NamedDecl *Decl = DRE->getDecl(); | ||||
88 | if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { | ||||
89 | // C++ [dcl.fct.default]p9 | ||||
90 | // Default arguments are evaluated each time the function is | ||||
91 | // called. The order of evaluation of function arguments is | ||||
92 | // unspecified. Consequently, parameters of a function shall not | ||||
93 | // be used in default argument expressions, even if they are not | ||||
94 | // evaluated. Parameters of a function declared before a default | ||||
95 | // argument expression are in scope and can hide namespace and | ||||
96 | // class member names. | ||||
97 | return S->Diag(DRE->getBeginLoc(), | ||||
98 | diag::err_param_default_argument_references_param) | ||||
99 | << Param->getDeclName() << DefaultArg->getSourceRange(); | ||||
100 | } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { | ||||
101 | // C++ [dcl.fct.default]p7 | ||||
102 | // Local variables shall not be used in default argument | ||||
103 | // expressions. | ||||
104 | if (VDecl->isLocalVarDecl()) | ||||
105 | return S->Diag(DRE->getBeginLoc(), | ||||
106 | diag::err_param_default_argument_references_local) | ||||
107 | << VDecl->getDeclName() << DefaultArg->getSourceRange(); | ||||
108 | } | ||||
109 | |||||
110 | return false; | ||||
111 | } | ||||
112 | |||||
113 | /// VisitCXXThisExpr - Visit a C++ "this" expression. | ||||
114 | bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { | ||||
115 | // C++ [dcl.fct.default]p8: | ||||
116 | // The keyword this shall not be used in a default argument of a | ||||
117 | // member function. | ||||
118 | return S->Diag(ThisE->getBeginLoc(), | ||||
119 | diag::err_param_default_argument_references_this) | ||||
120 | << ThisE->getSourceRange(); | ||||
121 | } | ||||
122 | |||||
123 | bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { | ||||
124 | bool Invalid = false; | ||||
125 | for (PseudoObjectExpr::semantics_iterator | ||||
126 | i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { | ||||
127 | Expr *E = *i; | ||||
128 | |||||
129 | // Look through bindings. | ||||
130 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { | ||||
131 | E = OVE->getSourceExpr(); | ||||
132 | assert(E && "pseudo-object binding without source expression?")((E && "pseudo-object binding without source expression?" ) ? static_cast<void> (0) : __assert_fail ("E && \"pseudo-object binding without source expression?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 132, __PRETTY_FUNCTION__)); | ||||
133 | } | ||||
134 | |||||
135 | Invalid |= Visit(E); | ||||
136 | } | ||||
137 | return Invalid; | ||||
138 | } | ||||
139 | |||||
140 | bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { | ||||
141 | // C++11 [expr.lambda.prim]p13: | ||||
142 | // A lambda-expression appearing in a default argument shall not | ||||
143 | // implicitly or explicitly capture any entity. | ||||
144 | if (Lambda->capture_begin() == Lambda->capture_end()) | ||||
145 | return false; | ||||
146 | |||||
147 | return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); | ||||
148 | } | ||||
149 | } | ||||
150 | |||||
151 | void | ||||
152 | Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, | ||||
153 | const CXXMethodDecl *Method) { | ||||
154 | // If we have an MSAny spec already, don't bother. | ||||
155 | if (!Method || ComputedEST == EST_MSAny) | ||||
156 | return; | ||||
157 | |||||
158 | const FunctionProtoType *Proto | ||||
159 | = Method->getType()->getAs<FunctionProtoType>(); | ||||
160 | Proto = Self->ResolveExceptionSpec(CallLoc, Proto); | ||||
161 | if (!Proto) | ||||
162 | return; | ||||
163 | |||||
164 | ExceptionSpecificationType EST = Proto->getExceptionSpecType(); | ||||
165 | |||||
166 | // If we have a throw-all spec at this point, ignore the function. | ||||
167 | if (ComputedEST == EST_None) | ||||
168 | return; | ||||
169 | |||||
170 | if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) | ||||
171 | EST = EST_BasicNoexcept; | ||||
172 | |||||
173 | switch (EST) { | ||||
174 | case EST_Unparsed: | ||||
175 | case EST_Uninstantiated: | ||||
176 | case EST_Unevaluated: | ||||
177 | llvm_unreachable("should not see unresolved exception specs here")::llvm::llvm_unreachable_internal("should not see unresolved exception specs here" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 177); | ||||
178 | |||||
179 | // If this function can throw any exceptions, make a note of that. | ||||
180 | case EST_MSAny: | ||||
181 | case EST_None: | ||||
182 | // FIXME: Whichever we see last of MSAny and None determines our result. | ||||
183 | // We should make a consistent, order-independent choice here. | ||||
184 | ClearExceptions(); | ||||
185 | ComputedEST = EST; | ||||
186 | return; | ||||
187 | case EST_NoexceptFalse: | ||||
188 | ClearExceptions(); | ||||
189 | ComputedEST = EST_None; | ||||
190 | return; | ||||
191 | // FIXME: If the call to this decl is using any of its default arguments, we | ||||
192 | // need to search them for potentially-throwing calls. | ||||
193 | // If this function has a basic noexcept, it doesn't affect the outcome. | ||||
194 | case EST_BasicNoexcept: | ||||
195 | case EST_NoexceptTrue: | ||||
196 | case EST_NoThrow: | ||||
197 | return; | ||||
198 | // If we're still at noexcept(true) and there's a throw() callee, | ||||
199 | // change to that specification. | ||||
200 | case EST_DynamicNone: | ||||
201 | if (ComputedEST == EST_BasicNoexcept) | ||||
202 | ComputedEST = EST_DynamicNone; | ||||
203 | return; | ||||
204 | case EST_DependentNoexcept: | ||||
205 | llvm_unreachable(::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 206) | ||||
206 | "should not generate implicit declarations for dependent cases")::llvm::llvm_unreachable_internal("should not generate implicit declarations for dependent cases" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 206); | ||||
207 | case EST_Dynamic: | ||||
208 | break; | ||||
209 | } | ||||
210 | assert(EST == EST_Dynamic && "EST case not considered earlier.")((EST == EST_Dynamic && "EST case not considered earlier." ) ? static_cast<void> (0) : __assert_fail ("EST == EST_Dynamic && \"EST case not considered earlier.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 210, __PRETTY_FUNCTION__)); | ||||
211 | assert(ComputedEST != EST_None &&((ComputedEST != EST_None && "Shouldn't collect exceptions when throw-all is guaranteed." ) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 212, __PRETTY_FUNCTION__)) | ||||
212 | "Shouldn't collect exceptions when throw-all is guaranteed.")((ComputedEST != EST_None && "Shouldn't collect exceptions when throw-all is guaranteed." ) ? static_cast<void> (0) : __assert_fail ("ComputedEST != EST_None && \"Shouldn't collect exceptions when throw-all is guaranteed.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 212, __PRETTY_FUNCTION__)); | ||||
213 | ComputedEST = EST_Dynamic; | ||||
214 | // Record the exceptions in this function's exception specification. | ||||
215 | for (const auto &E : Proto->exceptions()) | ||||
216 | if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) | ||||
217 | Exceptions.push_back(E); | ||||
218 | } | ||||
219 | |||||
220 | void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) { | ||||
221 | if (!S || ComputedEST == EST_MSAny) | ||||
222 | return; | ||||
223 | |||||
224 | // FIXME: | ||||
225 | // | ||||
226 | // C++0x [except.spec]p14: | ||||
227 | // [An] implicit exception-specification specifies the type-id T if and | ||||
228 | // only if T is allowed by the exception-specification of a function directly | ||||
229 | // invoked by f's implicit definition; f shall allow all exceptions if any | ||||
230 | // function it directly invokes allows all exceptions, and f shall allow no | ||||
231 | // exceptions if every function it directly invokes allows no exceptions. | ||||
232 | // | ||||
233 | // Note in particular that if an implicit exception-specification is generated | ||||
234 | // for a function containing a throw-expression, that specification can still | ||||
235 | // be noexcept(true). | ||||
236 | // | ||||
237 | // Note also that 'directly invoked' is not defined in the standard, and there | ||||
238 | // is no indication that we should only consider potentially-evaluated calls. | ||||
239 | // | ||||
240 | // Ultimately we should implement the intent of the standard: the exception | ||||
241 | // specification should be the set of exceptions which can be thrown by the | ||||
242 | // implicit definition. For now, we assume that any non-nothrow expression can | ||||
243 | // throw any exception. | ||||
244 | |||||
245 | if (Self->canThrow(S)) | ||||
246 | ComputedEST = EST_None; | ||||
247 | } | ||||
248 | |||||
249 | bool | ||||
250 | Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, | ||||
251 | SourceLocation EqualLoc) { | ||||
252 | if (RequireCompleteType(Param->getLocation(), Param->getType(), | ||||
253 | diag::err_typecheck_decl_incomplete_type)) { | ||||
254 | Param->setInvalidDecl(); | ||||
255 | return true; | ||||
256 | } | ||||
257 | |||||
258 | // C++ [dcl.fct.default]p5 | ||||
259 | // A default argument expression is implicitly converted (clause | ||||
260 | // 4) to the parameter type. The default argument expression has | ||||
261 | // the same semantic constraints as the initializer expression in | ||||
262 | // a declaration of a variable of the parameter type, using the | ||||
263 | // copy-initialization semantics (8.5). | ||||
264 | InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, | ||||
265 | Param); | ||||
266 | InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), | ||||
267 | EqualLoc); | ||||
268 | InitializationSequence InitSeq(*this, Entity, Kind, Arg); | ||||
269 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); | ||||
270 | if (Result.isInvalid()) | ||||
271 | return true; | ||||
272 | Arg = Result.getAs<Expr>(); | ||||
273 | |||||
274 | CheckCompletedExpr(Arg, EqualLoc); | ||||
275 | Arg = MaybeCreateExprWithCleanups(Arg); | ||||
276 | |||||
277 | // Okay: add the default argument to the parameter | ||||
278 | Param->setDefaultArg(Arg); | ||||
279 | |||||
280 | // We have already instantiated this parameter; provide each of the | ||||
281 | // instantiations with the uninstantiated default argument. | ||||
282 | UnparsedDefaultArgInstantiationsMap::iterator InstPos | ||||
283 | = UnparsedDefaultArgInstantiations.find(Param); | ||||
284 | if (InstPos != UnparsedDefaultArgInstantiations.end()) { | ||||
285 | for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) | ||||
286 | InstPos->second[I]->setUninstantiatedDefaultArg(Arg); | ||||
287 | |||||
288 | // We're done tracking this parameter's instantiations. | ||||
289 | UnparsedDefaultArgInstantiations.erase(InstPos); | ||||
290 | } | ||||
291 | |||||
292 | return false; | ||||
293 | } | ||||
294 | |||||
295 | /// ActOnParamDefaultArgument - Check whether the default argument | ||||
296 | /// provided for a function parameter is well-formed. If so, attach it | ||||
297 | /// to the parameter declaration. | ||||
298 | void | ||||
299 | Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, | ||||
300 | Expr *DefaultArg) { | ||||
301 | if (!param || !DefaultArg) | ||||
302 | return; | ||||
303 | |||||
304 | ParmVarDecl *Param = cast<ParmVarDecl>(param); | ||||
305 | UnparsedDefaultArgLocs.erase(Param); | ||||
306 | |||||
307 | // Default arguments are only permitted in C++ | ||||
308 | if (!getLangOpts().CPlusPlus) { | ||||
309 | Diag(EqualLoc, diag::err_param_default_argument) | ||||
310 | << DefaultArg->getSourceRange(); | ||||
311 | Param->setInvalidDecl(); | ||||
312 | return; | ||||
313 | } | ||||
314 | |||||
315 | // Check for unexpanded parameter packs. | ||||
316 | if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { | ||||
317 | Param->setInvalidDecl(); | ||||
318 | return; | ||||
319 | } | ||||
320 | |||||
321 | // C++11 [dcl.fct.default]p3 | ||||
322 | // A default argument expression [...] shall not be specified for a | ||||
323 | // parameter pack. | ||||
324 | if (Param->isParameterPack()) { | ||||
325 | Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) | ||||
326 | << DefaultArg->getSourceRange(); | ||||
327 | return; | ||||
328 | } | ||||
329 | |||||
330 | // Check that the default argument is well-formed | ||||
331 | CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); | ||||
332 | if (DefaultArgChecker.Visit(DefaultArg)) { | ||||
333 | Param->setInvalidDecl(); | ||||
334 | return; | ||||
335 | } | ||||
336 | |||||
337 | SetParamDefaultArgument(Param, DefaultArg, EqualLoc); | ||||
338 | } | ||||
339 | |||||
340 | /// ActOnParamUnparsedDefaultArgument - We've seen a default | ||||
341 | /// argument for a function parameter, but we can't parse it yet | ||||
342 | /// because we're inside a class definition. Note that this default | ||||
343 | /// argument will be parsed later. | ||||
344 | void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, | ||||
345 | SourceLocation EqualLoc, | ||||
346 | SourceLocation ArgLoc) { | ||||
347 | if (!param) | ||||
348 | return; | ||||
349 | |||||
350 | ParmVarDecl *Param = cast<ParmVarDecl>(param); | ||||
351 | Param->setUnparsedDefaultArg(); | ||||
352 | UnparsedDefaultArgLocs[Param] = ArgLoc; | ||||
353 | } | ||||
354 | |||||
355 | /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of | ||||
356 | /// the default argument for the parameter param failed. | ||||
357 | void Sema::ActOnParamDefaultArgumentError(Decl *param, | ||||
358 | SourceLocation EqualLoc) { | ||||
359 | if (!param) | ||||
360 | return; | ||||
361 | |||||
362 | ParmVarDecl *Param = cast<ParmVarDecl>(param); | ||||
363 | Param->setInvalidDecl(); | ||||
364 | UnparsedDefaultArgLocs.erase(Param); | ||||
365 | Param->setDefaultArg(new(Context) | ||||
366 | OpaqueValueExpr(EqualLoc, | ||||
367 | Param->getType().getNonReferenceType(), | ||||
368 | VK_RValue)); | ||||
369 | } | ||||
370 | |||||
371 | /// CheckExtraCXXDefaultArguments - Check for any extra default | ||||
372 | /// arguments in the declarator, which is not a function declaration | ||||
373 | /// or definition and therefore is not permitted to have default | ||||
374 | /// arguments. This routine should be invoked for every declarator | ||||
375 | /// that is not a function declaration or definition. | ||||
376 | void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { | ||||
377 | // C++ [dcl.fct.default]p3 | ||||
378 | // A default argument expression shall be specified only in the | ||||
379 | // parameter-declaration-clause of a function declaration or in a | ||||
380 | // template-parameter (14.1). It shall not be specified for a | ||||
381 | // parameter pack. If it is specified in a | ||||
382 | // parameter-declaration-clause, it shall not occur within a | ||||
383 | // declarator or abstract-declarator of a parameter-declaration. | ||||
384 | bool MightBeFunction = D.isFunctionDeclarationContext(); | ||||
385 | for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { | ||||
386 | DeclaratorChunk &chunk = D.getTypeObject(i); | ||||
387 | if (chunk.Kind == DeclaratorChunk::Function) { | ||||
388 | if (MightBeFunction) { | ||||
389 | // This is a function declaration. It can have default arguments, but | ||||
390 | // keep looking in case its return type is a function type with default | ||||
391 | // arguments. | ||||
392 | MightBeFunction = false; | ||||
393 | continue; | ||||
394 | } | ||||
395 | for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; | ||||
396 | ++argIdx) { | ||||
397 | ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); | ||||
398 | if (Param->hasUnparsedDefaultArg()) { | ||||
399 | std::unique_ptr<CachedTokens> Toks = | ||||
400 | std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); | ||||
401 | SourceRange SR; | ||||
402 | if (Toks->size() > 1) | ||||
403 | SR = SourceRange((*Toks)[1].getLocation(), | ||||
404 | Toks->back().getLocation()); | ||||
405 | else | ||||
406 | SR = UnparsedDefaultArgLocs[Param]; | ||||
407 | Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) | ||||
408 | << SR; | ||||
409 | } else if (Param->getDefaultArg()) { | ||||
410 | Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) | ||||
411 | << Param->getDefaultArg()->getSourceRange(); | ||||
412 | Param->setDefaultArg(nullptr); | ||||
413 | } | ||||
414 | } | ||||
415 | } else if (chunk.Kind != DeclaratorChunk::Paren) { | ||||
416 | MightBeFunction = false; | ||||
417 | } | ||||
418 | } | ||||
419 | } | ||||
420 | |||||
421 | static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { | ||||
422 | for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { | ||||
423 | const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); | ||||
424 | if (!PVD->hasDefaultArg()) | ||||
425 | return false; | ||||
426 | if (!PVD->hasInheritedDefaultArg()) | ||||
427 | return true; | ||||
428 | } | ||||
429 | return false; | ||||
430 | } | ||||
431 | |||||
432 | /// MergeCXXFunctionDecl - Merge two declarations of the same C++ | ||||
433 | /// function, once we already know that they have the same | ||||
434 | /// type. Subroutine of MergeFunctionDecl. Returns true if there was an | ||||
435 | /// error, false otherwise. | ||||
436 | bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, | ||||
437 | Scope *S) { | ||||
438 | bool Invalid = false; | ||||
439 | |||||
440 | // The declaration context corresponding to the scope is the semantic | ||||
441 | // parent, unless this is a local function declaration, in which case | ||||
442 | // it is that surrounding function. | ||||
443 | DeclContext *ScopeDC = New->isLocalExternDecl() | ||||
444 | ? New->getLexicalDeclContext() | ||||
445 | : New->getDeclContext(); | ||||
446 | |||||
447 | // Find the previous declaration for the purpose of default arguments. | ||||
448 | FunctionDecl *PrevForDefaultArgs = Old; | ||||
449 | for (/**/; PrevForDefaultArgs; | ||||
450 | // Don't bother looking back past the latest decl if this is a local | ||||
451 | // extern declaration; nothing else could work. | ||||
452 | PrevForDefaultArgs = New->isLocalExternDecl() | ||||
453 | ? nullptr | ||||
454 | : PrevForDefaultArgs->getPreviousDecl()) { | ||||
455 | // Ignore hidden declarations. | ||||
456 | if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) | ||||
457 | continue; | ||||
458 | |||||
459 | if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && | ||||
460 | !New->isCXXClassMember()) { | ||||
461 | // Ignore default arguments of old decl if they are not in | ||||
462 | // the same scope and this is not an out-of-line definition of | ||||
463 | // a member function. | ||||
464 | continue; | ||||
465 | } | ||||
466 | |||||
467 | if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { | ||||
468 | // If only one of these is a local function declaration, then they are | ||||
469 | // declared in different scopes, even though isDeclInScope may think | ||||
470 | // they're in the same scope. (If both are local, the scope check is | ||||
471 | // sufficient, and if neither is local, then they are in the same scope.) | ||||
472 | continue; | ||||
473 | } | ||||
474 | |||||
475 | // We found the right previous declaration. | ||||
476 | break; | ||||
477 | } | ||||
478 | |||||
479 | // C++ [dcl.fct.default]p4: | ||||
480 | // For non-template functions, default arguments can be added in | ||||
481 | // later declarations of a function in the same | ||||
482 | // scope. Declarations in different scopes have completely | ||||
483 | // distinct sets of default arguments. That is, declarations in | ||||
484 | // inner scopes do not acquire default arguments from | ||||
485 | // declarations in outer scopes, and vice versa. In a given | ||||
486 | // function declaration, all parameters subsequent to a | ||||
487 | // parameter with a default argument shall have default | ||||
488 | // arguments supplied in this or previous declarations. A | ||||
489 | // default argument shall not be redefined by a later | ||||
490 | // declaration (not even to the same value). | ||||
491 | // | ||||
492 | // C++ [dcl.fct.default]p6: | ||||
493 | // Except for member functions of class templates, the default arguments | ||||
494 | // in a member function definition that appears outside of the class | ||||
495 | // definition are added to the set of default arguments provided by the | ||||
496 | // member function declaration in the class definition. | ||||
497 | for (unsigned p = 0, NumParams = PrevForDefaultArgs | ||||
498 | ? PrevForDefaultArgs->getNumParams() | ||||
499 | : 0; | ||||
500 | p < NumParams; ++p) { | ||||
501 | ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); | ||||
502 | ParmVarDecl *NewParam = New->getParamDecl(p); | ||||
503 | |||||
504 | bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; | ||||
505 | bool NewParamHasDfl = NewParam->hasDefaultArg(); | ||||
506 | |||||
507 | if (OldParamHasDfl && NewParamHasDfl) { | ||||
508 | unsigned DiagDefaultParamID = | ||||
509 | diag::err_param_default_argument_redefinition; | ||||
510 | |||||
511 | // MSVC accepts that default parameters be redefined for member functions | ||||
512 | // of template class. The new default parameter's value is ignored. | ||||
513 | Invalid = true; | ||||
514 | if (getLangOpts().MicrosoftExt) { | ||||
515 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); | ||||
516 | if (MD && MD->getParent()->getDescribedClassTemplate()) { | ||||
517 | // Merge the old default argument into the new parameter. | ||||
518 | NewParam->setHasInheritedDefaultArg(); | ||||
519 | if (OldParam->hasUninstantiatedDefaultArg()) | ||||
520 | NewParam->setUninstantiatedDefaultArg( | ||||
521 | OldParam->getUninstantiatedDefaultArg()); | ||||
522 | else | ||||
523 | NewParam->setDefaultArg(OldParam->getInit()); | ||||
524 | DiagDefaultParamID = diag::ext_param_default_argument_redefinition; | ||||
525 | Invalid = false; | ||||
526 | } | ||||
527 | } | ||||
528 | |||||
529 | // FIXME: If we knew where the '=' was, we could easily provide a fix-it | ||||
530 | // hint here. Alternatively, we could walk the type-source information | ||||
531 | // for NewParam to find the last source location in the type... but it | ||||
532 | // isn't worth the effort right now. This is the kind of test case that | ||||
533 | // is hard to get right: | ||||
534 | // int f(int); | ||||
535 | // void g(int (*fp)(int) = f); | ||||
536 | // void g(int (*fp)(int) = &f); | ||||
537 | Diag(NewParam->getLocation(), DiagDefaultParamID) | ||||
538 | << NewParam->getDefaultArgRange(); | ||||
539 | |||||
540 | // Look for the function declaration where the default argument was | ||||
541 | // actually written, which may be a declaration prior to Old. | ||||
542 | for (auto Older = PrevForDefaultArgs; | ||||
543 | OldParam->hasInheritedDefaultArg(); /**/) { | ||||
544 | Older = Older->getPreviousDecl(); | ||||
545 | OldParam = Older->getParamDecl(p); | ||||
546 | } | ||||
547 | |||||
548 | Diag(OldParam->getLocation(), diag::note_previous_definition) | ||||
549 | << OldParam->getDefaultArgRange(); | ||||
550 | } else if (OldParamHasDfl) { | ||||
551 | // Merge the old default argument into the new parameter unless the new | ||||
552 | // function is a friend declaration in a template class. In the latter | ||||
553 | // case the default arguments will be inherited when the friend | ||||
554 | // declaration will be instantiated. | ||||
555 | if (New->getFriendObjectKind() == Decl::FOK_None || | ||||
556 | !New->getLexicalDeclContext()->isDependentContext()) { | ||||
557 | // It's important to use getInit() here; getDefaultArg() | ||||
558 | // strips off any top-level ExprWithCleanups. | ||||
559 | NewParam->setHasInheritedDefaultArg(); | ||||
560 | if (OldParam->hasUnparsedDefaultArg()) | ||||
561 | NewParam->setUnparsedDefaultArg(); | ||||
562 | else if (OldParam->hasUninstantiatedDefaultArg()) | ||||
563 | NewParam->setUninstantiatedDefaultArg( | ||||
564 | OldParam->getUninstantiatedDefaultArg()); | ||||
565 | else | ||||
566 | NewParam->setDefaultArg(OldParam->getInit()); | ||||
567 | } | ||||
568 | } else if (NewParamHasDfl) { | ||||
569 | if (New->getDescribedFunctionTemplate()) { | ||||
570 | // Paragraph 4, quoted above, only applies to non-template functions. | ||||
571 | Diag(NewParam->getLocation(), | ||||
572 | diag::err_param_default_argument_template_redecl) | ||||
573 | << NewParam->getDefaultArgRange(); | ||||
574 | Diag(PrevForDefaultArgs->getLocation(), | ||||
575 | diag::note_template_prev_declaration) | ||||
576 | << false; | ||||
577 | } else if (New->getTemplateSpecializationKind() | ||||
578 | != TSK_ImplicitInstantiation && | ||||
579 | New->getTemplateSpecializationKind() != TSK_Undeclared) { | ||||
580 | // C++ [temp.expr.spec]p21: | ||||
581 | // Default function arguments shall not be specified in a declaration | ||||
582 | // or a definition for one of the following explicit specializations: | ||||
583 | // - the explicit specialization of a function template; | ||||
584 | // - the explicit specialization of a member function template; | ||||
585 | // - the explicit specialization of a member function of a class | ||||
586 | // template where the class template specialization to which the | ||||
587 | // member function specialization belongs is implicitly | ||||
588 | // instantiated. | ||||
589 | Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) | ||||
590 | << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) | ||||
591 | << New->getDeclName() | ||||
592 | << NewParam->getDefaultArgRange(); | ||||
593 | } else if (New->getDeclContext()->isDependentContext()) { | ||||
594 | // C++ [dcl.fct.default]p6 (DR217): | ||||
595 | // Default arguments for a member function of a class template shall | ||||
596 | // be specified on the initial declaration of the member function | ||||
597 | // within the class template. | ||||
598 | // | ||||
599 | // Reading the tea leaves a bit in DR217 and its reference to DR205 | ||||
600 | // leads me to the conclusion that one cannot add default function | ||||
601 | // arguments for an out-of-line definition of a member function of a | ||||
602 | // dependent type. | ||||
603 | int WhichKind = 2; | ||||
604 | if (CXXRecordDecl *Record | ||||
605 | = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { | ||||
606 | if (Record->getDescribedClassTemplate()) | ||||
607 | WhichKind = 0; | ||||
608 | else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) | ||||
609 | WhichKind = 1; | ||||
610 | else | ||||
611 | WhichKind = 2; | ||||
612 | } | ||||
613 | |||||
614 | Diag(NewParam->getLocation(), | ||||
615 | diag::err_param_default_argument_member_template_redecl) | ||||
616 | << WhichKind | ||||
617 | << NewParam->getDefaultArgRange(); | ||||
618 | } | ||||
619 | } | ||||
620 | } | ||||
621 | |||||
622 | // DR1344: If a default argument is added outside a class definition and that | ||||
623 | // default argument makes the function a special member function, the program | ||||
624 | // is ill-formed. This can only happen for constructors. | ||||
625 | if (isa<CXXConstructorDecl>(New) && | ||||
626 | New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { | ||||
627 | CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), | ||||
628 | OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); | ||||
629 | if (NewSM != OldSM) { | ||||
630 | ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); | ||||
631 | assert(NewParam->hasDefaultArg())((NewParam->hasDefaultArg()) ? static_cast<void> (0) : __assert_fail ("NewParam->hasDefaultArg()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 631, __PRETTY_FUNCTION__)); | ||||
632 | Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) | ||||
633 | << NewParam->getDefaultArgRange() << NewSM; | ||||
634 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
635 | } | ||||
636 | } | ||||
637 | |||||
638 | const FunctionDecl *Def; | ||||
639 | // C++11 [dcl.constexpr]p1: If any declaration of a function or function | ||||
640 | // template has a constexpr specifier then all its declarations shall | ||||
641 | // contain the constexpr specifier. | ||||
642 | if (New->getConstexprKind() != Old->getConstexprKind()) { | ||||
643 | Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) | ||||
644 | << New << New->getConstexprKind() << Old->getConstexprKind(); | ||||
645 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
646 | Invalid = true; | ||||
647 | } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && | ||||
648 | Old->isDefined(Def) && | ||||
649 | // If a friend function is inlined but does not have 'inline' | ||||
650 | // specifier, it is a definition. Do not report attribute conflict | ||||
651 | // in this case, redefinition will be diagnosed later. | ||||
652 | (New->isInlineSpecified() || | ||||
653 | New->getFriendObjectKind() == Decl::FOK_None)) { | ||||
654 | // C++11 [dcl.fcn.spec]p4: | ||||
655 | // If the definition of a function appears in a translation unit before its | ||||
656 | // first declaration as inline, the program is ill-formed. | ||||
657 | Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; | ||||
658 | Diag(Def->getLocation(), diag::note_previous_definition); | ||||
659 | Invalid = true; | ||||
660 | } | ||||
661 | |||||
662 | // C++17 [temp.deduct.guide]p3: | ||||
663 | // Two deduction guide declarations in the same translation unit | ||||
664 | // for the same class template shall not have equivalent | ||||
665 | // parameter-declaration-clauses. | ||||
666 | if (isa<CXXDeductionGuideDecl>(New) && | ||||
667 | !New->isFunctionTemplateSpecialization()) { | ||||
668 | Diag(New->getLocation(), diag::err_deduction_guide_redeclared); | ||||
669 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
670 | } | ||||
671 | |||||
672 | // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default | ||||
673 | // argument expression, that declaration shall be a definition and shall be | ||||
674 | // the only declaration of the function or function template in the | ||||
675 | // translation unit. | ||||
676 | if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && | ||||
677 | functionDeclHasDefaultArgument(Old)) { | ||||
678 | Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); | ||||
679 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
680 | Invalid = true; | ||||
681 | } | ||||
682 | |||||
683 | return Invalid; | ||||
684 | } | ||||
685 | |||||
686 | NamedDecl * | ||||
687 | Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, | ||||
688 | MultiTemplateParamsArg TemplateParamLists) { | ||||
689 | assert(D.isDecompositionDeclarator())((D.isDecompositionDeclarator()) ? static_cast<void> (0 ) : __assert_fail ("D.isDecompositionDeclarator()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 689, __PRETTY_FUNCTION__)); | ||||
690 | const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); | ||||
691 | |||||
692 | // The syntax only allows a decomposition declarator as a simple-declaration, | ||||
693 | // a for-range-declaration, or a condition in Clang, but we parse it in more | ||||
694 | // cases than that. | ||||
695 | if (!D.mayHaveDecompositionDeclarator()) { | ||||
696 | Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) | ||||
697 | << Decomp.getSourceRange(); | ||||
698 | return nullptr; | ||||
699 | } | ||||
700 | |||||
701 | if (!TemplateParamLists.empty()) { | ||||
702 | // FIXME: There's no rule against this, but there are also no rules that | ||||
703 | // would actually make it usable, so we reject it for now. | ||||
704 | Diag(TemplateParamLists.front()->getTemplateLoc(), | ||||
705 | diag::err_decomp_decl_template); | ||||
706 | return nullptr; | ||||
707 | } | ||||
708 | |||||
709 | Diag(Decomp.getLSquareLoc(), | ||||
710 | !getLangOpts().CPlusPlus17 | ||||
711 | ? diag::ext_decomp_decl | ||||
712 | : D.getContext() == DeclaratorContext::ConditionContext | ||||
713 | ? diag::ext_decomp_decl_cond | ||||
714 | : diag::warn_cxx14_compat_decomp_decl) | ||||
715 | << Decomp.getSourceRange(); | ||||
716 | |||||
717 | // The semantic context is always just the current context. | ||||
718 | DeclContext *const DC = CurContext; | ||||
719 | |||||
720 | // C++17 [dcl.dcl]/8: | ||||
721 | // The decl-specifier-seq shall contain only the type-specifier auto | ||||
722 | // and cv-qualifiers. | ||||
723 | // C++2a [dcl.dcl]/8: | ||||
724 | // If decl-specifier-seq contains any decl-specifier other than static, | ||||
725 | // thread_local, auto, or cv-qualifiers, the program is ill-formed. | ||||
726 | auto &DS = D.getDeclSpec(); | ||||
727 | { | ||||
728 | SmallVector<StringRef, 8> BadSpecifiers; | ||||
729 | SmallVector<SourceLocation, 8> BadSpecifierLocs; | ||||
730 | SmallVector<StringRef, 8> CPlusPlus20Specifiers; | ||||
731 | SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; | ||||
732 | if (auto SCS = DS.getStorageClassSpec()) { | ||||
733 | if (SCS == DeclSpec::SCS_static) { | ||||
734 | CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); | ||||
735 | CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); | ||||
736 | } else { | ||||
737 | BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); | ||||
738 | BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); | ||||
739 | } | ||||
740 | } | ||||
741 | if (auto TSCS = DS.getThreadStorageClassSpec()) { | ||||
742 | CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); | ||||
743 | CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); | ||||
744 | } | ||||
745 | if (DS.hasConstexprSpecifier()) { | ||||
746 | BadSpecifiers.push_back( | ||||
747 | DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); | ||||
748 | BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); | ||||
749 | } | ||||
750 | if (DS.isInlineSpecified()) { | ||||
751 | BadSpecifiers.push_back("inline"); | ||||
752 | BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); | ||||
753 | } | ||||
754 | if (!BadSpecifiers.empty()) { | ||||
755 | auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); | ||||
756 | Err << (int)BadSpecifiers.size() | ||||
757 | << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); | ||||
758 | // Don't add FixItHints to remove the specifiers; we do still respect | ||||
759 | // them when building the underlying variable. | ||||
760 | for (auto Loc : BadSpecifierLocs) | ||||
761 | Err << SourceRange(Loc, Loc); | ||||
762 | } else if (!CPlusPlus20Specifiers.empty()) { | ||||
763 | auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), | ||||
764 | getLangOpts().CPlusPlus2a | ||||
765 | ? diag::warn_cxx17_compat_decomp_decl_spec | ||||
766 | : diag::ext_decomp_decl_spec); | ||||
767 | Warn << (int)CPlusPlus20Specifiers.size() | ||||
768 | << llvm::join(CPlusPlus20Specifiers.begin(), | ||||
769 | CPlusPlus20Specifiers.end(), " "); | ||||
770 | for (auto Loc : CPlusPlus20SpecifierLocs) | ||||
771 | Warn << SourceRange(Loc, Loc); | ||||
772 | } | ||||
773 | // We can't recover from it being declared as a typedef. | ||||
774 | if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) | ||||
775 | return nullptr; | ||||
776 | } | ||||
777 | |||||
778 | // C++2a [dcl.struct.bind]p1: | ||||
779 | // A cv that includes volatile is deprecated | ||||
780 | if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && | ||||
781 | getLangOpts().CPlusPlus2a) | ||||
782 | Diag(DS.getVolatileSpecLoc(), | ||||
783 | diag::warn_deprecated_volatile_structured_binding); | ||||
784 | |||||
785 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||
786 | QualType R = TInfo->getType(); | ||||
787 | |||||
788 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | ||||
789 | UPPC_DeclarationType)) | ||||
790 | D.setInvalidType(); | ||||
791 | |||||
792 | // The syntax only allows a single ref-qualifier prior to the decomposition | ||||
793 | // declarator. No other declarator chunks are permitted. Also check the type | ||||
794 | // specifier here. | ||||
795 | if (DS.getTypeSpecType() != DeclSpec::TST_auto || | ||||
796 | D.hasGroupingParens() || D.getNumTypeObjects() > 1 || | ||||
797 | (D.getNumTypeObjects() == 1 && | ||||
798 | D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { | ||||
799 | Diag(Decomp.getLSquareLoc(), | ||||
800 | (D.hasGroupingParens() || | ||||
801 | (D.getNumTypeObjects() && | ||||
802 | D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) | ||||
803 | ? diag::err_decomp_decl_parens | ||||
804 | : diag::err_decomp_decl_type) | ||||
805 | << R; | ||||
806 | |||||
807 | // In most cases, there's no actual problem with an explicitly-specified | ||||
808 | // type, but a function type won't work here, and ActOnVariableDeclarator | ||||
809 | // shouldn't be called for such a type. | ||||
810 | if (R->isFunctionType()) | ||||
811 | D.setInvalidType(); | ||||
812 | } | ||||
813 | |||||
814 | // Build the BindingDecls. | ||||
815 | SmallVector<BindingDecl*, 8> Bindings; | ||||
816 | |||||
817 | // Build the BindingDecls. | ||||
818 | for (auto &B : D.getDecompositionDeclarator().bindings()) { | ||||
819 | // Check for name conflicts. | ||||
820 | DeclarationNameInfo NameInfo(B.Name, B.NameLoc); | ||||
821 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||
822 | ForVisibleRedeclaration); | ||||
823 | LookupName(Previous, S, | ||||
824 | /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); | ||||
825 | |||||
826 | // It's not permitted to shadow a template parameter name. | ||||
827 | if (Previous.isSingleResult() && | ||||
828 | Previous.getFoundDecl()->isTemplateParameter()) { | ||||
829 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), | ||||
830 | Previous.getFoundDecl()); | ||||
831 | Previous.clear(); | ||||
832 | } | ||||
833 | |||||
834 | bool ConsiderLinkage = DC->isFunctionOrMethod() && | ||||
835 | DS.getStorageClassSpec() == DeclSpec::SCS_extern; | ||||
836 | FilterLookupForScope(Previous, DC, S, ConsiderLinkage, | ||||
837 | /*AllowInlineNamespace*/false); | ||||
838 | if (!Previous.empty()) { | ||||
839 | auto *Old = Previous.getRepresentativeDecl(); | ||||
840 | Diag(B.NameLoc, diag::err_redefinition) << B.Name; | ||||
841 | Diag(Old->getLocation(), diag::note_previous_definition); | ||||
842 | } | ||||
843 | |||||
844 | auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); | ||||
845 | PushOnScopeChains(BD, S, true); | ||||
846 | Bindings.push_back(BD); | ||||
847 | ParsingInitForAutoVars.insert(BD); | ||||
848 | } | ||||
849 | |||||
850 | // There are no prior lookup results for the variable itself, because it | ||||
851 | // is unnamed. | ||||
852 | DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, | ||||
853 | Decomp.getLSquareLoc()); | ||||
854 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||
855 | ForVisibleRedeclaration); | ||||
856 | |||||
857 | // Build the variable that holds the non-decomposed object. | ||||
858 | bool AddToScope = true; | ||||
859 | NamedDecl *New = | ||||
860 | ActOnVariableDeclarator(S, D, DC, TInfo, Previous, | ||||
861 | MultiTemplateParamsArg(), AddToScope, Bindings); | ||||
862 | if (AddToScope) { | ||||
863 | S->AddDecl(New); | ||||
864 | CurContext->addHiddenDecl(New); | ||||
865 | } | ||||
866 | |||||
867 | if (isInOpenMPDeclareTargetContext()) | ||||
868 | checkDeclIsAllowedInOpenMPTarget(nullptr, New); | ||||
869 | |||||
870 | return New; | ||||
871 | } | ||||
872 | |||||
873 | static bool checkSimpleDecomposition( | ||||
874 | Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, | ||||
875 | QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, | ||||
876 | llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { | ||||
877 | if ((int64_t)Bindings.size() != NumElems) { | ||||
878 | S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) | ||||
879 | << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) | ||||
880 | << (NumElems < Bindings.size()); | ||||
881 | return true; | ||||
882 | } | ||||
883 | |||||
884 | unsigned I = 0; | ||||
885 | for (auto *B : Bindings) { | ||||
886 | SourceLocation Loc = B->getLocation(); | ||||
887 | ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); | ||||
888 | if (E.isInvalid()) | ||||
889 | return true; | ||||
890 | E = GetInit(Loc, E.get(), I++); | ||||
891 | if (E.isInvalid()) | ||||
892 | return true; | ||||
893 | B->setBinding(ElemType, E.get()); | ||||
894 | } | ||||
895 | |||||
896 | return false; | ||||
897 | } | ||||
898 | |||||
899 | static bool checkArrayLikeDecomposition(Sema &S, | ||||
900 | ArrayRef<BindingDecl *> Bindings, | ||||
901 | ValueDecl *Src, QualType DecompType, | ||||
902 | const llvm::APSInt &NumElems, | ||||
903 | QualType ElemType) { | ||||
904 | return checkSimpleDecomposition( | ||||
905 | S, Bindings, Src, DecompType, NumElems, ElemType, | ||||
906 | [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { | ||||
907 | ExprResult E = S.ActOnIntegerConstant(Loc, I); | ||||
908 | if (E.isInvalid()) | ||||
909 | return ExprError(); | ||||
910 | return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); | ||||
911 | }); | ||||
912 | } | ||||
913 | |||||
914 | static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, | ||||
915 | ValueDecl *Src, QualType DecompType, | ||||
916 | const ConstantArrayType *CAT) { | ||||
917 | return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, | ||||
918 | llvm::APSInt(CAT->getSize()), | ||||
919 | CAT->getElementType()); | ||||
920 | } | ||||
921 | |||||
922 | static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, | ||||
923 | ValueDecl *Src, QualType DecompType, | ||||
924 | const VectorType *VT) { | ||||
925 | return checkArrayLikeDecomposition( | ||||
926 | S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), | ||||
927 | S.Context.getQualifiedType(VT->getElementType(), | ||||
928 | DecompType.getQualifiers())); | ||||
929 | } | ||||
930 | |||||
931 | static bool checkComplexDecomposition(Sema &S, | ||||
932 | ArrayRef<BindingDecl *> Bindings, | ||||
933 | ValueDecl *Src, QualType DecompType, | ||||
934 | const ComplexType *CT) { | ||||
935 | return checkSimpleDecomposition( | ||||
936 | S, Bindings, Src, DecompType, llvm::APSInt::get(2), | ||||
937 | S.Context.getQualifiedType(CT->getElementType(), | ||||
938 | DecompType.getQualifiers()), | ||||
939 | [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { | ||||
940 | return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); | ||||
941 | }); | ||||
942 | } | ||||
943 | |||||
944 | static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, | ||||
945 | TemplateArgumentListInfo &Args) { | ||||
946 | SmallString<128> SS; | ||||
947 | llvm::raw_svector_ostream OS(SS); | ||||
948 | bool First = true; | ||||
949 | for (auto &Arg : Args.arguments()) { | ||||
950 | if (!First) | ||||
951 | OS << ", "; | ||||
952 | Arg.getArgument().print(PrintingPolicy, OS); | ||||
953 | First = false; | ||||
954 | } | ||||
955 | return OS.str(); | ||||
956 | } | ||||
957 | |||||
958 | static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, | ||||
959 | SourceLocation Loc, StringRef Trait, | ||||
960 | TemplateArgumentListInfo &Args, | ||||
961 | unsigned DiagID) { | ||||
962 | auto DiagnoseMissing = [&] { | ||||
963 | if (DiagID) | ||||
964 | S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), | ||||
965 | Args); | ||||
966 | return true; | ||||
967 | }; | ||||
968 | |||||
969 | // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. | ||||
970 | NamespaceDecl *Std = S.getStdNamespace(); | ||||
971 | if (!Std) | ||||
972 | return DiagnoseMissing(); | ||||
973 | |||||
974 | // Look up the trait itself, within namespace std. We can diagnose various | ||||
975 | // problems with this lookup even if we've been asked to not diagnose a | ||||
976 | // missing specialization, because this can only fail if the user has been | ||||
977 | // declaring their own names in namespace std or we don't support the | ||||
978 | // standard library implementation in use. | ||||
979 | LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), | ||||
980 | Loc, Sema::LookupOrdinaryName); | ||||
981 | if (!S.LookupQualifiedName(Result, Std)) | ||||
982 | return DiagnoseMissing(); | ||||
983 | if (Result.isAmbiguous()) | ||||
984 | return true; | ||||
985 | |||||
986 | ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); | ||||
987 | if (!TraitTD) { | ||||
988 | Result.suppressDiagnostics(); | ||||
989 | NamedDecl *Found = *Result.begin(); | ||||
990 | S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; | ||||
991 | S.Diag(Found->getLocation(), diag::note_declared_at); | ||||
992 | return true; | ||||
993 | } | ||||
994 | |||||
995 | // Build the template-id. | ||||
996 | QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); | ||||
997 | if (TraitTy.isNull()) | ||||
998 | return true; | ||||
999 | if (!S.isCompleteType(Loc, TraitTy)) { | ||||
1000 | if (DiagID) | ||||
1001 | S.RequireCompleteType( | ||||
1002 | Loc, TraitTy, DiagID, | ||||
1003 | printTemplateArgs(S.Context.getPrintingPolicy(), Args)); | ||||
1004 | return true; | ||||
1005 | } | ||||
1006 | |||||
1007 | CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); | ||||
1008 | assert(RD && "specialization of class template is not a class?")((RD && "specialization of class template is not a class?" ) ? static_cast<void> (0) : __assert_fail ("RD && \"specialization of class template is not a class?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 1008, __PRETTY_FUNCTION__)); | ||||
1009 | |||||
1010 | // Look up the member of the trait type. | ||||
1011 | S.LookupQualifiedName(TraitMemberLookup, RD); | ||||
1012 | return TraitMemberLookup.isAmbiguous(); | ||||
1013 | } | ||||
1014 | |||||
1015 | static TemplateArgumentLoc | ||||
1016 | getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, | ||||
1017 | uint64_t I) { | ||||
1018 | TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); | ||||
1019 | return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); | ||||
1020 | } | ||||
1021 | |||||
1022 | static TemplateArgumentLoc | ||||
1023 | getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { | ||||
1024 | return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); | ||||
1025 | } | ||||
1026 | |||||
1027 | namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } | ||||
1028 | |||||
1029 | static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, | ||||
1030 | llvm::APSInt &Size) { | ||||
1031 | EnterExpressionEvaluationContext ContextRAII( | ||||
1032 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); | ||||
1033 | |||||
1034 | DeclarationName Value = S.PP.getIdentifierInfo("value"); | ||||
1035 | LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); | ||||
1036 | |||||
1037 | // Form template argument list for tuple_size<T>. | ||||
1038 | TemplateArgumentListInfo Args(Loc, Loc); | ||||
1039 | Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); | ||||
1040 | |||||
1041 | // If there's no tuple_size specialization or the lookup of 'value' is empty, | ||||
1042 | // it's not tuple-like. | ||||
1043 | if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || | ||||
1044 | R.empty()) | ||||
1045 | return IsTupleLike::NotTupleLike; | ||||
1046 | |||||
1047 | // If we get this far, we've committed to the tuple interpretation, but | ||||
1048 | // we can still fail if there actually isn't a usable ::value. | ||||
1049 | |||||
1050 | struct ICEDiagnoser : Sema::VerifyICEDiagnoser { | ||||
1051 | LookupResult &R; | ||||
1052 | TemplateArgumentListInfo &Args; | ||||
1053 | ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) | ||||
1054 | : R(R), Args(Args) {} | ||||
1055 | void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { | ||||
1056 | S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) | ||||
1057 | << printTemplateArgs(S.Context.getPrintingPolicy(), Args); | ||||
1058 | } | ||||
1059 | } Diagnoser(R, Args); | ||||
1060 | |||||
1061 | ExprResult E = | ||||
1062 | S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); | ||||
1063 | if (E.isInvalid()) | ||||
1064 | return IsTupleLike::Error; | ||||
1065 | |||||
1066 | E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); | ||||
1067 | if (E.isInvalid()) | ||||
1068 | return IsTupleLike::Error; | ||||
1069 | |||||
1070 | return IsTupleLike::TupleLike; | ||||
1071 | } | ||||
1072 | |||||
1073 | /// \return std::tuple_element<I, T>::type. | ||||
1074 | static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, | ||||
1075 | unsigned I, QualType T) { | ||||
1076 | // Form template argument list for tuple_element<I, T>. | ||||
1077 | TemplateArgumentListInfo Args(Loc, Loc); | ||||
1078 | Args.addArgument( | ||||
1079 | getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); | ||||
1080 | Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); | ||||
1081 | |||||
1082 | DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); | ||||
1083 | LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); | ||||
1084 | if (lookupStdTypeTraitMember( | ||||
1085 | S, R, Loc, "tuple_element", Args, | ||||
1086 | diag::err_decomp_decl_std_tuple_element_not_specialized)) | ||||
1087 | return QualType(); | ||||
1088 | |||||
1089 | auto *TD = R.getAsSingle<TypeDecl>(); | ||||
1090 | if (!TD) { | ||||
1091 | R.suppressDiagnostics(); | ||||
1092 | S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) | ||||
1093 | << printTemplateArgs(S.Context.getPrintingPolicy(), Args); | ||||
1094 | if (!R.empty()) | ||||
1095 | S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); | ||||
1096 | return QualType(); | ||||
1097 | } | ||||
1098 | |||||
1099 | return S.Context.getTypeDeclType(TD); | ||||
1100 | } | ||||
1101 | |||||
1102 | namespace { | ||||
1103 | struct BindingDiagnosticTrap { | ||||
1104 | Sema &S; | ||||
1105 | DiagnosticErrorTrap Trap; | ||||
1106 | BindingDecl *BD; | ||||
1107 | |||||
1108 | BindingDiagnosticTrap(Sema &S, BindingDecl *BD) | ||||
1109 | : S(S), Trap(S.Diags), BD(BD) {} | ||||
1110 | ~BindingDiagnosticTrap() { | ||||
1111 | if (Trap.hasErrorOccurred()) | ||||
1112 | S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; | ||||
1113 | } | ||||
1114 | }; | ||||
1115 | } | ||||
1116 | |||||
1117 | static bool checkTupleLikeDecomposition(Sema &S, | ||||
1118 | ArrayRef<BindingDecl *> Bindings, | ||||
1119 | VarDecl *Src, QualType DecompType, | ||||
1120 | const llvm::APSInt &TupleSize) { | ||||
1121 | if ((int64_t)Bindings.size() != TupleSize) { | ||||
1122 | S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) | ||||
1123 | << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) | ||||
1124 | << (TupleSize < Bindings.size()); | ||||
1125 | return true; | ||||
1126 | } | ||||
1127 | |||||
1128 | if (Bindings.empty()) | ||||
1129 | return false; | ||||
1130 | |||||
1131 | DeclarationName GetDN = S.PP.getIdentifierInfo("get"); | ||||
1132 | |||||
1133 | // [dcl.decomp]p3: | ||||
1134 | // The unqualified-id get is looked up in the scope of E by class member | ||||
1135 | // access lookup ... | ||||
1136 | LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); | ||||
1137 | bool UseMemberGet = false; | ||||
1138 | if (S.isCompleteType(Src->getLocation(), DecompType)) { | ||||
1139 | if (auto *RD = DecompType->getAsCXXRecordDecl()) | ||||
1140 | S.LookupQualifiedName(MemberGet, RD); | ||||
1141 | if (MemberGet.isAmbiguous()) | ||||
1142 | return true; | ||||
1143 | // ... and if that finds at least one declaration that is a function | ||||
1144 | // template whose first template parameter is a non-type parameter ... | ||||
1145 | for (NamedDecl *D : MemberGet) { | ||||
1146 | if (FunctionTemplateDecl *FTD = | ||||
1147 | dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { | ||||
1148 | TemplateParameterList *TPL = FTD->getTemplateParameters(); | ||||
1149 | if (TPL->size() != 0 && | ||||
1150 | isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { | ||||
1151 | // ... the initializer is e.get<i>(). | ||||
1152 | UseMemberGet = true; | ||||
1153 | break; | ||||
1154 | } | ||||
1155 | } | ||||
1156 | } | ||||
1157 | } | ||||
1158 | |||||
1159 | unsigned I = 0; | ||||
1160 | for (auto *B : Bindings) { | ||||
1161 | BindingDiagnosticTrap Trap(S, B); | ||||
1162 | SourceLocation Loc = B->getLocation(); | ||||
1163 | |||||
1164 | ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); | ||||
1165 | if (E.isInvalid()) | ||||
1166 | return true; | ||||
1167 | |||||
1168 | // e is an lvalue if the type of the entity is an lvalue reference and | ||||
1169 | // an xvalue otherwise | ||||
1170 | if (!Src->getType()->isLValueReferenceType()) | ||||
1171 | E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, | ||||
1172 | E.get(), nullptr, VK_XValue); | ||||
1173 | |||||
1174 | TemplateArgumentListInfo Args(Loc, Loc); | ||||
1175 | Args.addArgument( | ||||
1176 | getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); | ||||
1177 | |||||
1178 | if (UseMemberGet) { | ||||
1179 | // if [lookup of member get] finds at least one declaration, the | ||||
1180 | // initializer is e.get<i-1>(). | ||||
1181 | E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, | ||||
1182 | CXXScopeSpec(), SourceLocation(), nullptr, | ||||
1183 | MemberGet, &Args, nullptr); | ||||
1184 | if (E.isInvalid()) | ||||
1185 | return true; | ||||
1186 | |||||
1187 | E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); | ||||
1188 | } else { | ||||
1189 | // Otherwise, the initializer is get<i-1>(e), where get is looked up | ||||
1190 | // in the associated namespaces. | ||||
1191 | Expr *Get = UnresolvedLookupExpr::Create( | ||||
1192 | S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), | ||||
1193 | DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, | ||||
1194 | UnresolvedSetIterator(), UnresolvedSetIterator()); | ||||
1195 | |||||
1196 | Expr *Arg = E.get(); | ||||
1197 | E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); | ||||
1198 | } | ||||
1199 | if (E.isInvalid()) | ||||
1200 | return true; | ||||
1201 | Expr *Init = E.get(); | ||||
1202 | |||||
1203 | // Given the type T designated by std::tuple_element<i - 1, E>::type, | ||||
1204 | QualType T = getTupleLikeElementType(S, Loc, I, DecompType); | ||||
1205 | if (T.isNull()) | ||||
1206 | return true; | ||||
1207 | |||||
1208 | // each vi is a variable of type "reference to T" initialized with the | ||||
1209 | // initializer, where the reference is an lvalue reference if the | ||||
1210 | // initializer is an lvalue and an rvalue reference otherwise | ||||
1211 | QualType RefType = | ||||
1212 | S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); | ||||
1213 | if (RefType.isNull()) | ||||
1214 | return true; | ||||
1215 | auto *RefVD = VarDecl::Create( | ||||
1216 | S.Context, Src->getDeclContext(), Loc, Loc, | ||||
1217 | B->getDeclName().getAsIdentifierInfo(), RefType, | ||||
1218 | S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); | ||||
1219 | RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); | ||||
1220 | RefVD->setTSCSpec(Src->getTSCSpec()); | ||||
1221 | RefVD->setImplicit(); | ||||
1222 | if (Src->isInlineSpecified()) | ||||
1223 | RefVD->setInlineSpecified(); | ||||
1224 | RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); | ||||
1225 | |||||
1226 | InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); | ||||
1227 | InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); | ||||
1228 | InitializationSequence Seq(S, Entity, Kind, Init); | ||||
1229 | E = Seq.Perform(S, Entity, Kind, Init); | ||||
1230 | if (E.isInvalid()) | ||||
1231 | return true; | ||||
1232 | E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); | ||||
1233 | if (E.isInvalid()) | ||||
1234 | return true; | ||||
1235 | RefVD->setInit(E.get()); | ||||
1236 | if (!E.get()->isValueDependent()) | ||||
1237 | RefVD->checkInitIsICE(); | ||||
1238 | |||||
1239 | E = S.BuildDeclarationNameExpr(CXXScopeSpec(), | ||||
1240 | DeclarationNameInfo(B->getDeclName(), Loc), | ||||
1241 | RefVD); | ||||
1242 | if (E.isInvalid()) | ||||
1243 | return true; | ||||
1244 | |||||
1245 | B->setBinding(T, E.get()); | ||||
1246 | I++; | ||||
1247 | } | ||||
1248 | |||||
1249 | return false; | ||||
1250 | } | ||||
1251 | |||||
1252 | /// Find the base class to decompose in a built-in decomposition of a class type. | ||||
1253 | /// This base class search is, unfortunately, not quite like any other that we | ||||
1254 | /// perform anywhere else in C++. | ||||
1255 | static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, | ||||
1256 | const CXXRecordDecl *RD, | ||||
1257 | CXXCastPath &BasePath) { | ||||
1258 | auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, | ||||
1259 | CXXBasePath &Path) { | ||||
1260 | return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); | ||||
1261 | }; | ||||
1262 | |||||
1263 | const CXXRecordDecl *ClassWithFields = nullptr; | ||||
1264 | AccessSpecifier AS = AS_public; | ||||
1265 | if (RD->hasDirectFields()) | ||||
1266 | // [dcl.decomp]p4: | ||||
1267 | // Otherwise, all of E's non-static data members shall be public direct | ||||
1268 | // members of E ... | ||||
1269 | ClassWithFields = RD; | ||||
1270 | else { | ||||
1271 | // ... or of ... | ||||
1272 | CXXBasePaths Paths; | ||||
1273 | Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); | ||||
1274 | if (!RD->lookupInBases(BaseHasFields, Paths)) { | ||||
1275 | // If no classes have fields, just decompose RD itself. (This will work | ||||
1276 | // if and only if zero bindings were provided.) | ||||
1277 | return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); | ||||
1278 | } | ||||
1279 | |||||
1280 | CXXBasePath *BestPath = nullptr; | ||||
1281 | for (auto &P : Paths) { | ||||
1282 | if (!BestPath) | ||||
1283 | BestPath = &P; | ||||
1284 | else if (!S.Context.hasSameType(P.back().Base->getType(), | ||||
1285 | BestPath->back().Base->getType())) { | ||||
1286 | // ... the same ... | ||||
1287 | S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) | ||||
1288 | << false << RD << BestPath->back().Base->getType() | ||||
1289 | << P.back().Base->getType(); | ||||
1290 | return DeclAccessPair(); | ||||
1291 | } else if (P.Access < BestPath->Access) { | ||||
1292 | BestPath = &P; | ||||
1293 | } | ||||
1294 | } | ||||
1295 | |||||
1296 | // ... unambiguous ... | ||||
1297 | QualType BaseType = BestPath->back().Base->getType(); | ||||
1298 | if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { | ||||
1299 | S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) | ||||
1300 | << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); | ||||
1301 | return DeclAccessPair(); | ||||
1302 | } | ||||
1303 | |||||
1304 | // ... [accessible, implied by other rules] base class of E. | ||||
1305 | S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), | ||||
1306 | *BestPath, diag::err_decomp_decl_inaccessible_base); | ||||
1307 | AS = BestPath->Access; | ||||
1308 | |||||
1309 | ClassWithFields = BaseType->getAsCXXRecordDecl(); | ||||
1310 | S.BuildBasePathArray(Paths, BasePath); | ||||
1311 | } | ||||
1312 | |||||
1313 | // The above search did not check whether the selected class itself has base | ||||
1314 | // classes with fields, so check that now. | ||||
1315 | CXXBasePaths Paths; | ||||
1316 | if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { | ||||
1317 | S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) | ||||
1318 | << (ClassWithFields == RD) << RD << ClassWithFields | ||||
1319 | << Paths.front().back().Base->getType(); | ||||
1320 | return DeclAccessPair(); | ||||
1321 | } | ||||
1322 | |||||
1323 | return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); | ||||
1324 | } | ||||
1325 | |||||
1326 | static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, | ||||
1327 | ValueDecl *Src, QualType DecompType, | ||||
1328 | const CXXRecordDecl *OrigRD) { | ||||
1329 | if (S.RequireCompleteType(Src->getLocation(), DecompType, | ||||
1330 | diag::err_incomplete_type)) | ||||
1331 | return true; | ||||
1332 | |||||
1333 | CXXCastPath BasePath; | ||||
1334 | DeclAccessPair BasePair = | ||||
1335 | findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); | ||||
1336 | const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); | ||||
1337 | if (!RD) | ||||
1338 | return true; | ||||
1339 | QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), | ||||
1340 | DecompType.getQualifiers()); | ||||
1341 | |||||
1342 | auto DiagnoseBadNumberOfBindings = [&]() -> bool { | ||||
1343 | unsigned NumFields = | ||||
1344 | std::count_if(RD->field_begin(), RD->field_end(), | ||||
1345 | [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); | ||||
1346 | assert(Bindings.size() != NumFields)((Bindings.size() != NumFields) ? static_cast<void> (0) : __assert_fail ("Bindings.size() != NumFields", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 1346, __PRETTY_FUNCTION__)); | ||||
1347 | S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) | ||||
1348 | << DecompType << (unsigned)Bindings.size() << NumFields | ||||
1349 | << (NumFields < Bindings.size()); | ||||
1350 | return true; | ||||
1351 | }; | ||||
1352 | |||||
1353 | // all of E's non-static data members shall be [...] well-formed | ||||
1354 | // when named as e.name in the context of the structured binding, | ||||
1355 | // E shall not have an anonymous union member, ... | ||||
1356 | unsigned I = 0; | ||||
1357 | for (auto *FD : RD->fields()) { | ||||
1358 | if (FD->isUnnamedBitfield()) | ||||
1359 | continue; | ||||
1360 | |||||
1361 | if (FD->isAnonymousStructOrUnion()) { | ||||
1362 | S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) | ||||
1363 | << DecompType << FD->getType()->isUnionType(); | ||||
1364 | S.Diag(FD->getLocation(), diag::note_declared_at); | ||||
1365 | return true; | ||||
1366 | } | ||||
1367 | |||||
1368 | // We have a real field to bind. | ||||
1369 | if (I >= Bindings.size()) | ||||
1370 | return DiagnoseBadNumberOfBindings(); | ||||
1371 | auto *B = Bindings[I++]; | ||||
1372 | SourceLocation Loc = B->getLocation(); | ||||
1373 | |||||
1374 | // The field must be accessible in the context of the structured binding. | ||||
1375 | // We already checked that the base class is accessible. | ||||
1376 | // FIXME: Add 'const' to AccessedEntity's classes so we can remove the | ||||
1377 | // const_cast here. | ||||
1378 | S.CheckStructuredBindingMemberAccess( | ||||
1379 | Loc, const_cast<CXXRecordDecl *>(OrigRD), | ||||
1380 | DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( | ||||
1381 | BasePair.getAccess(), FD->getAccess()))); | ||||
1382 | |||||
1383 | // Initialize the binding to Src.FD. | ||||
1384 | ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); | ||||
1385 | if (E.isInvalid()) | ||||
1386 | return true; | ||||
1387 | E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, | ||||
1388 | VK_LValue, &BasePath); | ||||
1389 | if (E.isInvalid()) | ||||
1390 | return true; | ||||
1391 | E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, | ||||
1392 | CXXScopeSpec(), FD, | ||||
1393 | DeclAccessPair::make(FD, FD->getAccess()), | ||||
1394 | DeclarationNameInfo(FD->getDeclName(), Loc)); | ||||
1395 | if (E.isInvalid()) | ||||
1396 | return true; | ||||
1397 | |||||
1398 | // If the type of the member is T, the referenced type is cv T, where cv is | ||||
1399 | // the cv-qualification of the decomposition expression. | ||||
1400 | // | ||||
1401 | // FIXME: We resolve a defect here: if the field is mutable, we do not add | ||||
1402 | // 'const' to the type of the field. | ||||
1403 | Qualifiers Q = DecompType.getQualifiers(); | ||||
1404 | if (FD->isMutable()) | ||||
1405 | Q.removeConst(); | ||||
1406 | B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); | ||||
1407 | } | ||||
1408 | |||||
1409 | if (I != Bindings.size()) | ||||
1410 | return DiagnoseBadNumberOfBindings(); | ||||
1411 | |||||
1412 | return false; | ||||
1413 | } | ||||
1414 | |||||
1415 | void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { | ||||
1416 | QualType DecompType = DD->getType(); | ||||
1417 | |||||
1418 | // If the type of the decomposition is dependent, then so is the type of | ||||
1419 | // each binding. | ||||
1420 | if (DecompType->isDependentType()) { | ||||
1421 | for (auto *B : DD->bindings()) | ||||
1422 | B->setType(Context.DependentTy); | ||||
1423 | return; | ||||
1424 | } | ||||
1425 | |||||
1426 | DecompType = DecompType.getNonReferenceType(); | ||||
1427 | ArrayRef<BindingDecl*> Bindings = DD->bindings(); | ||||
1428 | |||||
1429 | // C++1z [dcl.decomp]/2: | ||||
1430 | // If E is an array type [...] | ||||
1431 | // As an extension, we also support decomposition of built-in complex and | ||||
1432 | // vector types. | ||||
1433 | if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { | ||||
1434 | if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) | ||||
1435 | DD->setInvalidDecl(); | ||||
1436 | return; | ||||
1437 | } | ||||
1438 | if (auto *VT = DecompType->getAs<VectorType>()) { | ||||
1439 | if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) | ||||
1440 | DD->setInvalidDecl(); | ||||
1441 | return; | ||||
1442 | } | ||||
1443 | if (auto *CT = DecompType->getAs<ComplexType>()) { | ||||
1444 | if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) | ||||
1445 | DD->setInvalidDecl(); | ||||
1446 | return; | ||||
1447 | } | ||||
1448 | |||||
1449 | // C++1z [dcl.decomp]/3: | ||||
1450 | // if the expression std::tuple_size<E>::value is a well-formed integral | ||||
1451 | // constant expression, [...] | ||||
1452 | llvm::APSInt TupleSize(32); | ||||
1453 | switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { | ||||
1454 | case IsTupleLike::Error: | ||||
1455 | DD->setInvalidDecl(); | ||||
1456 | return; | ||||
1457 | |||||
1458 | case IsTupleLike::TupleLike: | ||||
1459 | if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) | ||||
1460 | DD->setInvalidDecl(); | ||||
1461 | return; | ||||
1462 | |||||
1463 | case IsTupleLike::NotTupleLike: | ||||
1464 | break; | ||||
1465 | } | ||||
1466 | |||||
1467 | // C++1z [dcl.dcl]/8: | ||||
1468 | // [E shall be of array or non-union class type] | ||||
1469 | CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); | ||||
1470 | if (!RD || RD->isUnion()) { | ||||
1471 | Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) | ||||
1472 | << DD << !RD << DecompType; | ||||
1473 | DD->setInvalidDecl(); | ||||
1474 | return; | ||||
1475 | } | ||||
1476 | |||||
1477 | // C++1z [dcl.decomp]/4: | ||||
1478 | // all of E's non-static data members shall be [...] direct members of | ||||
1479 | // E or of the same unambiguous public base class of E, ... | ||||
1480 | if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) | ||||
1481 | DD->setInvalidDecl(); | ||||
1482 | } | ||||
1483 | |||||
1484 | /// Merge the exception specifications of two variable declarations. | ||||
1485 | /// | ||||
1486 | /// This is called when there's a redeclaration of a VarDecl. The function | ||||
1487 | /// checks if the redeclaration might have an exception specification and | ||||
1488 | /// validates compatibility and merges the specs if necessary. | ||||
1489 | void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { | ||||
1490 | // Shortcut if exceptions are disabled. | ||||
1491 | if (!getLangOpts().CXXExceptions) | ||||
1492 | return; | ||||
1493 | |||||
1494 | assert(Context.hasSameType(New->getType(), Old->getType()) &&((Context.hasSameType(New->getType(), Old->getType()) && "Should only be called if types are otherwise the same.") ? static_cast <void> (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 1495, __PRETTY_FUNCTION__)) | ||||
1495 | "Should only be called if types are otherwise the same.")((Context.hasSameType(New->getType(), Old->getType()) && "Should only be called if types are otherwise the same.") ? static_cast <void> (0) : __assert_fail ("Context.hasSameType(New->getType(), Old->getType()) && \"Should only be called if types are otherwise the same.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 1495, __PRETTY_FUNCTION__)); | ||||
1496 | |||||
1497 | QualType NewType = New->getType(); | ||||
1498 | QualType OldType = Old->getType(); | ||||
1499 | |||||
1500 | // We're only interested in pointers and references to functions, as well | ||||
1501 | // as pointers to member functions. | ||||
1502 | if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { | ||||
1503 | NewType = R->getPointeeType(); | ||||
1504 | OldType = OldType->getAs<ReferenceType>()->getPointeeType(); | ||||
1505 | } else if (const PointerType *P = NewType->getAs<PointerType>()) { | ||||
1506 | NewType = P->getPointeeType(); | ||||
1507 | OldType = OldType->getAs<PointerType>()->getPointeeType(); | ||||
1508 | } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { | ||||
1509 | NewType = M->getPointeeType(); | ||||
1510 | OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); | ||||
1511 | } | ||||
1512 | |||||
1513 | if (!NewType->isFunctionProtoType()) | ||||
1514 | return; | ||||
1515 | |||||
1516 | // There's lots of special cases for functions. For function pointers, system | ||||
1517 | // libraries are hopefully not as broken so that we don't need these | ||||
1518 | // workarounds. | ||||
1519 | if (CheckEquivalentExceptionSpec( | ||||
1520 | OldType->getAs<FunctionProtoType>(), Old->getLocation(), | ||||
1521 | NewType->getAs<FunctionProtoType>(), New->getLocation())) { | ||||
1522 | New->setInvalidDecl(); | ||||
1523 | } | ||||
1524 | } | ||||
1525 | |||||
1526 | /// CheckCXXDefaultArguments - Verify that the default arguments for a | ||||
1527 | /// function declaration are well-formed according to C++ | ||||
1528 | /// [dcl.fct.default]. | ||||
1529 | void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { | ||||
1530 | unsigned NumParams = FD->getNumParams(); | ||||
1531 | unsigned p; | ||||
1532 | |||||
1533 | // Find first parameter with a default argument | ||||
1534 | for (p = 0; p < NumParams; ++p) { | ||||
1535 | ParmVarDecl *Param = FD->getParamDecl(p); | ||||
1536 | if (Param->hasDefaultArg()) | ||||
1537 | break; | ||||
1538 | } | ||||
1539 | |||||
1540 | // C++11 [dcl.fct.default]p4: | ||||
1541 | // In a given function declaration, each parameter subsequent to a parameter | ||||
1542 | // with a default argument shall have a default argument supplied in this or | ||||
1543 | // a previous declaration or shall be a function parameter pack. A default | ||||
1544 | // argument shall not be redefined by a later declaration (not even to the | ||||
1545 | // same value). | ||||
1546 | unsigned LastMissingDefaultArg = 0; | ||||
1547 | for (; p < NumParams; ++p) { | ||||
1548 | ParmVarDecl *Param = FD->getParamDecl(p); | ||||
1549 | if (!Param->hasDefaultArg() && !Param->isParameterPack()) { | ||||
1550 | if (Param->isInvalidDecl()) | ||||
1551 | /* We already complained about this parameter. */; | ||||
1552 | else if (Param->getIdentifier()) | ||||
1553 | Diag(Param->getLocation(), | ||||
1554 | diag::err_param_default_argument_missing_name) | ||||
1555 | << Param->getIdentifier(); | ||||
1556 | else | ||||
1557 | Diag(Param->getLocation(), | ||||
1558 | diag::err_param_default_argument_missing); | ||||
1559 | |||||
1560 | LastMissingDefaultArg = p; | ||||
1561 | } | ||||
1562 | } | ||||
1563 | |||||
1564 | if (LastMissingDefaultArg > 0) { | ||||
1565 | // Some default arguments were missing. Clear out all of the | ||||
1566 | // default arguments up to (and including) the last missing | ||||
1567 | // default argument, so that we leave the function parameters | ||||
1568 | // in a semantically valid state. | ||||
1569 | for (p = 0; p <= LastMissingDefaultArg; ++p) { | ||||
1570 | ParmVarDecl *Param = FD->getParamDecl(p); | ||||
1571 | if (Param->hasDefaultArg()) { | ||||
1572 | Param->setDefaultArg(nullptr); | ||||
1573 | } | ||||
1574 | } | ||||
1575 | } | ||||
1576 | } | ||||
1577 | |||||
1578 | /// Check that the given type is a literal type. Issue a diagnostic if not, | ||||
1579 | /// if Kind is Diagnose. | ||||
1580 | /// \return \c true if a problem has been found (and optionally diagnosed). | ||||
1581 | template <typename... Ts> | ||||
1582 | static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, | ||||
1583 | SourceLocation Loc, QualType T, unsigned DiagID, | ||||
1584 | Ts &&...DiagArgs) { | ||||
1585 | if (T->isDependentType()) | ||||
1586 | return false; | ||||
1587 | |||||
1588 | switch (Kind) { | ||||
1589 | case Sema::CheckConstexprKind::Diagnose: | ||||
1590 | return SemaRef.RequireLiteralType(Loc, T, DiagID, | ||||
1591 | std::forward<Ts>(DiagArgs)...); | ||||
1592 | |||||
1593 | case Sema::CheckConstexprKind::CheckValid: | ||||
1594 | return !T->isLiteralType(SemaRef.Context); | ||||
1595 | } | ||||
1596 | |||||
1597 | llvm_unreachable("unknown CheckConstexprKind")::llvm::llvm_unreachable_internal("unknown CheckConstexprKind" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 1597); | ||||
1598 | } | ||||
1599 | |||||
1600 | /// Determine whether a destructor cannot be constexpr due to | ||||
1601 | static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, | ||||
1602 | const CXXDestructorDecl *DD, | ||||
1603 | Sema::CheckConstexprKind Kind) { | ||||
1604 | auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { | ||||
1605 | const CXXRecordDecl *RD = | ||||
1606 | T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); | ||||
1607 | if (!RD || RD->hasConstexprDestructor()) | ||||
1608 | return true; | ||||
1609 | |||||
1610 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | ||||
1611 | SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) | ||||
1612 | << DD->getConstexprKind() << !FD | ||||
1613 | << (FD ? FD->getDeclName() : DeclarationName()) << T; | ||||
1614 | SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) | ||||
1615 | << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; | ||||
1616 | } | ||||
1617 | return false; | ||||
1618 | }; | ||||
1619 | |||||
1620 | const CXXRecordDecl *RD = DD->getParent(); | ||||
1621 | for (const CXXBaseSpecifier &B : RD->bases()) | ||||
1622 | if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) | ||||
1623 | return false; | ||||
1624 | for (const FieldDecl *FD : RD->fields()) | ||||
1625 | if (!Check(FD->getLocation(), FD->getType(), FD)) | ||||
1626 | return false; | ||||
1627 | return true; | ||||
1628 | } | ||||
1629 | |||||
1630 | /// Check whether a function's parameter types are all literal types. If so, | ||||
1631 | /// return true. If not, produce a suitable diagnostic and return false. | ||||
1632 | static bool CheckConstexprParameterTypes(Sema &SemaRef, | ||||
1633 | const FunctionDecl *FD, | ||||
1634 | Sema::CheckConstexprKind Kind) { | ||||
1635 | unsigned ArgIndex = 0; | ||||
1636 | const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); | ||||
1637 | for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), | ||||
1638 | e = FT->param_type_end(); | ||||
1639 | i != e; ++i, ++ArgIndex) { | ||||
1640 | const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); | ||||
1641 | SourceLocation ParamLoc = PD->getLocation(); | ||||
1642 | if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, | ||||
1643 | diag::err_constexpr_non_literal_param, ArgIndex + 1, | ||||
1644 | PD->getSourceRange(), isa<CXXConstructorDecl>(FD), | ||||
1645 | FD->isConsteval())) | ||||
1646 | return false; | ||||
1647 | } | ||||
1648 | return true; | ||||
1649 | } | ||||
1650 | |||||
1651 | /// Check whether a function's return type is a literal type. If so, return | ||||
1652 | /// true. If not, produce a suitable diagnostic and return false. | ||||
1653 | static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, | ||||
1654 | Sema::CheckConstexprKind Kind) { | ||||
1655 | if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), | ||||
1656 | diag::err_constexpr_non_literal_return, | ||||
1657 | FD->isConsteval())) | ||||
1658 | return false; | ||||
1659 | return true; | ||||
1660 | } | ||||
1661 | |||||
1662 | /// Get diagnostic %select index for tag kind for | ||||
1663 | /// record diagnostic message. | ||||
1664 | /// WARNING: Indexes apply to particular diagnostics only! | ||||
1665 | /// | ||||
1666 | /// \returns diagnostic %select index. | ||||
1667 | static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { | ||||
1668 | switch (Tag) { | ||||
1669 | case TTK_Struct: return 0; | ||||
1670 | case TTK_Interface: return 1; | ||||
1671 | case TTK_Class: return 2; | ||||
1672 | default: llvm_unreachable("Invalid tag kind for record diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for record diagnostic!" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 1672); | ||||
1673 | } | ||||
1674 | } | ||||
1675 | |||||
1676 | static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, | ||||
1677 | Stmt *Body, | ||||
1678 | Sema::CheckConstexprKind Kind); | ||||
1679 | |||||
1680 | // Check whether a function declaration satisfies the requirements of a | ||||
1681 | // constexpr function definition or a constexpr constructor definition. If so, | ||||
1682 | // return true. If not, produce appropriate diagnostics (unless asked not to by | ||||
1683 | // Kind) and return false. | ||||
1684 | // | ||||
1685 | // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. | ||||
1686 | bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, | ||||
1687 | CheckConstexprKind Kind) { | ||||
1688 | const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | ||||
1689 | if (MD && MD->isInstance()) { | ||||
1690 | // C++11 [dcl.constexpr]p4: | ||||
1691 | // The definition of a constexpr constructor shall satisfy the following | ||||
1692 | // constraints: | ||||
1693 | // - the class shall not have any virtual base classes; | ||||
1694 | // | ||||
1695 | // FIXME: This only applies to constructors and destructors, not arbitrary | ||||
1696 | // member functions. | ||||
1697 | const CXXRecordDecl *RD = MD->getParent(); | ||||
1698 | if (RD->getNumVBases()) { | ||||
1699 | if (Kind == CheckConstexprKind::CheckValid) | ||||
1700 | return false; | ||||
1701 | |||||
1702 | Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) | ||||
1703 | << isa<CXXConstructorDecl>(NewFD) | ||||
1704 | << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); | ||||
1705 | for (const auto &I : RD->vbases()) | ||||
1706 | Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) | ||||
1707 | << I.getSourceRange(); | ||||
1708 | return false; | ||||
1709 | } | ||||
1710 | } | ||||
1711 | |||||
1712 | if (!isa<CXXConstructorDecl>(NewFD)) { | ||||
1713 | // C++11 [dcl.constexpr]p3: | ||||
1714 | // The definition of a constexpr function shall satisfy the following | ||||
1715 | // constraints: | ||||
1716 | // - it shall not be virtual; (removed in C++20) | ||||
1717 | const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); | ||||
1718 | if (Method && Method->isVirtual()) { | ||||
1719 | if (getLangOpts().CPlusPlus2a) { | ||||
1720 | if (Kind == CheckConstexprKind::Diagnose) | ||||
1721 | Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); | ||||
1722 | } else { | ||||
1723 | if (Kind == CheckConstexprKind::CheckValid) | ||||
1724 | return false; | ||||
1725 | |||||
1726 | Method = Method->getCanonicalDecl(); | ||||
1727 | Diag(Method->getLocation(), diag::err_constexpr_virtual); | ||||
1728 | |||||
1729 | // If it's not obvious why this function is virtual, find an overridden | ||||
1730 | // function which uses the 'virtual' keyword. | ||||
1731 | const CXXMethodDecl *WrittenVirtual = Method; | ||||
1732 | while (!WrittenVirtual->isVirtualAsWritten()) | ||||
1733 | WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); | ||||
1734 | if (WrittenVirtual != Method) | ||||
1735 | Diag(WrittenVirtual->getLocation(), | ||||
1736 | diag::note_overridden_virtual_function); | ||||
1737 | return false; | ||||
1738 | } | ||||
1739 | } | ||||
1740 | |||||
1741 | // - its return type shall be a literal type; | ||||
1742 | if (!CheckConstexprReturnType(*this, NewFD, Kind)) | ||||
1743 | return false; | ||||
1744 | } | ||||
1745 | |||||
1746 | if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { | ||||
1747 | // A destructor can be constexpr only if the defaulted destructor could be; | ||||
1748 | // we don't need to check the members and bases if we already know they all | ||||
1749 | // have constexpr destructors. | ||||
1750 | if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { | ||||
1751 | if (Kind == CheckConstexprKind::CheckValid) | ||||
1752 | return false; | ||||
1753 | if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) | ||||
1754 | return false; | ||||
1755 | } | ||||
1756 | } | ||||
1757 | |||||
1758 | // - each of its parameter types shall be a literal type; | ||||
1759 | if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) | ||||
1760 | return false; | ||||
1761 | |||||
1762 | Stmt *Body = NewFD->getBody(); | ||||
1763 | assert(Body &&((Body && "CheckConstexprFunctionDefinition called on function with no body" ) ? static_cast<void> (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 1764, __PRETTY_FUNCTION__)) | ||||
1764 | "CheckConstexprFunctionDefinition called on function with no body")((Body && "CheckConstexprFunctionDefinition called on function with no body" ) ? static_cast<void> (0) : __assert_fail ("Body && \"CheckConstexprFunctionDefinition called on function with no body\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 1764, __PRETTY_FUNCTION__)); | ||||
1765 | return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); | ||||
1766 | } | ||||
1767 | |||||
1768 | /// Check the given declaration statement is legal within a constexpr function | ||||
1769 | /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. | ||||
1770 | /// | ||||
1771 | /// \return true if the body is OK (maybe only as an extension), false if we | ||||
1772 | /// have diagnosed a problem. | ||||
1773 | static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, | ||||
1774 | DeclStmt *DS, SourceLocation &Cxx1yLoc, | ||||
1775 | Sema::CheckConstexprKind Kind) { | ||||
1776 | // C++11 [dcl.constexpr]p3 and p4: | ||||
1777 | // The definition of a constexpr function(p3) or constructor(p4) [...] shall | ||||
1778 | // contain only | ||||
1779 | for (const auto *DclIt : DS->decls()) { | ||||
1780 | switch (DclIt->getKind()) { | ||||
1781 | case Decl::StaticAssert: | ||||
1782 | case Decl::Using: | ||||
1783 | case Decl::UsingShadow: | ||||
1784 | case Decl::UsingDirective: | ||||
1785 | case Decl::UnresolvedUsingTypename: | ||||
1786 | case Decl::UnresolvedUsingValue: | ||||
1787 | // - static_assert-declarations | ||||
1788 | // - using-declarations, | ||||
1789 | // - using-directives, | ||||
1790 | continue; | ||||
1791 | |||||
1792 | case Decl::Typedef: | ||||
1793 | case Decl::TypeAlias: { | ||||
1794 | // - typedef declarations and alias-declarations that do not define | ||||
1795 | // classes or enumerations, | ||||
1796 | const auto *TN = cast<TypedefNameDecl>(DclIt); | ||||
1797 | if (TN->getUnderlyingType()->isVariablyModifiedType()) { | ||||
1798 | // Don't allow variably-modified types in constexpr functions. | ||||
1799 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | ||||
1800 | TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); | ||||
1801 | SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) | ||||
1802 | << TL.getSourceRange() << TL.getType() | ||||
1803 | << isa<CXXConstructorDecl>(Dcl); | ||||
1804 | } | ||||
1805 | return false; | ||||
1806 | } | ||||
1807 | continue; | ||||
1808 | } | ||||
1809 | |||||
1810 | case Decl::Enum: | ||||
1811 | case Decl::CXXRecord: | ||||
1812 | // C++1y allows types to be defined, not just declared. | ||||
1813 | if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { | ||||
1814 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | ||||
1815 | SemaRef.Diag(DS->getBeginLoc(), | ||||
1816 | SemaRef.getLangOpts().CPlusPlus14 | ||||
1817 | ? diag::warn_cxx11_compat_constexpr_type_definition | ||||
1818 | : diag::ext_constexpr_type_definition) | ||||
1819 | << isa<CXXConstructorDecl>(Dcl); | ||||
1820 | } else if (!SemaRef.getLangOpts().CPlusPlus14) { | ||||
1821 | return false; | ||||
1822 | } | ||||
1823 | } | ||||
1824 | continue; | ||||
1825 | |||||
1826 | case Decl::EnumConstant: | ||||
1827 | case Decl::IndirectField: | ||||
1828 | case Decl::ParmVar: | ||||
1829 | // These can only appear with other declarations which are banned in | ||||
1830 | // C++11 and permitted in C++1y, so ignore them. | ||||
1831 | continue; | ||||
1832 | |||||
1833 | case Decl::Var: | ||||
1834 | case Decl::Decomposition: { | ||||
1835 | // C++1y [dcl.constexpr]p3 allows anything except: | ||||
1836 | // a definition of a variable of non-literal type or of static or | ||||
1837 | // thread storage duration or [before C++2a] for which no | ||||
1838 | // initialization is performed. | ||||
1839 | const auto *VD = cast<VarDecl>(DclIt); | ||||
1840 | if (VD->isThisDeclarationADefinition()) { | ||||
1841 | if (VD->isStaticLocal()) { | ||||
1842 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | ||||
1843 | SemaRef.Diag(VD->getLocation(), | ||||
1844 | diag::err_constexpr_local_var_static) | ||||
1845 | << isa<CXXConstructorDecl>(Dcl) | ||||
1846 | << (VD->getTLSKind() == VarDecl::TLS_Dynamic); | ||||
1847 | } | ||||
1848 | return false; | ||||
1849 | } | ||||
1850 | if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), | ||||
1851 | diag::err_constexpr_local_var_non_literal_type, | ||||
1852 | isa<CXXConstructorDecl>(Dcl))) | ||||
1853 | return false; | ||||
1854 | if (!VD->getType()->isDependentType() && | ||||
1855 | !VD->hasInit() && !VD->isCXXForRangeDecl()) { | ||||
1856 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | ||||
1857 | SemaRef.Diag( | ||||
1858 | VD->getLocation(), | ||||
1859 | SemaRef.getLangOpts().CPlusPlus2a | ||||
1860 | ? diag::warn_cxx17_compat_constexpr_local_var_no_init | ||||
1861 | : diag::ext_constexpr_local_var_no_init) | ||||
1862 | << isa<CXXConstructorDecl>(Dcl); | ||||
1863 | } else if (!SemaRef.getLangOpts().CPlusPlus2a) { | ||||
1864 | return false; | ||||
1865 | } | ||||
1866 | continue; | ||||
1867 | } | ||||
1868 | } | ||||
1869 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | ||||
1870 | SemaRef.Diag(VD->getLocation(), | ||||
1871 | SemaRef.getLangOpts().CPlusPlus14 | ||||
1872 | ? diag::warn_cxx11_compat_constexpr_local_var | ||||
1873 | : diag::ext_constexpr_local_var) | ||||
1874 | << isa<CXXConstructorDecl>(Dcl); | ||||
1875 | } else if (!SemaRef.getLangOpts().CPlusPlus14) { | ||||
1876 | return false; | ||||
1877 | } | ||||
1878 | continue; | ||||
1879 | } | ||||
1880 | |||||
1881 | case Decl::NamespaceAlias: | ||||
1882 | case Decl::Function: | ||||
1883 | // These are disallowed in C++11 and permitted in C++1y. Allow them | ||||
1884 | // everywhere as an extension. | ||||
1885 | if (!Cxx1yLoc.isValid()) | ||||
1886 | Cxx1yLoc = DS->getBeginLoc(); | ||||
1887 | continue; | ||||
1888 | |||||
1889 | default: | ||||
1890 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | ||||
1891 | SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) | ||||
1892 | << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); | ||||
1893 | } | ||||
1894 | return false; | ||||
1895 | } | ||||
1896 | } | ||||
1897 | |||||
1898 | return true; | ||||
1899 | } | ||||
1900 | |||||
1901 | /// Check that the given field is initialized within a constexpr constructor. | ||||
1902 | /// | ||||
1903 | /// \param Dcl The constexpr constructor being checked. | ||||
1904 | /// \param Field The field being checked. This may be a member of an anonymous | ||||
1905 | /// struct or union nested within the class being checked. | ||||
1906 | /// \param Inits All declarations, including anonymous struct/union members and | ||||
1907 | /// indirect members, for which any initialization was provided. | ||||
1908 | /// \param Diagnosed Whether we've emitted the error message yet. Used to attach | ||||
1909 | /// multiple notes for different members to the same error. | ||||
1910 | /// \param Kind Whether we're diagnosing a constructor as written or determining | ||||
1911 | /// whether the formal requirements are satisfied. | ||||
1912 | /// \return \c false if we're checking for validity and the constructor does | ||||
1913 | /// not satisfy the requirements on a constexpr constructor. | ||||
1914 | static bool CheckConstexprCtorInitializer(Sema &SemaRef, | ||||
1915 | const FunctionDecl *Dcl, | ||||
1916 | FieldDecl *Field, | ||||
1917 | llvm::SmallSet<Decl*, 16> &Inits, | ||||
1918 | bool &Diagnosed, | ||||
1919 | Sema::CheckConstexprKind Kind) { | ||||
1920 | // In C++20 onwards, there's nothing to check for validity. | ||||
1921 | if (Kind == Sema::CheckConstexprKind::CheckValid && | ||||
1922 | SemaRef.getLangOpts().CPlusPlus2a) | ||||
1923 | return true; | ||||
1924 | |||||
1925 | if (Field->isInvalidDecl()) | ||||
1926 | return true; | ||||
1927 | |||||
1928 | if (Field->isUnnamedBitfield()) | ||||
1929 | return true; | ||||
1930 | |||||
1931 | // Anonymous unions with no variant members and empty anonymous structs do not | ||||
1932 | // need to be explicitly initialized. FIXME: Anonymous structs that contain no | ||||
1933 | // indirect fields don't need initializing. | ||||
1934 | if (Field->isAnonymousStructOrUnion() && | ||||
1935 | (Field->getType()->isUnionType() | ||||
1936 | ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() | ||||
1937 | : Field->getType()->getAsCXXRecordDecl()->isEmpty())) | ||||
1938 | return true; | ||||
1939 | |||||
1940 | if (!Inits.count(Field)) { | ||||
1941 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | ||||
1942 | if (!Diagnosed) { | ||||
1943 | SemaRef.Diag(Dcl->getLocation(), | ||||
1944 | SemaRef.getLangOpts().CPlusPlus2a | ||||
1945 | ? diag::warn_cxx17_compat_constexpr_ctor_missing_init | ||||
1946 | : diag::ext_constexpr_ctor_missing_init); | ||||
1947 | Diagnosed = true; | ||||
1948 | } | ||||
1949 | SemaRef.Diag(Field->getLocation(), | ||||
1950 | diag::note_constexpr_ctor_missing_init); | ||||
1951 | } else if (!SemaRef.getLangOpts().CPlusPlus2a) { | ||||
1952 | return false; | ||||
1953 | } | ||||
1954 | } else if (Field->isAnonymousStructOrUnion()) { | ||||
1955 | const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); | ||||
1956 | for (auto *I : RD->fields()) | ||||
1957 | // If an anonymous union contains an anonymous struct of which any member | ||||
1958 | // is initialized, all members must be initialized. | ||||
1959 | if (!RD->isUnion() || Inits.count(I)) | ||||
1960 | if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, | ||||
1961 | Kind)) | ||||
1962 | return false; | ||||
1963 | } | ||||
1964 | return true; | ||||
1965 | } | ||||
1966 | |||||
1967 | /// Check the provided statement is allowed in a constexpr function | ||||
1968 | /// definition. | ||||
1969 | static bool | ||||
1970 | CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, | ||||
1971 | SmallVectorImpl<SourceLocation> &ReturnStmts, | ||||
1972 | SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, | ||||
1973 | Sema::CheckConstexprKind Kind) { | ||||
1974 | // - its function-body shall be [...] a compound-statement that contains only | ||||
1975 | switch (S->getStmtClass()) { | ||||
1976 | case Stmt::NullStmtClass: | ||||
1977 | // - null statements, | ||||
1978 | return true; | ||||
1979 | |||||
1980 | case Stmt::DeclStmtClass: | ||||
1981 | // - static_assert-declarations | ||||
1982 | // - using-declarations, | ||||
1983 | // - using-directives, | ||||
1984 | // - typedef declarations and alias-declarations that do not define | ||||
1985 | // classes or enumerations, | ||||
1986 | if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) | ||||
1987 | return false; | ||||
1988 | return true; | ||||
1989 | |||||
1990 | case Stmt::ReturnStmtClass: | ||||
1991 | // - and exactly one return statement; | ||||
1992 | if (isa<CXXConstructorDecl>(Dcl)) { | ||||
1993 | // C++1y allows return statements in constexpr constructors. | ||||
1994 | if (!Cxx1yLoc.isValid()) | ||||
1995 | Cxx1yLoc = S->getBeginLoc(); | ||||
1996 | return true; | ||||
1997 | } | ||||
1998 | |||||
1999 | ReturnStmts.push_back(S->getBeginLoc()); | ||||
2000 | return true; | ||||
2001 | |||||
2002 | case Stmt::CompoundStmtClass: { | ||||
2003 | // C++1y allows compound-statements. | ||||
2004 | if (!Cxx1yLoc.isValid()) | ||||
2005 | Cxx1yLoc = S->getBeginLoc(); | ||||
2006 | |||||
2007 | CompoundStmt *CompStmt = cast<CompoundStmt>(S); | ||||
2008 | for (auto *BodyIt : CompStmt->body()) { | ||||
2009 | if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, | ||||
2010 | Cxx1yLoc, Cxx2aLoc, Kind)) | ||||
2011 | return false; | ||||
2012 | } | ||||
2013 | return true; | ||||
2014 | } | ||||
2015 | |||||
2016 | case Stmt::AttributedStmtClass: | ||||
2017 | if (!Cxx1yLoc.isValid()) | ||||
2018 | Cxx1yLoc = S->getBeginLoc(); | ||||
2019 | return true; | ||||
2020 | |||||
2021 | case Stmt::IfStmtClass: { | ||||
2022 | // C++1y allows if-statements. | ||||
2023 | if (!Cxx1yLoc.isValid()) | ||||
2024 | Cxx1yLoc = S->getBeginLoc(); | ||||
2025 | |||||
2026 | IfStmt *If = cast<IfStmt>(S); | ||||
2027 | if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, | ||||
2028 | Cxx1yLoc, Cxx2aLoc, Kind)) | ||||
2029 | return false; | ||||
2030 | if (If->getElse() && | ||||
2031 | !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, | ||||
2032 | Cxx1yLoc, Cxx2aLoc, Kind)) | ||||
2033 | return false; | ||||
2034 | return true; | ||||
2035 | } | ||||
2036 | |||||
2037 | case Stmt::WhileStmtClass: | ||||
2038 | case Stmt::DoStmtClass: | ||||
2039 | case Stmt::ForStmtClass: | ||||
2040 | case Stmt::CXXForRangeStmtClass: | ||||
2041 | case Stmt::ContinueStmtClass: | ||||
2042 | // C++1y allows all of these. We don't allow them as extensions in C++11, | ||||
2043 | // because they don't make sense without variable mutation. | ||||
2044 | if (!SemaRef.getLangOpts().CPlusPlus14) | ||||
2045 | break; | ||||
2046 | if (!Cxx1yLoc.isValid()) | ||||
2047 | Cxx1yLoc = S->getBeginLoc(); | ||||
2048 | for (Stmt *SubStmt : S->children()) | ||||
2049 | if (SubStmt && | ||||
2050 | !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, | ||||
2051 | Cxx1yLoc, Cxx2aLoc, Kind)) | ||||
2052 | return false; | ||||
2053 | return true; | ||||
2054 | |||||
2055 | case Stmt::SwitchStmtClass: | ||||
2056 | case Stmt::CaseStmtClass: | ||||
2057 | case Stmt::DefaultStmtClass: | ||||
2058 | case Stmt::BreakStmtClass: | ||||
2059 | // C++1y allows switch-statements, and since they don't need variable | ||||
2060 | // mutation, we can reasonably allow them in C++11 as an extension. | ||||
2061 | if (!Cxx1yLoc.isValid()) | ||||
2062 | Cxx1yLoc = S->getBeginLoc(); | ||||
2063 | for (Stmt *SubStmt : S->children()) | ||||
2064 | if (SubStmt && | ||||
2065 | !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, | ||||
2066 | Cxx1yLoc, Cxx2aLoc, Kind)) | ||||
2067 | return false; | ||||
2068 | return true; | ||||
2069 | |||||
2070 | case Stmt::GCCAsmStmtClass: | ||||
2071 | case Stmt::MSAsmStmtClass: | ||||
2072 | // C++2a allows inline assembly statements. | ||||
2073 | case Stmt::CXXTryStmtClass: | ||||
2074 | if (Cxx2aLoc.isInvalid()) | ||||
2075 | Cxx2aLoc = S->getBeginLoc(); | ||||
2076 | for (Stmt *SubStmt : S->children()) { | ||||
2077 | if (SubStmt && | ||||
2078 | !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, | ||||
2079 | Cxx1yLoc, Cxx2aLoc, Kind)) | ||||
2080 | return false; | ||||
2081 | } | ||||
2082 | return true; | ||||
2083 | |||||
2084 | case Stmt::CXXCatchStmtClass: | ||||
2085 | // Do not bother checking the language mode (already covered by the | ||||
2086 | // try block check). | ||||
2087 | if (!CheckConstexprFunctionStmt(SemaRef, Dcl, | ||||
2088 | cast<CXXCatchStmt>(S)->getHandlerBlock(), | ||||
2089 | ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) | ||||
2090 | return false; | ||||
2091 | return true; | ||||
2092 | |||||
2093 | default: | ||||
2094 | if (!isa<Expr>(S)) | ||||
2095 | break; | ||||
2096 | |||||
2097 | // C++1y allows expression-statements. | ||||
2098 | if (!Cxx1yLoc.isValid()) | ||||
2099 | Cxx1yLoc = S->getBeginLoc(); | ||||
2100 | return true; | ||||
2101 | } | ||||
2102 | |||||
2103 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | ||||
2104 | SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) | ||||
2105 | << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); | ||||
2106 | } | ||||
2107 | return false; | ||||
2108 | } | ||||
2109 | |||||
2110 | /// Check the body for the given constexpr function declaration only contains | ||||
2111 | /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. | ||||
2112 | /// | ||||
2113 | /// \return true if the body is OK, false if we have found or diagnosed a | ||||
2114 | /// problem. | ||||
2115 | static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, | ||||
2116 | Stmt *Body, | ||||
2117 | Sema::CheckConstexprKind Kind) { | ||||
2118 | SmallVector<SourceLocation, 4> ReturnStmts; | ||||
2119 | |||||
2120 | if (isa<CXXTryStmt>(Body)) { | ||||
2121 | // C++11 [dcl.constexpr]p3: | ||||
2122 | // The definition of a constexpr function shall satisfy the following | ||||
2123 | // constraints: [...] | ||||
2124 | // - its function-body shall be = delete, = default, or a | ||||
2125 | // compound-statement | ||||
2126 | // | ||||
2127 | // C++11 [dcl.constexpr]p4: | ||||
2128 | // In the definition of a constexpr constructor, [...] | ||||
2129 | // - its function-body shall not be a function-try-block; | ||||
2130 | // | ||||
2131 | // This restriction is lifted in C++2a, as long as inner statements also | ||||
2132 | // apply the general constexpr rules. | ||||
2133 | switch (Kind) { | ||||
2134 | case Sema::CheckConstexprKind::CheckValid: | ||||
2135 | if (!SemaRef.getLangOpts().CPlusPlus2a) | ||||
2136 | return false; | ||||
2137 | break; | ||||
2138 | |||||
2139 | case Sema::CheckConstexprKind::Diagnose: | ||||
2140 | SemaRef.Diag(Body->getBeginLoc(), | ||||
2141 | !SemaRef.getLangOpts().CPlusPlus2a | ||||
2142 | ? diag::ext_constexpr_function_try_block_cxx2a | ||||
2143 | : diag::warn_cxx17_compat_constexpr_function_try_block) | ||||
2144 | << isa<CXXConstructorDecl>(Dcl); | ||||
2145 | break; | ||||
2146 | } | ||||
2147 | } | ||||
2148 | |||||
2149 | // - its function-body shall be [...] a compound-statement that contains only | ||||
2150 | // [... list of cases ...] | ||||
2151 | // | ||||
2152 | // Note that walking the children here is enough to properly check for | ||||
2153 | // CompoundStmt and CXXTryStmt body. | ||||
2154 | SourceLocation Cxx1yLoc, Cxx2aLoc; | ||||
2155 | for (Stmt *SubStmt : Body->children()) { | ||||
2156 | if (SubStmt && | ||||
2157 | !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, | ||||
2158 | Cxx1yLoc, Cxx2aLoc, Kind)) | ||||
2159 | return false; | ||||
2160 | } | ||||
2161 | |||||
2162 | if (Kind == Sema::CheckConstexprKind::CheckValid) { | ||||
2163 | // If this is only valid as an extension, report that we don't satisfy the | ||||
2164 | // constraints of the current language. | ||||
2165 | if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) || | ||||
2166 | (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) | ||||
2167 | return false; | ||||
2168 | } else if (Cxx2aLoc.isValid()) { | ||||
2169 | SemaRef.Diag(Cxx2aLoc, | ||||
2170 | SemaRef.getLangOpts().CPlusPlus2a | ||||
2171 | ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt | ||||
2172 | : diag::ext_constexpr_body_invalid_stmt_cxx2a) | ||||
2173 | << isa<CXXConstructorDecl>(Dcl); | ||||
2174 | } else if (Cxx1yLoc.isValid()) { | ||||
2175 | SemaRef.Diag(Cxx1yLoc, | ||||
2176 | SemaRef.getLangOpts().CPlusPlus14 | ||||
2177 | ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt | ||||
2178 | : diag::ext_constexpr_body_invalid_stmt) | ||||
2179 | << isa<CXXConstructorDecl>(Dcl); | ||||
2180 | } | ||||
2181 | |||||
2182 | if (const CXXConstructorDecl *Constructor | ||||
2183 | = dyn_cast<CXXConstructorDecl>(Dcl)) { | ||||
2184 | const CXXRecordDecl *RD = Constructor->getParent(); | ||||
2185 | // DR1359: | ||||
2186 | // - every non-variant non-static data member and base class sub-object | ||||
2187 | // shall be initialized; | ||||
2188 | // DR1460: | ||||
2189 | // - if the class is a union having variant members, exactly one of them | ||||
2190 | // shall be initialized; | ||||
2191 | if (RD->isUnion()) { | ||||
2192 | if (Constructor->getNumCtorInitializers() == 0 && | ||||
2193 | RD->hasVariantMembers()) { | ||||
2194 | if (Kind == Sema::CheckConstexprKind::Diagnose) { | ||||
2195 | SemaRef.Diag( | ||||
2196 | Dcl->getLocation(), | ||||
2197 | SemaRef.getLangOpts().CPlusPlus2a | ||||
2198 | ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init | ||||
2199 | : diag::ext_constexpr_union_ctor_no_init); | ||||
2200 | } else if (!SemaRef.getLangOpts().CPlusPlus2a) { | ||||
2201 | return false; | ||||
2202 | } | ||||
2203 | } | ||||
2204 | } else if (!Constructor->isDependentContext() && | ||||
2205 | !Constructor->isDelegatingConstructor()) { | ||||
2206 | assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases")((RD->getNumVBases() == 0 && "constexpr ctor with virtual bases" ) ? static_cast<void> (0) : __assert_fail ("RD->getNumVBases() == 0 && \"constexpr ctor with virtual bases\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 2206, __PRETTY_FUNCTION__)); | ||||
2207 | |||||
2208 | // Skip detailed checking if we have enough initializers, and we would | ||||
2209 | // allow at most one initializer per member. | ||||
2210 | bool AnyAnonStructUnionMembers = false; | ||||
2211 | unsigned Fields = 0; | ||||
2212 | for (CXXRecordDecl::field_iterator I = RD->field_begin(), | ||||
2213 | E = RD->field_end(); I != E; ++I, ++Fields) { | ||||
2214 | if (I->isAnonymousStructOrUnion()) { | ||||
2215 | AnyAnonStructUnionMembers = true; | ||||
2216 | break; | ||||
2217 | } | ||||
2218 | } | ||||
2219 | // DR1460: | ||||
2220 | // - if the class is a union-like class, but is not a union, for each of | ||||
2221 | // its anonymous union members having variant members, exactly one of | ||||
2222 | // them shall be initialized; | ||||
2223 | if (AnyAnonStructUnionMembers || | ||||
2224 | Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { | ||||
2225 | // Check initialization of non-static data members. Base classes are | ||||
2226 | // always initialized so do not need to be checked. Dependent bases | ||||
2227 | // might not have initializers in the member initializer list. | ||||
2228 | llvm::SmallSet<Decl*, 16> Inits; | ||||
2229 | for (const auto *I: Constructor->inits()) { | ||||
2230 | if (FieldDecl *FD = I->getMember()) | ||||
2231 | Inits.insert(FD); | ||||
2232 | else if (IndirectFieldDecl *ID = I->getIndirectMember()) | ||||
2233 | Inits.insert(ID->chain_begin(), ID->chain_end()); | ||||
2234 | } | ||||
2235 | |||||
2236 | bool Diagnosed = false; | ||||
2237 | for (auto *I : RD->fields()) | ||||
2238 | if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, | ||||
2239 | Kind)) | ||||
2240 | return false; | ||||
2241 | } | ||||
2242 | } | ||||
2243 | } else { | ||||
2244 | if (ReturnStmts.empty()) { | ||||
2245 | // C++1y doesn't require constexpr functions to contain a 'return' | ||||
2246 | // statement. We still do, unless the return type might be void, because | ||||
2247 | // otherwise if there's no return statement, the function cannot | ||||
2248 | // be used in a core constant expression. | ||||
2249 | bool OK = SemaRef.getLangOpts().CPlusPlus14 && | ||||
2250 | (Dcl->getReturnType()->isVoidType() || | ||||
2251 | Dcl->getReturnType()->isDependentType()); | ||||
2252 | switch (Kind) { | ||||
2253 | case Sema::CheckConstexprKind::Diagnose: | ||||
2254 | SemaRef.Diag(Dcl->getLocation(), | ||||
2255 | OK ? diag::warn_cxx11_compat_constexpr_body_no_return | ||||
2256 | : diag::err_constexpr_body_no_return) | ||||
2257 | << Dcl->isConsteval(); | ||||
2258 | if (!OK) | ||||
2259 | return false; | ||||
2260 | break; | ||||
2261 | |||||
2262 | case Sema::CheckConstexprKind::CheckValid: | ||||
2263 | // The formal requirements don't include this rule in C++14, even | ||||
2264 | // though the "must be able to produce a constant expression" rules | ||||
2265 | // still imply it in some cases. | ||||
2266 | if (!SemaRef.getLangOpts().CPlusPlus14) | ||||
2267 | return false; | ||||
2268 | break; | ||||
2269 | } | ||||
2270 | } else if (ReturnStmts.size() > 1) { | ||||
2271 | switch (Kind) { | ||||
2272 | case Sema::CheckConstexprKind::Diagnose: | ||||
2273 | SemaRef.Diag( | ||||
2274 | ReturnStmts.back(), | ||||
2275 | SemaRef.getLangOpts().CPlusPlus14 | ||||
2276 | ? diag::warn_cxx11_compat_constexpr_body_multiple_return | ||||
2277 | : diag::ext_constexpr_body_multiple_return); | ||||
2278 | for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) | ||||
2279 | SemaRef.Diag(ReturnStmts[I], | ||||
2280 | diag::note_constexpr_body_previous_return); | ||||
2281 | break; | ||||
2282 | |||||
2283 | case Sema::CheckConstexprKind::CheckValid: | ||||
2284 | if (!SemaRef.getLangOpts().CPlusPlus14) | ||||
2285 | return false; | ||||
2286 | break; | ||||
2287 | } | ||||
2288 | } | ||||
2289 | } | ||||
2290 | |||||
2291 | // C++11 [dcl.constexpr]p5: | ||||
2292 | // if no function argument values exist such that the function invocation | ||||
2293 | // substitution would produce a constant expression, the program is | ||||
2294 | // ill-formed; no diagnostic required. | ||||
2295 | // C++11 [dcl.constexpr]p3: | ||||
2296 | // - every constructor call and implicit conversion used in initializing the | ||||
2297 | // return value shall be one of those allowed in a constant expression. | ||||
2298 | // C++11 [dcl.constexpr]p4: | ||||
2299 | // - every constructor involved in initializing non-static data members and | ||||
2300 | // base class sub-objects shall be a constexpr constructor. | ||||
2301 | // | ||||
2302 | // Note that this rule is distinct from the "requirements for a constexpr | ||||
2303 | // function", so is not checked in CheckValid mode. | ||||
2304 | SmallVector<PartialDiagnosticAt, 8> Diags; | ||||
2305 | if (Kind == Sema::CheckConstexprKind::Diagnose && | ||||
2306 | !Expr::isPotentialConstantExpr(Dcl, Diags)) { | ||||
2307 | SemaRef.Diag(Dcl->getLocation(), | ||||
2308 | diag::ext_constexpr_function_never_constant_expr) | ||||
2309 | << isa<CXXConstructorDecl>(Dcl); | ||||
2310 | for (size_t I = 0, N = Diags.size(); I != N; ++I) | ||||
2311 | SemaRef.Diag(Diags[I].first, Diags[I].second); | ||||
2312 | // Don't return false here: we allow this for compatibility in | ||||
2313 | // system headers. | ||||
2314 | } | ||||
2315 | |||||
2316 | return true; | ||||
2317 | } | ||||
2318 | |||||
2319 | /// Get the class that is directly named by the current context. This is the | ||||
2320 | /// class for which an unqualified-id in this scope could name a constructor | ||||
2321 | /// or destructor. | ||||
2322 | /// | ||||
2323 | /// If the scope specifier denotes a class, this will be that class. | ||||
2324 | /// If the scope specifier is empty, this will be the class whose | ||||
2325 | /// member-specification we are currently within. Otherwise, there | ||||
2326 | /// is no such class. | ||||
2327 | CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { | ||||
2328 | assert(getLangOpts().CPlusPlus && "No class names in C!")((getLangOpts().CPlusPlus && "No class names in C!") ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 2328, __PRETTY_FUNCTION__)); | ||||
2329 | |||||
2330 | if (SS && SS->isInvalid()) | ||||
2331 | return nullptr; | ||||
2332 | |||||
2333 | if (SS && SS->isNotEmpty()) { | ||||
2334 | DeclContext *DC = computeDeclContext(*SS, true); | ||||
2335 | return dyn_cast_or_null<CXXRecordDecl>(DC); | ||||
2336 | } | ||||
2337 | |||||
2338 | return dyn_cast_or_null<CXXRecordDecl>(CurContext); | ||||
2339 | } | ||||
2340 | |||||
2341 | /// isCurrentClassName - Determine whether the identifier II is the | ||||
2342 | /// name of the class type currently being defined. In the case of | ||||
2343 | /// nested classes, this will only return true if II is the name of | ||||
2344 | /// the innermost class. | ||||
2345 | bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, | ||||
2346 | const CXXScopeSpec *SS) { | ||||
2347 | CXXRecordDecl *CurDecl = getCurrentClass(S, SS); | ||||
2348 | return CurDecl && &II == CurDecl->getIdentifier(); | ||||
2349 | } | ||||
2350 | |||||
2351 | /// Determine whether the identifier II is a typo for the name of | ||||
2352 | /// the class type currently being defined. If so, update it to the identifier | ||||
2353 | /// that should have been used. | ||||
2354 | bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { | ||||
2355 | assert(getLangOpts().CPlusPlus && "No class names in C!")((getLangOpts().CPlusPlus && "No class names in C!") ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No class names in C!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 2355, __PRETTY_FUNCTION__)); | ||||
2356 | |||||
2357 | if (!getLangOpts().SpellChecking) | ||||
2358 | return false; | ||||
2359 | |||||
2360 | CXXRecordDecl *CurDecl; | ||||
2361 | if (SS && SS->isSet() && !SS->isInvalid()) { | ||||
2362 | DeclContext *DC = computeDeclContext(*SS, true); | ||||
2363 | CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); | ||||
2364 | } else | ||||
2365 | CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); | ||||
2366 | |||||
2367 | if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && | ||||
2368 | 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) | ||||
2369 | < II->getLength()) { | ||||
2370 | II = CurDecl->getIdentifier(); | ||||
2371 | return true; | ||||
2372 | } | ||||
2373 | |||||
2374 | return false; | ||||
2375 | } | ||||
2376 | |||||
2377 | /// Determine whether the given class is a base class of the given | ||||
2378 | /// class, including looking at dependent bases. | ||||
2379 | static bool findCircularInheritance(const CXXRecordDecl *Class, | ||||
2380 | const CXXRecordDecl *Current) { | ||||
2381 | SmallVector<const CXXRecordDecl*, 8> Queue; | ||||
2382 | |||||
2383 | Class = Class->getCanonicalDecl(); | ||||
2384 | while (true) { | ||||
2385 | for (const auto &I : Current->bases()) { | ||||
2386 | CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); | ||||
2387 | if (!Base) | ||||
2388 | continue; | ||||
2389 | |||||
2390 | Base = Base->getDefinition(); | ||||
2391 | if (!Base) | ||||
2392 | continue; | ||||
2393 | |||||
2394 | if (Base->getCanonicalDecl() == Class) | ||||
2395 | return true; | ||||
2396 | |||||
2397 | Queue.push_back(Base); | ||||
2398 | } | ||||
2399 | |||||
2400 | if (Queue.empty()) | ||||
2401 | return false; | ||||
2402 | |||||
2403 | Current = Queue.pop_back_val(); | ||||
2404 | } | ||||
2405 | |||||
2406 | return false; | ||||
2407 | } | ||||
2408 | |||||
2409 | /// Check the validity of a C++ base class specifier. | ||||
2410 | /// | ||||
2411 | /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics | ||||
2412 | /// and returns NULL otherwise. | ||||
2413 | CXXBaseSpecifier * | ||||
2414 | Sema::CheckBaseSpecifier(CXXRecordDecl *Class, | ||||
2415 | SourceRange SpecifierRange, | ||||
2416 | bool Virtual, AccessSpecifier Access, | ||||
2417 | TypeSourceInfo *TInfo, | ||||
2418 | SourceLocation EllipsisLoc) { | ||||
2419 | QualType BaseType = TInfo->getType(); | ||||
2420 | |||||
2421 | // C++ [class.union]p1: | ||||
2422 | // A union shall not have base classes. | ||||
2423 | if (Class->isUnion()) { | ||||
2424 | Diag(Class->getLocation(), diag::err_base_clause_on_union) | ||||
2425 | << SpecifierRange; | ||||
2426 | return nullptr; | ||||
2427 | } | ||||
2428 | |||||
2429 | if (EllipsisLoc.isValid() && | ||||
2430 | !TInfo->getType()->containsUnexpandedParameterPack()) { | ||||
2431 | Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) | ||||
2432 | << TInfo->getTypeLoc().getSourceRange(); | ||||
2433 | EllipsisLoc = SourceLocation(); | ||||
2434 | } | ||||
2435 | |||||
2436 | SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); | ||||
2437 | |||||
2438 | if (BaseType->isDependentType()) { | ||||
2439 | // Make sure that we don't have circular inheritance among our dependent | ||||
2440 | // bases. For non-dependent bases, the check for completeness below handles | ||||
2441 | // this. | ||||
2442 | if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { | ||||
2443 | if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || | ||||
2444 | ((BaseDecl = BaseDecl->getDefinition()) && | ||||
2445 | findCircularInheritance(Class, BaseDecl))) { | ||||
2446 | Diag(BaseLoc, diag::err_circular_inheritance) | ||||
2447 | << BaseType << Context.getTypeDeclType(Class); | ||||
2448 | |||||
2449 | if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) | ||||
2450 | Diag(BaseDecl->getLocation(), diag::note_previous_decl) | ||||
2451 | << BaseType; | ||||
2452 | |||||
2453 | return nullptr; | ||||
2454 | } | ||||
2455 | } | ||||
2456 | |||||
2457 | return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, | ||||
2458 | Class->getTagKind() == TTK_Class, | ||||
2459 | Access, TInfo, EllipsisLoc); | ||||
2460 | } | ||||
2461 | |||||
2462 | // Base specifiers must be record types. | ||||
2463 | if (!BaseType->isRecordType()) { | ||||
2464 | Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; | ||||
2465 | return nullptr; | ||||
2466 | } | ||||
2467 | |||||
2468 | // C++ [class.union]p1: | ||||
2469 | // A union shall not be used as a base class. | ||||
2470 | if (BaseType->isUnionType()) { | ||||
2471 | Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; | ||||
2472 | return nullptr; | ||||
2473 | } | ||||
2474 | |||||
2475 | // For the MS ABI, propagate DLL attributes to base class templates. | ||||
2476 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | ||||
2477 | if (Attr *ClassAttr = getDLLAttr(Class)) { | ||||
2478 | if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( | ||||
2479 | BaseType->getAsCXXRecordDecl())) { | ||||
2480 | propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, | ||||
2481 | BaseLoc); | ||||
2482 | } | ||||
2483 | } | ||||
2484 | } | ||||
2485 | |||||
2486 | // C++ [class.derived]p2: | ||||
2487 | // The class-name in a base-specifier shall not be an incompletely | ||||
2488 | // defined class. | ||||
2489 | if (RequireCompleteType(BaseLoc, BaseType, | ||||
2490 | diag::err_incomplete_base_class, SpecifierRange)) { | ||||
2491 | Class->setInvalidDecl(); | ||||
2492 | return nullptr; | ||||
2493 | } | ||||
2494 | |||||
2495 | // If the base class is polymorphic or isn't empty, the new one is/isn't, too. | ||||
2496 | RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); | ||||
2497 | assert(BaseDecl && "Record type has no declaration")((BaseDecl && "Record type has no declaration") ? static_cast <void> (0) : __assert_fail ("BaseDecl && \"Record type has no declaration\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 2497, __PRETTY_FUNCTION__)); | ||||
2498 | BaseDecl = BaseDecl->getDefinition(); | ||||
2499 | assert(BaseDecl && "Base type is not incomplete, but has no definition")((BaseDecl && "Base type is not incomplete, but has no definition" ) ? static_cast<void> (0) : __assert_fail ("BaseDecl && \"Base type is not incomplete, but has no definition\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 2499, __PRETTY_FUNCTION__)); | ||||
2500 | CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); | ||||
2501 | assert(CXXBaseDecl && "Base type is not a C++ type")((CXXBaseDecl && "Base type is not a C++ type") ? static_cast <void> (0) : __assert_fail ("CXXBaseDecl && \"Base type is not a C++ type\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 2501, __PRETTY_FUNCTION__)); | ||||
2502 | |||||
2503 | // Microsoft docs say: | ||||
2504 | // "If a base-class has a code_seg attribute, derived classes must have the | ||||
2505 | // same attribute." | ||||
2506 | const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); | ||||
2507 | const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); | ||||
2508 | if ((DerivedCSA || BaseCSA) && | ||||
2509 | (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { | ||||
2510 | Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); | ||||
2511 | Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) | ||||
2512 | << CXXBaseDecl; | ||||
2513 | return nullptr; | ||||
2514 | } | ||||
2515 | |||||
2516 | // A class which contains a flexible array member is not suitable for use as a | ||||
2517 | // base class: | ||||
2518 | // - If the layout determines that a base comes before another base, | ||||
2519 | // the flexible array member would index into the subsequent base. | ||||
2520 | // - If the layout determines that base comes before the derived class, | ||||
2521 | // the flexible array member would index into the derived class. | ||||
2522 | if (CXXBaseDecl->hasFlexibleArrayMember()) { | ||||
2523 | Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) | ||||
2524 | << CXXBaseDecl->getDeclName(); | ||||
2525 | return nullptr; | ||||
2526 | } | ||||
2527 | |||||
2528 | // C++ [class]p3: | ||||
2529 | // If a class is marked final and it appears as a base-type-specifier in | ||||
2530 | // base-clause, the program is ill-formed. | ||||
2531 | if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { | ||||
2532 | Diag(BaseLoc, diag::err_class_marked_final_used_as_base) | ||||
2533 | << CXXBaseDecl->getDeclName() | ||||
2534 | << FA->isSpelledAsSealed(); | ||||
2535 | Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) | ||||
2536 | << CXXBaseDecl->getDeclName() << FA->getRange(); | ||||
2537 | return nullptr; | ||||
2538 | } | ||||
2539 | |||||
2540 | if (BaseDecl->isInvalidDecl()) | ||||
2541 | Class->setInvalidDecl(); | ||||
2542 | |||||
2543 | // Create the base specifier. | ||||
2544 | return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, | ||||
2545 | Class->getTagKind() == TTK_Class, | ||||
2546 | Access, TInfo, EllipsisLoc); | ||||
2547 | } | ||||
2548 | |||||
2549 | /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is | ||||
2550 | /// one entry in the base class list of a class specifier, for | ||||
2551 | /// example: | ||||
2552 | /// class foo : public bar, virtual private baz { | ||||
2553 | /// 'public bar' and 'virtual private baz' are each base-specifiers. | ||||
2554 | BaseResult | ||||
2555 | Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, | ||||
2556 | ParsedAttributes &Attributes, | ||||
2557 | bool Virtual, AccessSpecifier Access, | ||||
2558 | ParsedType basetype, SourceLocation BaseLoc, | ||||
2559 | SourceLocation EllipsisLoc) { | ||||
2560 | if (!classdecl) | ||||
2561 | return true; | ||||
2562 | |||||
2563 | AdjustDeclIfTemplate(classdecl); | ||||
2564 | CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); | ||||
2565 | if (!Class) | ||||
2566 | return true; | ||||
2567 | |||||
2568 | // We haven't yet attached the base specifiers. | ||||
2569 | Class->setIsParsingBaseSpecifiers(); | ||||
2570 | |||||
2571 | // We do not support any C++11 attributes on base-specifiers yet. | ||||
2572 | // Diagnose any attributes we see. | ||||
2573 | for (const ParsedAttr &AL : Attributes) { | ||||
2574 | if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) | ||||
2575 | continue; | ||||
2576 | Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute | ||||
2577 | ? (unsigned)diag::warn_unknown_attribute_ignored | ||||
2578 | : (unsigned)diag::err_base_specifier_attribute) | ||||
2579 | << AL; | ||||
2580 | } | ||||
2581 | |||||
2582 | TypeSourceInfo *TInfo = nullptr; | ||||
2583 | GetTypeFromParser(basetype, &TInfo); | ||||
2584 | |||||
2585 | if (EllipsisLoc.isInvalid() && | ||||
2586 | DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, | ||||
2587 | UPPC_BaseType)) | ||||
2588 | return true; | ||||
2589 | |||||
2590 | if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, | ||||
2591 | Virtual, Access, TInfo, | ||||
2592 | EllipsisLoc)) | ||||
2593 | return BaseSpec; | ||||
2594 | else | ||||
2595 | Class->setInvalidDecl(); | ||||
2596 | |||||
2597 | return true; | ||||
2598 | } | ||||
2599 | |||||
2600 | /// Use small set to collect indirect bases. As this is only used | ||||
2601 | /// locally, there's no need to abstract the small size parameter. | ||||
2602 | typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; | ||||
2603 | |||||
2604 | /// Recursively add the bases of Type. Don't add Type itself. | ||||
2605 | static void | ||||
2606 | NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, | ||||
2607 | const QualType &Type) | ||||
2608 | { | ||||
2609 | // Even though the incoming type is a base, it might not be | ||||
2610 | // a class -- it could be a template parm, for instance. | ||||
2611 | if (auto Rec = Type->getAs<RecordType>()) { | ||||
2612 | auto Decl = Rec->getAsCXXRecordDecl(); | ||||
2613 | |||||
2614 | // Iterate over its bases. | ||||
2615 | for (const auto &BaseSpec : Decl->bases()) { | ||||
2616 | QualType Base = Context.getCanonicalType(BaseSpec.getType()) | ||||
2617 | .getUnqualifiedType(); | ||||
2618 | if (Set.insert(Base).second) | ||||
2619 | // If we've not already seen it, recurse. | ||||
2620 | NoteIndirectBases(Context, Set, Base); | ||||
2621 | } | ||||
2622 | } | ||||
2623 | } | ||||
2624 | |||||
2625 | /// Performs the actual work of attaching the given base class | ||||
2626 | /// specifiers to a C++ class. | ||||
2627 | bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, | ||||
2628 | MutableArrayRef<CXXBaseSpecifier *> Bases) { | ||||
2629 | if (Bases.empty()) | ||||
2630 | return false; | ||||
2631 | |||||
2632 | // Used to keep track of which base types we have already seen, so | ||||
2633 | // that we can properly diagnose redundant direct base types. Note | ||||
2634 | // that the key is always the unqualified canonical type of the base | ||||
2635 | // class. | ||||
2636 | std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; | ||||
2637 | |||||
2638 | // Used to track indirect bases so we can see if a direct base is | ||||
2639 | // ambiguous. | ||||
2640 | IndirectBaseSet IndirectBaseTypes; | ||||
2641 | |||||
2642 | // Copy non-redundant base specifiers into permanent storage. | ||||
2643 | unsigned NumGoodBases = 0; | ||||
2644 | bool Invalid = false; | ||||
2645 | for (unsigned idx = 0; idx < Bases.size(); ++idx) { | ||||
2646 | QualType NewBaseType | ||||
2647 | = Context.getCanonicalType(Bases[idx]->getType()); | ||||
2648 | NewBaseType = NewBaseType.getLocalUnqualifiedType(); | ||||
2649 | |||||
2650 | CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; | ||||
2651 | if (KnownBase) { | ||||
2652 | // C++ [class.mi]p3: | ||||
2653 | // A class shall not be specified as a direct base class of a | ||||
2654 | // derived class more than once. | ||||
2655 | Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) | ||||
2656 | << KnownBase->getType() << Bases[idx]->getSourceRange(); | ||||
2657 | |||||
2658 | // Delete the duplicate base class specifier; we're going to | ||||
2659 | // overwrite its pointer later. | ||||
2660 | Context.Deallocate(Bases[idx]); | ||||
2661 | |||||
2662 | Invalid = true; | ||||
2663 | } else { | ||||
2664 | // Okay, add this new base class. | ||||
2665 | KnownBase = Bases[idx]; | ||||
2666 | Bases[NumGoodBases++] = Bases[idx]; | ||||
2667 | |||||
2668 | // Note this base's direct & indirect bases, if there could be ambiguity. | ||||
2669 | if (Bases.size() > 1) | ||||
2670 | NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); | ||||
2671 | |||||
2672 | if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { | ||||
2673 | const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); | ||||
2674 | if (Class->isInterface() && | ||||
2675 | (!RD->isInterfaceLike() || | ||||
2676 | KnownBase->getAccessSpecifier() != AS_public)) { | ||||
2677 | // The Microsoft extension __interface does not permit bases that | ||||
2678 | // are not themselves public interfaces. | ||||
2679 | Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) | ||||
2680 | << getRecordDiagFromTagKind(RD->getTagKind()) << RD | ||||
2681 | << RD->getSourceRange(); | ||||
2682 | Invalid = true; | ||||
2683 | } | ||||
2684 | if (RD->hasAttr<WeakAttr>()) | ||||
2685 | Class->addAttr(WeakAttr::CreateImplicit(Context)); | ||||
2686 | } | ||||
2687 | } | ||||
2688 | } | ||||
2689 | |||||
2690 | // Attach the remaining base class specifiers to the derived class. | ||||
2691 | Class->setBases(Bases.data(), NumGoodBases); | ||||
2692 | |||||
2693 | // Check that the only base classes that are duplicate are virtual. | ||||
2694 | for (unsigned idx = 0; idx < NumGoodBases; ++idx) { | ||||
2695 | // Check whether this direct base is inaccessible due to ambiguity. | ||||
2696 | QualType BaseType = Bases[idx]->getType(); | ||||
2697 | |||||
2698 | // Skip all dependent types in templates being used as base specifiers. | ||||
2699 | // Checks below assume that the base specifier is a CXXRecord. | ||||
2700 | if (BaseType->isDependentType()) | ||||
2701 | continue; | ||||
2702 | |||||
2703 | CanQualType CanonicalBase = Context.getCanonicalType(BaseType) | ||||
2704 | .getUnqualifiedType(); | ||||
2705 | |||||
2706 | if (IndirectBaseTypes.count(CanonicalBase)) { | ||||
2707 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | ||||
2708 | /*DetectVirtual=*/true); | ||||
2709 | bool found | ||||
2710 | = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); | ||||
2711 | assert(found)((found) ? static_cast<void> (0) : __assert_fail ("found" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 2711, __PRETTY_FUNCTION__)); | ||||
2712 | (void)found; | ||||
2713 | |||||
2714 | if (Paths.isAmbiguous(CanonicalBase)) | ||||
2715 | Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) | ||||
2716 | << BaseType << getAmbiguousPathsDisplayString(Paths) | ||||
2717 | << Bases[idx]->getSourceRange(); | ||||
2718 | else | ||||
2719 | assert(Bases[idx]->isVirtual())((Bases[idx]->isVirtual()) ? static_cast<void> (0) : __assert_fail ("Bases[idx]->isVirtual()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 2719, __PRETTY_FUNCTION__)); | ||||
2720 | } | ||||
2721 | |||||
2722 | // Delete the base class specifier, since its data has been copied | ||||
2723 | // into the CXXRecordDecl. | ||||
2724 | Context.Deallocate(Bases[idx]); | ||||
2725 | } | ||||
2726 | |||||
2727 | return Invalid; | ||||
2728 | } | ||||
2729 | |||||
2730 | /// ActOnBaseSpecifiers - Attach the given base specifiers to the | ||||
2731 | /// class, after checking whether there are any duplicate base | ||||
2732 | /// classes. | ||||
2733 | void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, | ||||
2734 | MutableArrayRef<CXXBaseSpecifier *> Bases) { | ||||
2735 | if (!ClassDecl || Bases.empty()) | ||||
2736 | return; | ||||
2737 | |||||
2738 | AdjustDeclIfTemplate(ClassDecl); | ||||
2739 | AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); | ||||
2740 | } | ||||
2741 | |||||
2742 | /// Determine whether the type \p Derived is a C++ class that is | ||||
2743 | /// derived from the type \p Base. | ||||
2744 | bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { | ||||
2745 | if (!getLangOpts().CPlusPlus) | ||||
2746 | return false; | ||||
2747 | |||||
2748 | CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); | ||||
2749 | if (!DerivedRD) | ||||
2750 | return false; | ||||
2751 | |||||
2752 | CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); | ||||
2753 | if (!BaseRD) | ||||
2754 | return false; | ||||
2755 | |||||
2756 | // If either the base or the derived type is invalid, don't try to | ||||
2757 | // check whether one is derived from the other. | ||||
2758 | if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) | ||||
2759 | return false; | ||||
2760 | |||||
2761 | // FIXME: In a modules build, do we need the entire path to be visible for us | ||||
2762 | // to be able to use the inheritance relationship? | ||||
2763 | if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) | ||||
2764 | return false; | ||||
2765 | |||||
2766 | return DerivedRD->isDerivedFrom(BaseRD); | ||||
2767 | } | ||||
2768 | |||||
2769 | /// Determine whether the type \p Derived is a C++ class that is | ||||
2770 | /// derived from the type \p Base. | ||||
2771 | bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, | ||||
2772 | CXXBasePaths &Paths) { | ||||
2773 | if (!getLangOpts().CPlusPlus) | ||||
2774 | return false; | ||||
2775 | |||||
2776 | CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); | ||||
2777 | if (!DerivedRD) | ||||
2778 | return false; | ||||
2779 | |||||
2780 | CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); | ||||
2781 | if (!BaseRD) | ||||
2782 | return false; | ||||
2783 | |||||
2784 | if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) | ||||
2785 | return false; | ||||
2786 | |||||
2787 | return DerivedRD->isDerivedFrom(BaseRD, Paths); | ||||
2788 | } | ||||
2789 | |||||
2790 | static void BuildBasePathArray(const CXXBasePath &Path, | ||||
2791 | CXXCastPath &BasePathArray) { | ||||
2792 | // We first go backward and check if we have a virtual base. | ||||
2793 | // FIXME: It would be better if CXXBasePath had the base specifier for | ||||
2794 | // the nearest virtual base. | ||||
2795 | unsigned Start = 0; | ||||
2796 | for (unsigned I = Path.size(); I != 0; --I) { | ||||
2797 | if (Path[I - 1].Base->isVirtual()) { | ||||
2798 | Start = I - 1; | ||||
2799 | break; | ||||
2800 | } | ||||
2801 | } | ||||
2802 | |||||
2803 | // Now add all bases. | ||||
2804 | for (unsigned I = Start, E = Path.size(); I != E; ++I) | ||||
2805 | BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); | ||||
2806 | } | ||||
2807 | |||||
2808 | |||||
2809 | void Sema::BuildBasePathArray(const CXXBasePaths &Paths, | ||||
2810 | CXXCastPath &BasePathArray) { | ||||
2811 | assert(BasePathArray.empty() && "Base path array must be empty!")((BasePathArray.empty() && "Base path array must be empty!" ) ? static_cast<void> (0) : __assert_fail ("BasePathArray.empty() && \"Base path array must be empty!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 2811, __PRETTY_FUNCTION__)); | ||||
2812 | assert(Paths.isRecordingPaths() && "Must record paths!")((Paths.isRecordingPaths() && "Must record paths!") ? static_cast<void> (0) : __assert_fail ("Paths.isRecordingPaths() && \"Must record paths!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 2812, __PRETTY_FUNCTION__)); | ||||
2813 | return ::BuildBasePathArray(Paths.front(), BasePathArray); | ||||
2814 | } | ||||
2815 | /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base | ||||
2816 | /// conversion (where Derived and Base are class types) is | ||||
2817 | /// well-formed, meaning that the conversion is unambiguous (and | ||||
2818 | /// that all of the base classes are accessible). Returns true | ||||
2819 | /// and emits a diagnostic if the code is ill-formed, returns false | ||||
2820 | /// otherwise. Loc is the location where this routine should point to | ||||
2821 | /// if there is an error, and Range is the source range to highlight | ||||
2822 | /// if there is an error. | ||||
2823 | /// | ||||
2824 | /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the | ||||
2825 | /// diagnostic for the respective type of error will be suppressed, but the | ||||
2826 | /// check for ill-formed code will still be performed. | ||||
2827 | bool | ||||
2828 | Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, | ||||
2829 | unsigned InaccessibleBaseID, | ||||
2830 | unsigned AmbigiousBaseConvID, | ||||
2831 | SourceLocation Loc, SourceRange Range, | ||||
2832 | DeclarationName Name, | ||||
2833 | CXXCastPath *BasePath, | ||||
2834 | bool IgnoreAccess) { | ||||
2835 | // First, determine whether the path from Derived to Base is | ||||
2836 | // ambiguous. This is slightly more expensive than checking whether | ||||
2837 | // the Derived to Base conversion exists, because here we need to | ||||
2838 | // explore multiple paths to determine if there is an ambiguity. | ||||
2839 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | ||||
2840 | /*DetectVirtual=*/false); | ||||
2841 | bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); | ||||
2842 | if (!DerivationOkay) | ||||
2843 | return true; | ||||
2844 | |||||
2845 | const CXXBasePath *Path = nullptr; | ||||
2846 | if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) | ||||
2847 | Path = &Paths.front(); | ||||
2848 | |||||
2849 | // For MSVC compatibility, check if Derived directly inherits from Base. Clang | ||||
2850 | // warns about this hierarchy under -Winaccessible-base, but MSVC allows the | ||||
2851 | // user to access such bases. | ||||
2852 | if (!Path && getLangOpts().MSVCCompat) { | ||||
2853 | for (const CXXBasePath &PossiblePath : Paths) { | ||||
2854 | if (PossiblePath.size() == 1) { | ||||
2855 | Path = &PossiblePath; | ||||
2856 | if (AmbigiousBaseConvID) | ||||
2857 | Diag(Loc, diag::ext_ms_ambiguous_direct_base) | ||||
2858 | << Base << Derived << Range; | ||||
2859 | break; | ||||
2860 | } | ||||
2861 | } | ||||
2862 | } | ||||
2863 | |||||
2864 | if (Path) { | ||||
2865 | if (!IgnoreAccess) { | ||||
2866 | // Check that the base class can be accessed. | ||||
2867 | switch ( | ||||
2868 | CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { | ||||
2869 | case AR_inaccessible: | ||||
2870 | return true; | ||||
2871 | case AR_accessible: | ||||
2872 | case AR_dependent: | ||||
2873 | case AR_delayed: | ||||
2874 | break; | ||||
2875 | } | ||||
2876 | } | ||||
2877 | |||||
2878 | // Build a base path if necessary. | ||||
2879 | if (BasePath) | ||||
2880 | ::BuildBasePathArray(*Path, *BasePath); | ||||
2881 | return false; | ||||
2882 | } | ||||
2883 | |||||
2884 | if (AmbigiousBaseConvID) { | ||||
2885 | // We know that the derived-to-base conversion is ambiguous, and | ||||
2886 | // we're going to produce a diagnostic. Perform the derived-to-base | ||||
2887 | // search just one more time to compute all of the possible paths so | ||||
2888 | // that we can print them out. This is more expensive than any of | ||||
2889 | // the previous derived-to-base checks we've done, but at this point | ||||
2890 | // performance isn't as much of an issue. | ||||
2891 | Paths.clear(); | ||||
2892 | Paths.setRecordingPaths(true); | ||||
2893 | bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); | ||||
2894 | assert(StillOkay && "Can only be used with a derived-to-base conversion")((StillOkay && "Can only be used with a derived-to-base conversion" ) ? static_cast<void> (0) : __assert_fail ("StillOkay && \"Can only be used with a derived-to-base conversion\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 2894, __PRETTY_FUNCTION__)); | ||||
2895 | (void)StillOkay; | ||||
2896 | |||||
2897 | // Build up a textual representation of the ambiguous paths, e.g., | ||||
2898 | // D -> B -> A, that will be used to illustrate the ambiguous | ||||
2899 | // conversions in the diagnostic. We only print one of the paths | ||||
2900 | // to each base class subobject. | ||||
2901 | std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); | ||||
2902 | |||||
2903 | Diag(Loc, AmbigiousBaseConvID) | ||||
2904 | << Derived << Base << PathDisplayStr << Range << Name; | ||||
2905 | } | ||||
2906 | return true; | ||||
2907 | } | ||||
2908 | |||||
2909 | bool | ||||
2910 | Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, | ||||
2911 | SourceLocation Loc, SourceRange Range, | ||||
2912 | CXXCastPath *BasePath, | ||||
2913 | bool IgnoreAccess) { | ||||
2914 | return CheckDerivedToBaseConversion( | ||||
2915 | Derived, Base, diag::err_upcast_to_inaccessible_base, | ||||
2916 | diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), | ||||
2917 | BasePath, IgnoreAccess); | ||||
2918 | } | ||||
2919 | |||||
2920 | |||||
2921 | /// Builds a string representing ambiguous paths from a | ||||
2922 | /// specific derived class to different subobjects of the same base | ||||
2923 | /// class. | ||||
2924 | /// | ||||
2925 | /// This function builds a string that can be used in error messages | ||||
2926 | /// to show the different paths that one can take through the | ||||
2927 | /// inheritance hierarchy to go from the derived class to different | ||||
2928 | /// subobjects of a base class. The result looks something like this: | ||||
2929 | /// @code | ||||
2930 | /// struct D -> struct B -> struct A | ||||
2931 | /// struct D -> struct C -> struct A | ||||
2932 | /// @endcode | ||||
2933 | std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { | ||||
2934 | std::string PathDisplayStr; | ||||
2935 | std::set<unsigned> DisplayedPaths; | ||||
2936 | for (CXXBasePaths::paths_iterator Path = Paths.begin(); | ||||
2937 | Path != Paths.end(); ++Path) { | ||||
2938 | if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { | ||||
2939 | // We haven't displayed a path to this particular base | ||||
2940 | // class subobject yet. | ||||
2941 | PathDisplayStr += "\n "; | ||||
2942 | PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); | ||||
2943 | for (CXXBasePath::const_iterator Element = Path->begin(); | ||||
2944 | Element != Path->end(); ++Element) | ||||
2945 | PathDisplayStr += " -> " + Element->Base->getType().getAsString(); | ||||
2946 | } | ||||
2947 | } | ||||
2948 | |||||
2949 | return PathDisplayStr; | ||||
2950 | } | ||||
2951 | |||||
2952 | //===----------------------------------------------------------------------===// | ||||
2953 | // C++ class member Handling | ||||
2954 | //===----------------------------------------------------------------------===// | ||||
2955 | |||||
2956 | /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. | ||||
2957 | bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, | ||||
2958 | SourceLocation ColonLoc, | ||||
2959 | const ParsedAttributesView &Attrs) { | ||||
2960 | assert(Access != AS_none && "Invalid kind for syntactic access specifier!")((Access != AS_none && "Invalid kind for syntactic access specifier!" ) ? static_cast<void> (0) : __assert_fail ("Access != AS_none && \"Invalid kind for syntactic access specifier!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 2960, __PRETTY_FUNCTION__)); | ||||
2961 | AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, | ||||
2962 | ASLoc, ColonLoc); | ||||
2963 | CurContext->addHiddenDecl(ASDecl); | ||||
2964 | return ProcessAccessDeclAttributeList(ASDecl, Attrs); | ||||
2965 | } | ||||
2966 | |||||
2967 | /// CheckOverrideControl - Check C++11 override control semantics. | ||||
2968 | void Sema::CheckOverrideControl(NamedDecl *D) { | ||||
2969 | if (D->isInvalidDecl()) | ||||
2970 | return; | ||||
2971 | |||||
2972 | // We only care about "override" and "final" declarations. | ||||
2973 | if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) | ||||
2974 | return; | ||||
2975 | |||||
2976 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); | ||||
2977 | |||||
2978 | // We can't check dependent instance methods. | ||||
2979 | if (MD && MD->isInstance() && | ||||
2980 | (MD->getParent()->hasAnyDependentBases() || | ||||
2981 | MD->getType()->isDependentType())) | ||||
2982 | return; | ||||
2983 | |||||
2984 | if (MD && !MD->isVirtual()) { | ||||
2985 | // If we have a non-virtual method, check if if hides a virtual method. | ||||
2986 | // (In that case, it's most likely the method has the wrong type.) | ||||
2987 | SmallVector<CXXMethodDecl *, 8> OverloadedMethods; | ||||
2988 | FindHiddenVirtualMethods(MD, OverloadedMethods); | ||||
2989 | |||||
2990 | if (!OverloadedMethods.empty()) { | ||||
2991 | if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { | ||||
2992 | Diag(OA->getLocation(), | ||||
2993 | diag::override_keyword_hides_virtual_member_function) | ||||
2994 | << "override" << (OverloadedMethods.size() > 1); | ||||
2995 | } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { | ||||
2996 | Diag(FA->getLocation(), | ||||
2997 | diag::override_keyword_hides_virtual_member_function) | ||||
2998 | << (FA->isSpelledAsSealed() ? "sealed" : "final") | ||||
2999 | << (OverloadedMethods.size() > 1); | ||||
3000 | } | ||||
3001 | NoteHiddenVirtualMethods(MD, OverloadedMethods); | ||||
3002 | MD->setInvalidDecl(); | ||||
3003 | return; | ||||
3004 | } | ||||
3005 | // Fall through into the general case diagnostic. | ||||
3006 | // FIXME: We might want to attempt typo correction here. | ||||
3007 | } | ||||
3008 | |||||
3009 | if (!MD || !MD->isVirtual()) { | ||||
3010 | if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { | ||||
3011 | Diag(OA->getLocation(), | ||||
3012 | diag::override_keyword_only_allowed_on_virtual_member_functions) | ||||
3013 | << "override" << FixItHint::CreateRemoval(OA->getLocation()); | ||||
3014 | D->dropAttr<OverrideAttr>(); | ||||
3015 | } | ||||
3016 | if (FinalAttr *FA = D->getAttr<FinalAttr>()) { | ||||
3017 | Diag(FA->getLocation(), | ||||
3018 | diag::override_keyword_only_allowed_on_virtual_member_functions) | ||||
3019 | << (FA->isSpelledAsSealed() ? "sealed" : "final") | ||||
3020 | << FixItHint::CreateRemoval(FA->getLocation()); | ||||
3021 | D->dropAttr<FinalAttr>(); | ||||
3022 | } | ||||
3023 | return; | ||||
3024 | } | ||||
3025 | |||||
3026 | // C++11 [class.virtual]p5: | ||||
3027 | // If a function is marked with the virt-specifier override and | ||||
3028 | // does not override a member function of a base class, the program is | ||||
3029 | // ill-formed. | ||||
3030 | bool HasOverriddenMethods = MD->size_overridden_methods() != 0; | ||||
3031 | if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) | ||||
3032 | Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) | ||||
3033 | << MD->getDeclName(); | ||||
3034 | } | ||||
3035 | |||||
3036 | void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { | ||||
3037 | if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) | ||||
3038 | return; | ||||
3039 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); | ||||
3040 | if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) | ||||
3041 | return; | ||||
3042 | |||||
3043 | SourceLocation Loc = MD->getLocation(); | ||||
3044 | SourceLocation SpellingLoc = Loc; | ||||
3045 | if (getSourceManager().isMacroArgExpansion(Loc)) | ||||
3046 | SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); | ||||
3047 | SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); | ||||
3048 | if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) | ||||
3049 | return; | ||||
3050 | |||||
3051 | if (MD->size_overridden_methods() > 0) { | ||||
3052 | unsigned DiagID = isa<CXXDestructorDecl>(MD) | ||||
3053 | ? diag::warn_destructor_marked_not_override_overriding | ||||
3054 | : diag::warn_function_marked_not_override_overriding; | ||||
3055 | Diag(MD->getLocation(), DiagID) << MD->getDeclName(); | ||||
3056 | const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); | ||||
3057 | Diag(OMD->getLocation(), diag::note_overridden_virtual_function); | ||||
3058 | } | ||||
3059 | } | ||||
3060 | |||||
3061 | /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member | ||||
3062 | /// function overrides a virtual member function marked 'final', according to | ||||
3063 | /// C++11 [class.virtual]p4. | ||||
3064 | bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, | ||||
3065 | const CXXMethodDecl *Old) { | ||||
3066 | FinalAttr *FA = Old->getAttr<FinalAttr>(); | ||||
3067 | if (!FA) | ||||
3068 | return false; | ||||
3069 | |||||
3070 | Diag(New->getLocation(), diag::err_final_function_overridden) | ||||
3071 | << New->getDeclName() | ||||
3072 | << FA->isSpelledAsSealed(); | ||||
3073 | Diag(Old->getLocation(), diag::note_overridden_virtual_function); | ||||
3074 | return true; | ||||
3075 | } | ||||
3076 | |||||
3077 | static bool InitializationHasSideEffects(const FieldDecl &FD) { | ||||
3078 | const Type *T = FD.getType()->getBaseElementTypeUnsafe(); | ||||
3079 | // FIXME: Destruction of ObjC lifetime types has side-effects. | ||||
3080 | if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) | ||||
3081 | return !RD->isCompleteDefinition() || | ||||
3082 | !RD->hasTrivialDefaultConstructor() || | ||||
3083 | !RD->hasTrivialDestructor(); | ||||
3084 | return false; | ||||
3085 | } | ||||
3086 | |||||
3087 | static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { | ||||
3088 | ParsedAttributesView::const_iterator Itr = | ||||
3089 | llvm::find_if(list, [](const ParsedAttr &AL) { | ||||
3090 | return AL.isDeclspecPropertyAttribute(); | ||||
3091 | }); | ||||
3092 | if (Itr != list.end()) | ||||
3093 | return &*Itr; | ||||
3094 | return nullptr; | ||||
3095 | } | ||||
3096 | |||||
3097 | // Check if there is a field shadowing. | ||||
3098 | void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, | ||||
3099 | DeclarationName FieldName, | ||||
3100 | const CXXRecordDecl *RD, | ||||
3101 | bool DeclIsField) { | ||||
3102 | if (Diags.isIgnored(diag::warn_shadow_field, Loc)) | ||||
3103 | return; | ||||
3104 | |||||
3105 | // To record a shadowed field in a base | ||||
3106 | std::map<CXXRecordDecl*, NamedDecl*> Bases; | ||||
3107 | auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, | ||||
3108 | CXXBasePath &Path) { | ||||
3109 | const auto Base = Specifier->getType()->getAsCXXRecordDecl(); | ||||
3110 | // Record an ambiguous path directly | ||||
3111 | if (Bases.find(Base) != Bases.end()) | ||||
3112 | return true; | ||||
3113 | for (const auto Field : Base->lookup(FieldName)) { | ||||
3114 | if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && | ||||
3115 | Field->getAccess() != AS_private) { | ||||
3116 | assert(Field->getAccess() != AS_none)((Field->getAccess() != AS_none) ? static_cast<void> (0) : __assert_fail ("Field->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 3116, __PRETTY_FUNCTION__)); | ||||
3117 | assert(Bases.find(Base) == Bases.end())((Bases.find(Base) == Bases.end()) ? static_cast<void> ( 0) : __assert_fail ("Bases.find(Base) == Bases.end()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 3117, __PRETTY_FUNCTION__)); | ||||
3118 | Bases[Base] = Field; | ||||
3119 | return true; | ||||
3120 | } | ||||
3121 | } | ||||
3122 | return false; | ||||
3123 | }; | ||||
3124 | |||||
3125 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | ||||
3126 | /*DetectVirtual=*/true); | ||||
3127 | if (!RD->lookupInBases(FieldShadowed, Paths)) | ||||
3128 | return; | ||||
3129 | |||||
3130 | for (const auto &P : Paths) { | ||||
3131 | auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); | ||||
3132 | auto It = Bases.find(Base); | ||||
3133 | // Skip duplicated bases | ||||
3134 | if (It == Bases.end()) | ||||
3135 | continue; | ||||
3136 | auto BaseField = It->second; | ||||
3137 | assert(BaseField->getAccess() != AS_private)((BaseField->getAccess() != AS_private) ? static_cast<void > (0) : __assert_fail ("BaseField->getAccess() != AS_private" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 3137, __PRETTY_FUNCTION__)); | ||||
3138 | if (AS_none != | ||||
3139 | CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { | ||||
3140 | Diag(Loc, diag::warn_shadow_field) | ||||
3141 | << FieldName << RD << Base << DeclIsField; | ||||
3142 | Diag(BaseField->getLocation(), diag::note_shadow_field); | ||||
3143 | Bases.erase(It); | ||||
3144 | } | ||||
3145 | } | ||||
3146 | } | ||||
3147 | |||||
3148 | /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member | ||||
3149 | /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the | ||||
3150 | /// bitfield width if there is one, 'InitExpr' specifies the initializer if | ||||
3151 | /// one has been parsed, and 'InitStyle' is set if an in-class initializer is | ||||
3152 | /// present (but parsing it has been deferred). | ||||
3153 | NamedDecl * | ||||
3154 | Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, | ||||
3155 | MultiTemplateParamsArg TemplateParameterLists, | ||||
3156 | Expr *BW, const VirtSpecifiers &VS, | ||||
3157 | InClassInitStyle InitStyle) { | ||||
3158 | const DeclSpec &DS = D.getDeclSpec(); | ||||
3159 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | ||||
3160 | DeclarationName Name = NameInfo.getName(); | ||||
3161 | SourceLocation Loc = NameInfo.getLoc(); | ||||
3162 | |||||
3163 | // For anonymous bitfields, the location should point to the type. | ||||
3164 | if (Loc.isInvalid()) | ||||
3165 | Loc = D.getBeginLoc(); | ||||
3166 | |||||
3167 | Expr *BitWidth = static_cast<Expr*>(BW); | ||||
3168 | |||||
3169 | assert(isa<CXXRecordDecl>(CurContext))((isa<CXXRecordDecl>(CurContext)) ? static_cast<void > (0) : __assert_fail ("isa<CXXRecordDecl>(CurContext)" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 3169, __PRETTY_FUNCTION__)); | ||||
3170 | assert(!DS.isFriendSpecified())((!DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail ("!DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 3170, __PRETTY_FUNCTION__)); | ||||
3171 | |||||
3172 | bool isFunc = D.isDeclarationOfFunction(); | ||||
3173 | const ParsedAttr *MSPropertyAttr = | ||||
3174 | getMSPropertyAttr(D.getDeclSpec().getAttributes()); | ||||
3175 | |||||
3176 | if (cast<CXXRecordDecl>(CurContext)->isInterface()) { | ||||
3177 | // The Microsoft extension __interface only permits public member functions | ||||
3178 | // and prohibits constructors, destructors, operators, non-public member | ||||
3179 | // functions, static methods and data members. | ||||
3180 | unsigned InvalidDecl; | ||||
3181 | bool ShowDeclName = true; | ||||
3182 | if (!isFunc && | ||||
3183 | (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) | ||||
3184 | InvalidDecl = 0; | ||||
3185 | else if (!isFunc) | ||||
3186 | InvalidDecl = 1; | ||||
3187 | else if (AS != AS_public) | ||||
3188 | InvalidDecl = 2; | ||||
3189 | else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) | ||||
3190 | InvalidDecl = 3; | ||||
3191 | else switch (Name.getNameKind()) { | ||||
3192 | case DeclarationName::CXXConstructorName: | ||||
3193 | InvalidDecl = 4; | ||||
3194 | ShowDeclName = false; | ||||
3195 | break; | ||||
3196 | |||||
3197 | case DeclarationName::CXXDestructorName: | ||||
3198 | InvalidDecl = 5; | ||||
3199 | ShowDeclName = false; | ||||
3200 | break; | ||||
3201 | |||||
3202 | case DeclarationName::CXXOperatorName: | ||||
3203 | case DeclarationName::CXXConversionFunctionName: | ||||
3204 | InvalidDecl = 6; | ||||
3205 | break; | ||||
3206 | |||||
3207 | default: | ||||
3208 | InvalidDecl = 0; | ||||
3209 | break; | ||||
3210 | } | ||||
3211 | |||||
3212 | if (InvalidDecl) { | ||||
3213 | if (ShowDeclName) | ||||
3214 | Diag(Loc, diag::err_invalid_member_in_interface) | ||||
3215 | << (InvalidDecl-1) << Name; | ||||
3216 | else | ||||
3217 | Diag(Loc, diag::err_invalid_member_in_interface) | ||||
3218 | << (InvalidDecl-1) << ""; | ||||
3219 | return nullptr; | ||||
3220 | } | ||||
3221 | } | ||||
3222 | |||||
3223 | // C++ 9.2p6: A member shall not be declared to have automatic storage | ||||
3224 | // duration (auto, register) or with the extern storage-class-specifier. | ||||
3225 | // C++ 7.1.1p8: The mutable specifier can be applied only to names of class | ||||
3226 | // data members and cannot be applied to names declared const or static, | ||||
3227 | // and cannot be applied to reference members. | ||||
3228 | switch (DS.getStorageClassSpec()) { | ||||
3229 | case DeclSpec::SCS_unspecified: | ||||
3230 | case DeclSpec::SCS_typedef: | ||||
3231 | case DeclSpec::SCS_static: | ||||
3232 | break; | ||||
3233 | case DeclSpec::SCS_mutable: | ||||
3234 | if (isFunc) { | ||||
3235 | Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); | ||||
3236 | |||||
3237 | // FIXME: It would be nicer if the keyword was ignored only for this | ||||
3238 | // declarator. Otherwise we could get follow-up errors. | ||||
3239 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | ||||
3240 | } | ||||
3241 | break; | ||||
3242 | default: | ||||
3243 | Diag(DS.getStorageClassSpecLoc(), | ||||
3244 | diag::err_storageclass_invalid_for_member); | ||||
3245 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | ||||
3246 | break; | ||||
3247 | } | ||||
3248 | |||||
3249 | bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || | ||||
3250 | DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && | ||||
3251 | !isFunc); | ||||
3252 | |||||
3253 | if (DS.hasConstexprSpecifier() && isInstField) { | ||||
3254 | SemaDiagnosticBuilder B = | ||||
3255 | Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); | ||||
3256 | SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); | ||||
3257 | if (InitStyle == ICIS_NoInit) { | ||||
3258 | B << 0 << 0; | ||||
3259 | if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) | ||||
3260 | B << FixItHint::CreateRemoval(ConstexprLoc); | ||||
3261 | else { | ||||
3262 | B << FixItHint::CreateReplacement(ConstexprLoc, "const"); | ||||
3263 | D.getMutableDeclSpec().ClearConstexprSpec(); | ||||
3264 | const char *PrevSpec; | ||||
3265 | unsigned DiagID; | ||||
3266 | bool Failed = D.getMutableDeclSpec().SetTypeQual( | ||||
3267 | DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); | ||||
3268 | (void)Failed; | ||||
3269 | assert(!Failed && "Making a constexpr member const shouldn't fail")((!Failed && "Making a constexpr member const shouldn't fail" ) ? static_cast<void> (0) : __assert_fail ("!Failed && \"Making a constexpr member const shouldn't fail\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 3269, __PRETTY_FUNCTION__)); | ||||
3270 | } | ||||
3271 | } else { | ||||
3272 | B << 1; | ||||
3273 | const char *PrevSpec; | ||||
3274 | unsigned DiagID; | ||||
3275 | if (D.getMutableDeclSpec().SetStorageClassSpec( | ||||
3276 | *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, | ||||
3277 | Context.getPrintingPolicy())) { | ||||
3278 | assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&((DS.getStorageClassSpec() == DeclSpec::SCS_mutable && "This is the only DeclSpec that should fail to be applied") ? static_cast<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 3279, __PRETTY_FUNCTION__)) | ||||
3279 | "This is the only DeclSpec that should fail to be applied")((DS.getStorageClassSpec() == DeclSpec::SCS_mutable && "This is the only DeclSpec that should fail to be applied") ? static_cast<void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_mutable && \"This is the only DeclSpec that should fail to be applied\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 3279, __PRETTY_FUNCTION__)); | ||||
3280 | B << 1; | ||||
3281 | } else { | ||||
3282 | B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); | ||||
3283 | isInstField = false; | ||||
3284 | } | ||||
3285 | } | ||||
3286 | } | ||||
3287 | |||||
3288 | NamedDecl *Member; | ||||
3289 | if (isInstField) { | ||||
3290 | CXXScopeSpec &SS = D.getCXXScopeSpec(); | ||||
3291 | |||||
3292 | // Data members must have identifiers for names. | ||||
3293 | if (!Name.isIdentifier()) { | ||||
3294 | Diag(Loc, diag::err_bad_variable_name) | ||||
3295 | << Name; | ||||
3296 | return nullptr; | ||||
3297 | } | ||||
3298 | |||||
3299 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||
3300 | |||||
3301 | // Member field could not be with "template" keyword. | ||||
3302 | // So TemplateParameterLists should be empty in this case. | ||||
3303 | if (TemplateParameterLists.size()) { | ||||
3304 | TemplateParameterList* TemplateParams = TemplateParameterLists[0]; | ||||
3305 | if (TemplateParams->size()) { | ||||
3306 | // There is no such thing as a member field template. | ||||
3307 | Diag(D.getIdentifierLoc(), diag::err_template_member) | ||||
3308 | << II | ||||
3309 | << SourceRange(TemplateParams->getTemplateLoc(), | ||||
3310 | TemplateParams->getRAngleLoc()); | ||||
3311 | } else { | ||||
3312 | // There is an extraneous 'template<>' for this member. | ||||
3313 | Diag(TemplateParams->getTemplateLoc(), | ||||
3314 | diag::err_template_member_noparams) | ||||
3315 | << II | ||||
3316 | << SourceRange(TemplateParams->getTemplateLoc(), | ||||
3317 | TemplateParams->getRAngleLoc()); | ||||
3318 | } | ||||
3319 | return nullptr; | ||||
3320 | } | ||||
3321 | |||||
3322 | if (SS.isSet() && !SS.isInvalid()) { | ||||
3323 | // The user provided a superfluous scope specifier inside a class | ||||
3324 | // definition: | ||||
3325 | // | ||||
3326 | // class X { | ||||
3327 | // int X::member; | ||||
3328 | // }; | ||||
3329 | if (DeclContext *DC = computeDeclContext(SS, false)) | ||||
3330 | diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), | ||||
3331 | D.getName().getKind() == | ||||
3332 | UnqualifiedIdKind::IK_TemplateId); | ||||
3333 | else | ||||
3334 | Diag(D.getIdentifierLoc(), diag::err_member_qualification) | ||||
3335 | << Name << SS.getRange(); | ||||
3336 | |||||
3337 | SS.clear(); | ||||
3338 | } | ||||
3339 | |||||
3340 | if (MSPropertyAttr) { | ||||
3341 | Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, | ||||
3342 | BitWidth, InitStyle, AS, *MSPropertyAttr); | ||||
3343 | if (!Member) | ||||
3344 | return nullptr; | ||||
3345 | isInstField = false; | ||||
3346 | } else { | ||||
3347 | Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, | ||||
3348 | BitWidth, InitStyle, AS); | ||||
3349 | if (!Member) | ||||
3350 | return nullptr; | ||||
3351 | } | ||||
3352 | |||||
3353 | CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); | ||||
3354 | } else { | ||||
3355 | Member = HandleDeclarator(S, D, TemplateParameterLists); | ||||
3356 | if (!Member) | ||||
3357 | return nullptr; | ||||
3358 | |||||
3359 | // Non-instance-fields can't have a bitfield. | ||||
3360 | if (BitWidth) { | ||||
3361 | if (Member->isInvalidDecl()) { | ||||
3362 | // don't emit another diagnostic. | ||||
3363 | } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { | ||||
3364 | // C++ 9.6p3: A bit-field shall not be a static member. | ||||
3365 | // "static member 'A' cannot be a bit-field" | ||||
3366 | Diag(Loc, diag::err_static_not_bitfield) | ||||
3367 | << Name << BitWidth->getSourceRange(); | ||||
3368 | } else if (isa<TypedefDecl>(Member)) { | ||||
3369 | // "typedef member 'x' cannot be a bit-field" | ||||
3370 | Diag(Loc, diag::err_typedef_not_bitfield) | ||||
3371 | << Name << BitWidth->getSourceRange(); | ||||
3372 | } else { | ||||
3373 | // A function typedef ("typedef int f(); f a;"). | ||||
3374 | // C++ 9.6p3: A bit-field shall have integral or enumeration type. | ||||
3375 | Diag(Loc, diag::err_not_integral_type_bitfield) | ||||
3376 | << Name << cast<ValueDecl>(Member)->getType() | ||||
3377 | << BitWidth->getSourceRange(); | ||||
3378 | } | ||||
3379 | |||||
3380 | BitWidth = nullptr; | ||||
3381 | Member->setInvalidDecl(); | ||||
3382 | } | ||||
3383 | |||||
3384 | NamedDecl *NonTemplateMember = Member; | ||||
3385 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) | ||||
3386 | NonTemplateMember = FunTmpl->getTemplatedDecl(); | ||||
3387 | else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) | ||||
3388 | NonTemplateMember = VarTmpl->getTemplatedDecl(); | ||||
3389 | |||||
3390 | Member->setAccess(AS); | ||||
3391 | |||||
3392 | // If we have declared a member function template or static data member | ||||
3393 | // template, set the access of the templated declaration as well. | ||||
3394 | if (NonTemplateMember != Member) | ||||
3395 | NonTemplateMember->setAccess(AS); | ||||
3396 | |||||
3397 | // C++ [temp.deduct.guide]p3: | ||||
3398 | // A deduction guide [...] for a member class template [shall be | ||||
3399 | // declared] with the same access [as the template]. | ||||
3400 | if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { | ||||
3401 | auto *TD = DG->getDeducedTemplate(); | ||||
3402 | // Access specifiers are only meaningful if both the template and the | ||||
3403 | // deduction guide are from the same scope. | ||||
3404 | if (AS != TD->getAccess() && | ||||
3405 | TD->getDeclContext()->getRedeclContext()->Equals( | ||||
3406 | DG->getDeclContext()->getRedeclContext())) { | ||||
3407 | Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); | ||||
3408 | Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) | ||||
3409 | << TD->getAccess(); | ||||
3410 | const AccessSpecDecl *LastAccessSpec = nullptr; | ||||
3411 | for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { | ||||
3412 | if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) | ||||
3413 | LastAccessSpec = AccessSpec; | ||||
3414 | } | ||||
3415 | assert(LastAccessSpec && "differing access with no access specifier")((LastAccessSpec && "differing access with no access specifier" ) ? static_cast<void> (0) : __assert_fail ("LastAccessSpec && \"differing access with no access specifier\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 3415, __PRETTY_FUNCTION__)); | ||||
3416 | Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) | ||||
3417 | << AS; | ||||
3418 | } | ||||
3419 | } | ||||
3420 | } | ||||
3421 | |||||
3422 | if (VS.isOverrideSpecified()) | ||||
3423 | Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), | ||||
3424 | AttributeCommonInfo::AS_Keyword)); | ||||
3425 | if (VS.isFinalSpecified()) | ||||
3426 | Member->addAttr(FinalAttr::Create( | ||||
3427 | Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, | ||||
3428 | static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); | ||||
3429 | |||||
3430 | if (VS.getLastLocation().isValid()) { | ||||
3431 | // Update the end location of a method that has a virt-specifiers. | ||||
3432 | if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) | ||||
3433 | MD->setRangeEnd(VS.getLastLocation()); | ||||
3434 | } | ||||
3435 | |||||
3436 | CheckOverrideControl(Member); | ||||
3437 | |||||
3438 | assert((Name || isInstField) && "No identifier for non-field ?")(((Name || isInstField) && "No identifier for non-field ?" ) ? static_cast<void> (0) : __assert_fail ("(Name || isInstField) && \"No identifier for non-field ?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 3438, __PRETTY_FUNCTION__)); | ||||
3439 | |||||
3440 | if (isInstField) { | ||||
3441 | FieldDecl *FD = cast<FieldDecl>(Member); | ||||
3442 | FieldCollector->Add(FD); | ||||
3443 | |||||
3444 | if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { | ||||
3445 | // Remember all explicit private FieldDecls that have a name, no side | ||||
3446 | // effects and are not part of a dependent type declaration. | ||||
3447 | if (!FD->isImplicit() && FD->getDeclName() && | ||||
3448 | FD->getAccess() == AS_private && | ||||
3449 | !FD->hasAttr<UnusedAttr>() && | ||||
3450 | !FD->getParent()->isDependentContext() && | ||||
3451 | !InitializationHasSideEffects(*FD)) | ||||
3452 | UnusedPrivateFields.insert(FD); | ||||
3453 | } | ||||
3454 | } | ||||
3455 | |||||
3456 | return Member; | ||||
3457 | } | ||||
3458 | |||||
3459 | namespace { | ||||
3460 | class UninitializedFieldVisitor | ||||
3461 | : public EvaluatedExprVisitor<UninitializedFieldVisitor> { | ||||
3462 | Sema &S; | ||||
3463 | // List of Decls to generate a warning on. Also remove Decls that become | ||||
3464 | // initialized. | ||||
3465 | llvm::SmallPtrSetImpl<ValueDecl*> &Decls; | ||||
3466 | // List of base classes of the record. Classes are removed after their | ||||
3467 | // initializers. | ||||
3468 | llvm::SmallPtrSetImpl<QualType> &BaseClasses; | ||||
3469 | // Vector of decls to be removed from the Decl set prior to visiting the | ||||
3470 | // nodes. These Decls may have been initialized in the prior initializer. | ||||
3471 | llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; | ||||
3472 | // If non-null, add a note to the warning pointing back to the constructor. | ||||
3473 | const CXXConstructorDecl *Constructor; | ||||
3474 | // Variables to hold state when processing an initializer list. When | ||||
3475 | // InitList is true, special case initialization of FieldDecls matching | ||||
3476 | // InitListFieldDecl. | ||||
3477 | bool InitList; | ||||
3478 | FieldDecl *InitListFieldDecl; | ||||
3479 | llvm::SmallVector<unsigned, 4> InitFieldIndex; | ||||
3480 | |||||
3481 | public: | ||||
3482 | typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; | ||||
3483 | UninitializedFieldVisitor(Sema &S, | ||||
3484 | llvm::SmallPtrSetImpl<ValueDecl*> &Decls, | ||||
3485 | llvm::SmallPtrSetImpl<QualType> &BaseClasses) | ||||
3486 | : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), | ||||
3487 | Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} | ||||
3488 | |||||
3489 | // Returns true if the use of ME is not an uninitialized use. | ||||
3490 | bool IsInitListMemberExprInitialized(MemberExpr *ME, | ||||
3491 | bool CheckReferenceOnly) { | ||||
3492 | llvm::SmallVector<FieldDecl*, 4> Fields; | ||||
3493 | bool ReferenceField = false; | ||||
3494 | while (ME) { | ||||
3495 | FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); | ||||
3496 | if (!FD) | ||||
3497 | return false; | ||||
3498 | Fields.push_back(FD); | ||||
3499 | if (FD->getType()->isReferenceType()) | ||||
3500 | ReferenceField = true; | ||||
3501 | ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); | ||||
3502 | } | ||||
3503 | |||||
3504 | // Binding a reference to an uninitialized field is not an | ||||
3505 | // uninitialized use. | ||||
3506 | if (CheckReferenceOnly && !ReferenceField) | ||||
3507 | return true; | ||||
3508 | |||||
3509 | llvm::SmallVector<unsigned, 4> UsedFieldIndex; | ||||
3510 | // Discard the first field since it is the field decl that is being | ||||
3511 | // initialized. | ||||
3512 | for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { | ||||
3513 | UsedFieldIndex.push_back((*I)->getFieldIndex()); | ||||
3514 | } | ||||
3515 | |||||
3516 | for (auto UsedIter = UsedFieldIndex.begin(), | ||||
3517 | UsedEnd = UsedFieldIndex.end(), | ||||
3518 | OrigIter = InitFieldIndex.begin(), | ||||
3519 | OrigEnd = InitFieldIndex.end(); | ||||
3520 | UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { | ||||
3521 | if (*UsedIter < *OrigIter) | ||||
3522 | return true; | ||||
3523 | if (*UsedIter > *OrigIter) | ||||
3524 | break; | ||||
3525 | } | ||||
3526 | |||||
3527 | return false; | ||||
3528 | } | ||||
3529 | |||||
3530 | void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, | ||||
3531 | bool AddressOf) { | ||||
3532 | if (isa<EnumConstantDecl>(ME->getMemberDecl())) | ||||
3533 | return; | ||||
3534 | |||||
3535 | // FieldME is the inner-most MemberExpr that is not an anonymous struct | ||||
3536 | // or union. | ||||
3537 | MemberExpr *FieldME = ME; | ||||
3538 | |||||
3539 | bool AllPODFields = FieldME->getType().isPODType(S.Context); | ||||
3540 | |||||
3541 | Expr *Base = ME; | ||||
3542 | while (MemberExpr *SubME = | ||||
3543 | dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { | ||||
3544 | |||||
3545 | if (isa<VarDecl>(SubME->getMemberDecl())) | ||||
3546 | return; | ||||
3547 | |||||
3548 | if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) | ||||
3549 | if (!FD->isAnonymousStructOrUnion()) | ||||
3550 | FieldME = SubME; | ||||
3551 | |||||
3552 | if (!FieldME->getType().isPODType(S.Context)) | ||||
3553 | AllPODFields = false; | ||||
3554 | |||||
3555 | Base = SubME->getBase(); | ||||
3556 | } | ||||
3557 | |||||
3558 | if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) | ||||
3559 | return; | ||||
3560 | |||||
3561 | if (AddressOf && AllPODFields) | ||||
3562 | return; | ||||
3563 | |||||
3564 | ValueDecl* FoundVD = FieldME->getMemberDecl(); | ||||
3565 | |||||
3566 | if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { | ||||
3567 | while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { | ||||
3568 | BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); | ||||
3569 | } | ||||
3570 | |||||
3571 | if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { | ||||
3572 | QualType T = BaseCast->getType(); | ||||
3573 | if (T->isPointerType() && | ||||
3574 | BaseClasses.count(T->getPointeeType())) { | ||||
3575 | S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) | ||||
3576 | << T->getPointeeType() << FoundVD; | ||||
3577 | } | ||||
3578 | } | ||||
3579 | } | ||||
3580 | |||||
3581 | if (!Decls.count(FoundVD)) | ||||
3582 | return; | ||||
3583 | |||||
3584 | const bool IsReference = FoundVD->getType()->isReferenceType(); | ||||
3585 | |||||
3586 | if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { | ||||
3587 | // Special checking for initializer lists. | ||||
3588 | if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { | ||||
3589 | return; | ||||
3590 | } | ||||
3591 | } else { | ||||
3592 | // Prevent double warnings on use of unbounded references. | ||||
3593 | if (CheckReferenceOnly && !IsReference) | ||||
3594 | return; | ||||
3595 | } | ||||
3596 | |||||
3597 | unsigned diag = IsReference | ||||
3598 | ? diag::warn_reference_field_is_uninit | ||||
3599 | : diag::warn_field_is_uninit; | ||||
3600 | S.Diag(FieldME->getExprLoc(), diag) << FoundVD; | ||||
3601 | if (Constructor) | ||||
3602 | S.Diag(Constructor->getLocation(), | ||||
3603 | diag::note_uninit_in_this_constructor) | ||||
3604 | << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); | ||||
3605 | |||||
3606 | } | ||||
3607 | |||||
3608 | void HandleValue(Expr *E, bool AddressOf) { | ||||
3609 | E = E->IgnoreParens(); | ||||
3610 | |||||
3611 | if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { | ||||
3612 | HandleMemberExpr(ME, false /*CheckReferenceOnly*/, | ||||
3613 | AddressOf /*AddressOf*/); | ||||
3614 | return; | ||||
3615 | } | ||||
3616 | |||||
3617 | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { | ||||
3618 | Visit(CO->getCond()); | ||||
3619 | HandleValue(CO->getTrueExpr(), AddressOf); | ||||
3620 | HandleValue(CO->getFalseExpr(), AddressOf); | ||||
3621 | return; | ||||
3622 | } | ||||
3623 | |||||
3624 | if (BinaryConditionalOperator *BCO = | ||||
3625 | dyn_cast<BinaryConditionalOperator>(E)) { | ||||
3626 | Visit(BCO->getCond()); | ||||
3627 | HandleValue(BCO->getFalseExpr(), AddressOf); | ||||
3628 | return; | ||||
3629 | } | ||||
3630 | |||||
3631 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { | ||||
3632 | HandleValue(OVE->getSourceExpr(), AddressOf); | ||||
3633 | return; | ||||
3634 | } | ||||
3635 | |||||
3636 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | ||||
3637 | switch (BO->getOpcode()) { | ||||
3638 | default: | ||||
3639 | break; | ||||
3640 | case(BO_PtrMemD): | ||||
3641 | case(BO_PtrMemI): | ||||
3642 | HandleValue(BO->getLHS(), AddressOf); | ||||
3643 | Visit(BO->getRHS()); | ||||
3644 | return; | ||||
3645 | case(BO_Comma): | ||||
3646 | Visit(BO->getLHS()); | ||||
3647 | HandleValue(BO->getRHS(), AddressOf); | ||||
3648 | return; | ||||
3649 | } | ||||
3650 | } | ||||
3651 | |||||
3652 | Visit(E); | ||||
3653 | } | ||||
3654 | |||||
3655 | void CheckInitListExpr(InitListExpr *ILE) { | ||||
3656 | InitFieldIndex.push_back(0); | ||||
3657 | for (auto Child : ILE->children()) { | ||||
3658 | if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { | ||||
3659 | CheckInitListExpr(SubList); | ||||
3660 | } else { | ||||
3661 | Visit(Child); | ||||
3662 | } | ||||
3663 | ++InitFieldIndex.back(); | ||||
3664 | } | ||||
3665 | InitFieldIndex.pop_back(); | ||||
3666 | } | ||||
3667 | |||||
3668 | void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, | ||||
3669 | FieldDecl *Field, const Type *BaseClass) { | ||||
3670 | // Remove Decls that may have been initialized in the previous | ||||
3671 | // initializer. | ||||
3672 | for (ValueDecl* VD : DeclsToRemove) | ||||
3673 | Decls.erase(VD); | ||||
3674 | DeclsToRemove.clear(); | ||||
3675 | |||||
3676 | Constructor = FieldConstructor; | ||||
3677 | InitListExpr *ILE = dyn_cast<InitListExpr>(E); | ||||
3678 | |||||
3679 | if (ILE && Field) { | ||||
3680 | InitList = true; | ||||
3681 | InitListFieldDecl = Field; | ||||
3682 | InitFieldIndex.clear(); | ||||
3683 | CheckInitListExpr(ILE); | ||||
3684 | } else { | ||||
3685 | InitList = false; | ||||
3686 | Visit(E); | ||||
3687 | } | ||||
3688 | |||||
3689 | if (Field) | ||||
3690 | Decls.erase(Field); | ||||
3691 | if (BaseClass) | ||||
3692 | BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); | ||||
3693 | } | ||||
3694 | |||||
3695 | void VisitMemberExpr(MemberExpr *ME) { | ||||
3696 | // All uses of unbounded reference fields will warn. | ||||
3697 | HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); | ||||
3698 | } | ||||
3699 | |||||
3700 | void VisitImplicitCastExpr(ImplicitCastExpr *E) { | ||||
3701 | if (E->getCastKind() == CK_LValueToRValue) { | ||||
3702 | HandleValue(E->getSubExpr(), false /*AddressOf*/); | ||||
3703 | return; | ||||
3704 | } | ||||
3705 | |||||
3706 | Inherited::VisitImplicitCastExpr(E); | ||||
3707 | } | ||||
3708 | |||||
3709 | void VisitCXXConstructExpr(CXXConstructExpr *E) { | ||||
3710 | if (E->getConstructor()->isCopyConstructor()) { | ||||
3711 | Expr *ArgExpr = E->getArg(0); | ||||
3712 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) | ||||
3713 | if (ILE->getNumInits() == 1) | ||||
3714 | ArgExpr = ILE->getInit(0); | ||||
3715 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) | ||||
3716 | if (ICE->getCastKind() == CK_NoOp) | ||||
3717 | ArgExpr = ICE->getSubExpr(); | ||||
3718 | HandleValue(ArgExpr, false /*AddressOf*/); | ||||
3719 | return; | ||||
3720 | } | ||||
3721 | Inherited::VisitCXXConstructExpr(E); | ||||
3722 | } | ||||
3723 | |||||
3724 | void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { | ||||
3725 | Expr *Callee = E->getCallee(); | ||||
3726 | if (isa<MemberExpr>(Callee)) { | ||||
3727 | HandleValue(Callee, false /*AddressOf*/); | ||||
3728 | for (auto Arg : E->arguments()) | ||||
3729 | Visit(Arg); | ||||
3730 | return; | ||||
3731 | } | ||||
3732 | |||||
3733 | Inherited::VisitCXXMemberCallExpr(E); | ||||
3734 | } | ||||
3735 | |||||
3736 | void VisitCallExpr(CallExpr *E) { | ||||
3737 | // Treat std::move as a use. | ||||
3738 | if (E->isCallToStdMove()) { | ||||
3739 | HandleValue(E->getArg(0), /*AddressOf=*/false); | ||||
3740 | return; | ||||
3741 | } | ||||
3742 | |||||
3743 | Inherited::VisitCallExpr(E); | ||||
3744 | } | ||||
3745 | |||||
3746 | void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | ||||
3747 | Expr *Callee = E->getCallee(); | ||||
3748 | |||||
3749 | if (isa<UnresolvedLookupExpr>(Callee)) | ||||
3750 | return Inherited::VisitCXXOperatorCallExpr(E); | ||||
3751 | |||||
3752 | Visit(Callee); | ||||
3753 | for (auto Arg : E->arguments()) | ||||
3754 | HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); | ||||
3755 | } | ||||
3756 | |||||
3757 | void VisitBinaryOperator(BinaryOperator *E) { | ||||
3758 | // If a field assignment is detected, remove the field from the | ||||
3759 | // uninitiailized field set. | ||||
3760 | if (E->getOpcode() == BO_Assign) | ||||
3761 | if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) | ||||
3762 | if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) | ||||
3763 | if (!FD->getType()->isReferenceType()) | ||||
3764 | DeclsToRemove.push_back(FD); | ||||
3765 | |||||
3766 | if (E->isCompoundAssignmentOp()) { | ||||
3767 | HandleValue(E->getLHS(), false /*AddressOf*/); | ||||
3768 | Visit(E->getRHS()); | ||||
3769 | return; | ||||
3770 | } | ||||
3771 | |||||
3772 | Inherited::VisitBinaryOperator(E); | ||||
3773 | } | ||||
3774 | |||||
3775 | void VisitUnaryOperator(UnaryOperator *E) { | ||||
3776 | if (E->isIncrementDecrementOp()) { | ||||
3777 | HandleValue(E->getSubExpr(), false /*AddressOf*/); | ||||
3778 | return; | ||||
3779 | } | ||||
3780 | if (E->getOpcode() == UO_AddrOf) { | ||||
3781 | if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { | ||||
3782 | HandleValue(ME->getBase(), true /*AddressOf*/); | ||||
3783 | return; | ||||
3784 | } | ||||
3785 | } | ||||
3786 | |||||
3787 | Inherited::VisitUnaryOperator(E); | ||||
3788 | } | ||||
3789 | }; | ||||
3790 | |||||
3791 | // Diagnose value-uses of fields to initialize themselves, e.g. | ||||
3792 | // foo(foo) | ||||
3793 | // where foo is not also a parameter to the constructor. | ||||
3794 | // Also diagnose across field uninitialized use such as | ||||
3795 | // x(y), y(x) | ||||
3796 | // TODO: implement -Wuninitialized and fold this into that framework. | ||||
3797 | static void DiagnoseUninitializedFields( | ||||
3798 | Sema &SemaRef, const CXXConstructorDecl *Constructor) { | ||||
3799 | |||||
3800 | if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, | ||||
3801 | Constructor->getLocation())) { | ||||
3802 | return; | ||||
3803 | } | ||||
3804 | |||||
3805 | if (Constructor->isInvalidDecl()) | ||||
3806 | return; | ||||
3807 | |||||
3808 | const CXXRecordDecl *RD = Constructor->getParent(); | ||||
3809 | |||||
3810 | if (RD->isDependentContext()) | ||||
3811 | return; | ||||
3812 | |||||
3813 | // Holds fields that are uninitialized. | ||||
3814 | llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; | ||||
3815 | |||||
3816 | // At the beginning, all fields are uninitialized. | ||||
3817 | for (auto *I : RD->decls()) { | ||||
3818 | if (auto *FD = dyn_cast<FieldDecl>(I)) { | ||||
3819 | UninitializedFields.insert(FD); | ||||
3820 | } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { | ||||
3821 | UninitializedFields.insert(IFD->getAnonField()); | ||||
3822 | } | ||||
3823 | } | ||||
3824 | |||||
3825 | llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; | ||||
3826 | for (auto I : RD->bases()) | ||||
3827 | UninitializedBaseClasses.insert(I.getType().getCanonicalType()); | ||||
3828 | |||||
3829 | if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) | ||||
3830 | return; | ||||
3831 | |||||
3832 | UninitializedFieldVisitor UninitializedChecker(SemaRef, | ||||
3833 | UninitializedFields, | ||||
3834 | UninitializedBaseClasses); | ||||
3835 | |||||
3836 | for (const auto *FieldInit : Constructor->inits()) { | ||||
3837 | if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) | ||||
3838 | break; | ||||
3839 | |||||
3840 | Expr *InitExpr = FieldInit->getInit(); | ||||
3841 | if (!InitExpr) | ||||
3842 | continue; | ||||
3843 | |||||
3844 | if (CXXDefaultInitExpr *Default = | ||||
3845 | dyn_cast<CXXDefaultInitExpr>(InitExpr)) { | ||||
3846 | InitExpr = Default->getExpr(); | ||||
3847 | if (!InitExpr) | ||||
3848 | continue; | ||||
3849 | // In class initializers will point to the constructor. | ||||
3850 | UninitializedChecker.CheckInitializer(InitExpr, Constructor, | ||||
3851 | FieldInit->getAnyMember(), | ||||
3852 | FieldInit->getBaseClass()); | ||||
3853 | } else { | ||||
3854 | UninitializedChecker.CheckInitializer(InitExpr, nullptr, | ||||
3855 | FieldInit->getAnyMember(), | ||||
3856 | FieldInit->getBaseClass()); | ||||
3857 | } | ||||
3858 | } | ||||
3859 | } | ||||
3860 | } // namespace | ||||
3861 | |||||
3862 | /// Enter a new C++ default initializer scope. After calling this, the | ||||
3863 | /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if | ||||
3864 | /// parsing or instantiating the initializer failed. | ||||
3865 | void Sema::ActOnStartCXXInClassMemberInitializer() { | ||||
3866 | // Create a synthetic function scope to represent the call to the constructor | ||||
3867 | // that notionally surrounds a use of this initializer. | ||||
3868 | PushFunctionScope(); | ||||
3869 | } | ||||
3870 | |||||
3871 | void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { | ||||
3872 | if (!D.isFunctionDeclarator()) | ||||
3873 | return; | ||||
3874 | auto &FTI = D.getFunctionTypeInfo(); | ||||
3875 | if (!FTI.Params) | ||||
3876 | return; | ||||
3877 | for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, | ||||
3878 | FTI.NumParams)) { | ||||
3879 | auto *ParamDecl = cast<NamedDecl>(Param.Param); | ||||
3880 | if (ParamDecl->getDeclName()) | ||||
3881 | PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); | ||||
3882 | } | ||||
3883 | } | ||||
3884 | |||||
3885 | ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { | ||||
3886 | if (ConstraintExpr.isInvalid()) | ||||
3887 | return ExprError(); | ||||
3888 | return CorrectDelayedTyposInExpr(ConstraintExpr); | ||||
3889 | } | ||||
3890 | |||||
3891 | /// This is invoked after parsing an in-class initializer for a | ||||
3892 | /// non-static C++ class member, and after instantiating an in-class initializer | ||||
3893 | /// in a class template. Such actions are deferred until the class is complete. | ||||
3894 | void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, | ||||
3895 | SourceLocation InitLoc, | ||||
3896 | Expr *InitExpr) { | ||||
3897 | // Pop the notional constructor scope we created earlier. | ||||
3898 | PopFunctionScopeInfo(nullptr, D); | ||||
3899 | |||||
3900 | FieldDecl *FD = dyn_cast<FieldDecl>(D); | ||||
3901 | assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&(((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle () != ICIS_NoInit) && "must set init style when field is created" ) ? static_cast<void> (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 3902, __PRETTY_FUNCTION__)) | ||||
3902 | "must set init style when field is created")(((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle () != ICIS_NoInit) && "must set init style when field is created" ) ? static_cast<void> (0) : __assert_fail ("(isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && \"must set init style when field is created\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 3902, __PRETTY_FUNCTION__)); | ||||
3903 | |||||
3904 | if (!InitExpr) { | ||||
3905 | D->setInvalidDecl(); | ||||
3906 | if (FD) | ||||
3907 | FD->removeInClassInitializer(); | ||||
3908 | return; | ||||
3909 | } | ||||
3910 | |||||
3911 | if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { | ||||
3912 | FD->setInvalidDecl(); | ||||
3913 | FD->removeInClassInitializer(); | ||||
3914 | return; | ||||
3915 | } | ||||
3916 | |||||
3917 | ExprResult Init = InitExpr; | ||||
3918 | if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { | ||||
3919 | InitializedEntity Entity = | ||||
3920 | InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); | ||||
3921 | InitializationKind Kind = | ||||
3922 | FD->getInClassInitStyle() == ICIS_ListInit | ||||
3923 | ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), | ||||
3924 | InitExpr->getBeginLoc(), | ||||
3925 | InitExpr->getEndLoc()) | ||||
3926 | : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); | ||||
3927 | InitializationSequence Seq(*this, Entity, Kind, InitExpr); | ||||
3928 | Init = Seq.Perform(*this, Entity, Kind, InitExpr); | ||||
3929 | if (Init.isInvalid()) { | ||||
3930 | FD->setInvalidDecl(); | ||||
3931 | return; | ||||
3932 | } | ||||
3933 | } | ||||
3934 | |||||
3935 | // C++11 [class.base.init]p7: | ||||
3936 | // The initialization of each base and member constitutes a | ||||
3937 | // full-expression. | ||||
3938 | Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); | ||||
3939 | if (Init.isInvalid()) { | ||||
3940 | FD->setInvalidDecl(); | ||||
3941 | return; | ||||
3942 | } | ||||
3943 | |||||
3944 | InitExpr = Init.get(); | ||||
3945 | |||||
3946 | FD->setInClassInitializer(InitExpr); | ||||
3947 | } | ||||
3948 | |||||
3949 | /// Find the direct and/or virtual base specifiers that | ||||
3950 | /// correspond to the given base type, for use in base initialization | ||||
3951 | /// within a constructor. | ||||
3952 | static bool FindBaseInitializer(Sema &SemaRef, | ||||
3953 | CXXRecordDecl *ClassDecl, | ||||
3954 | QualType BaseType, | ||||
3955 | const CXXBaseSpecifier *&DirectBaseSpec, | ||||
3956 | const CXXBaseSpecifier *&VirtualBaseSpec) { | ||||
3957 | // First, check for a direct base class. | ||||
3958 | DirectBaseSpec = nullptr; | ||||
3959 | for (const auto &Base : ClassDecl->bases()) { | ||||
3960 | if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { | ||||
3961 | // We found a direct base of this type. That's what we're | ||||
3962 | // initializing. | ||||
3963 | DirectBaseSpec = &Base; | ||||
3964 | break; | ||||
3965 | } | ||||
3966 | } | ||||
3967 | |||||
3968 | // Check for a virtual base class. | ||||
3969 | // FIXME: We might be able to short-circuit this if we know in advance that | ||||
3970 | // there are no virtual bases. | ||||
3971 | VirtualBaseSpec = nullptr; | ||||
3972 | if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { | ||||
3973 | // We haven't found a base yet; search the class hierarchy for a | ||||
3974 | // virtual base class. | ||||
3975 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, | ||||
3976 | /*DetectVirtual=*/false); | ||||
3977 | if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), | ||||
3978 | SemaRef.Context.getTypeDeclType(ClassDecl), | ||||
3979 | BaseType, Paths)) { | ||||
3980 | for (CXXBasePaths::paths_iterator Path = Paths.begin(); | ||||
3981 | Path != Paths.end(); ++Path) { | ||||
3982 | if (Path->back().Base->isVirtual()) { | ||||
3983 | VirtualBaseSpec = Path->back().Base; | ||||
3984 | break; | ||||
3985 | } | ||||
3986 | } | ||||
3987 | } | ||||
3988 | } | ||||
3989 | |||||
3990 | return DirectBaseSpec || VirtualBaseSpec; | ||||
3991 | } | ||||
3992 | |||||
3993 | /// Handle a C++ member initializer using braced-init-list syntax. | ||||
3994 | MemInitResult | ||||
3995 | Sema::ActOnMemInitializer(Decl *ConstructorD, | ||||
3996 | Scope *S, | ||||
3997 | CXXScopeSpec &SS, | ||||
3998 | IdentifierInfo *MemberOrBase, | ||||
3999 | ParsedType TemplateTypeTy, | ||||
4000 | const DeclSpec &DS, | ||||
4001 | SourceLocation IdLoc, | ||||
4002 | Expr *InitList, | ||||
4003 | SourceLocation EllipsisLoc) { | ||||
4004 | return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, | ||||
4005 | DS, IdLoc, InitList, | ||||
4006 | EllipsisLoc); | ||||
4007 | } | ||||
4008 | |||||
4009 | /// Handle a C++ member initializer using parentheses syntax. | ||||
4010 | MemInitResult | ||||
4011 | Sema::ActOnMemInitializer(Decl *ConstructorD, | ||||
4012 | Scope *S, | ||||
4013 | CXXScopeSpec &SS, | ||||
4014 | IdentifierInfo *MemberOrBase, | ||||
4015 | ParsedType TemplateTypeTy, | ||||
4016 | const DeclSpec &DS, | ||||
4017 | SourceLocation IdLoc, | ||||
4018 | SourceLocation LParenLoc, | ||||
4019 | ArrayRef<Expr *> Args, | ||||
4020 | SourceLocation RParenLoc, | ||||
4021 | SourceLocation EllipsisLoc) { | ||||
4022 | Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); | ||||
4023 | return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, | ||||
4024 | DS, IdLoc, List, EllipsisLoc); | ||||
4025 | } | ||||
4026 | |||||
4027 | namespace { | ||||
4028 | |||||
4029 | // Callback to only accept typo corrections that can be a valid C++ member | ||||
4030 | // intializer: either a non-static field member or a base class. | ||||
4031 | class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { | ||||
4032 | public: | ||||
4033 | explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) | ||||
4034 | : ClassDecl(ClassDecl) {} | ||||
4035 | |||||
4036 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||
4037 | if (NamedDecl *ND = candidate.getCorrectionDecl()) { | ||||
4038 | if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) | ||||
4039 | return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); | ||||
4040 | return isa<TypeDecl>(ND); | ||||
4041 | } | ||||
4042 | return false; | ||||
4043 | } | ||||
4044 | |||||
4045 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||
4046 | return std::make_unique<MemInitializerValidatorCCC>(*this); | ||||
4047 | } | ||||
4048 | |||||
4049 | private: | ||||
4050 | CXXRecordDecl *ClassDecl; | ||||
4051 | }; | ||||
4052 | |||||
4053 | } | ||||
4054 | |||||
4055 | ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, | ||||
4056 | CXXScopeSpec &SS, | ||||
4057 | ParsedType TemplateTypeTy, | ||||
4058 | IdentifierInfo *MemberOrBase) { | ||||
4059 | if (SS.getScopeRep() || TemplateTypeTy) | ||||
4060 | return nullptr; | ||||
4061 | DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); | ||||
4062 | if (Result.empty()) | ||||
4063 | return nullptr; | ||||
4064 | ValueDecl *Member; | ||||
4065 | if ((Member = dyn_cast<FieldDecl>(Result.front())) || | ||||
4066 | (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) | ||||
4067 | return Member; | ||||
4068 | return nullptr; | ||||
4069 | } | ||||
4070 | |||||
4071 | /// Handle a C++ member initializer. | ||||
4072 | MemInitResult | ||||
4073 | Sema::BuildMemInitializer(Decl *ConstructorD, | ||||
4074 | Scope *S, | ||||
4075 | CXXScopeSpec &SS, | ||||
4076 | IdentifierInfo *MemberOrBase, | ||||
4077 | ParsedType TemplateTypeTy, | ||||
4078 | const DeclSpec &DS, | ||||
4079 | SourceLocation IdLoc, | ||||
4080 | Expr *Init, | ||||
4081 | SourceLocation EllipsisLoc) { | ||||
4082 | ExprResult Res = CorrectDelayedTyposInExpr(Init); | ||||
4083 | if (!Res.isUsable()) | ||||
4084 | return true; | ||||
4085 | Init = Res.get(); | ||||
4086 | |||||
4087 | if (!ConstructorD) | ||||
4088 | return true; | ||||
4089 | |||||
4090 | AdjustDeclIfTemplate(ConstructorD); | ||||
4091 | |||||
4092 | CXXConstructorDecl *Constructor | ||||
4093 | = dyn_cast<CXXConstructorDecl>(ConstructorD); | ||||
4094 | if (!Constructor) { | ||||
4095 | // The user wrote a constructor initializer on a function that is | ||||
4096 | // not a C++ constructor. Ignore the error for now, because we may | ||||
4097 | // have more member initializers coming; we'll diagnose it just | ||||
4098 | // once in ActOnMemInitializers. | ||||
4099 | return true; | ||||
4100 | } | ||||
4101 | |||||
4102 | CXXRecordDecl *ClassDecl = Constructor->getParent(); | ||||
4103 | |||||
4104 | // C++ [class.base.init]p2: | ||||
4105 | // Names in a mem-initializer-id are looked up in the scope of the | ||||
4106 | // constructor's class and, if not found in that scope, are looked | ||||
4107 | // up in the scope containing the constructor's definition. | ||||
4108 | // [Note: if the constructor's class contains a member with the | ||||
4109 | // same name as a direct or virtual base class of the class, a | ||||
4110 | // mem-initializer-id naming the member or base class and composed | ||||
4111 | // of a single identifier refers to the class member. A | ||||
4112 | // mem-initializer-id for the hidden base class may be specified | ||||
4113 | // using a qualified name. ] | ||||
4114 | |||||
4115 | // Look for a member, first. | ||||
4116 | if (ValueDecl *Member = tryLookupCtorInitMemberDecl( | ||||
4117 | ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { | ||||
4118 | if (EllipsisLoc.isValid()) | ||||
4119 | Diag(EllipsisLoc, diag::err_pack_expansion_member_init) | ||||
4120 | << MemberOrBase | ||||
4121 | << SourceRange(IdLoc, Init->getSourceRange().getEnd()); | ||||
4122 | |||||
4123 | return BuildMemberInitializer(Member, Init, IdLoc); | ||||
4124 | } | ||||
4125 | // It didn't name a member, so see if it names a class. | ||||
4126 | QualType BaseType; | ||||
4127 | TypeSourceInfo *TInfo = nullptr; | ||||
4128 | |||||
4129 | if (TemplateTypeTy) { | ||||
4130 | BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); | ||||
4131 | if (BaseType.isNull()) | ||||
4132 | return true; | ||||
4133 | } else if (DS.getTypeSpecType() == TST_decltype) { | ||||
4134 | BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); | ||||
4135 | } else if (DS.getTypeSpecType() == TST_decltype_auto) { | ||||
4136 | Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); | ||||
4137 | return true; | ||||
4138 | } else { | ||||
4139 | LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); | ||||
4140 | LookupParsedName(R, S, &SS); | ||||
4141 | |||||
4142 | TypeDecl *TyD = R.getAsSingle<TypeDecl>(); | ||||
4143 | if (!TyD) { | ||||
4144 | if (R.isAmbiguous()) return true; | ||||
4145 | |||||
4146 | // We don't want access-control diagnostics here. | ||||
4147 | R.suppressDiagnostics(); | ||||
4148 | |||||
4149 | if (SS.isSet() && isDependentScopeSpecifier(SS)) { | ||||
4150 | bool NotUnknownSpecialization = false; | ||||
4151 | DeclContext *DC = computeDeclContext(SS, false); | ||||
4152 | if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) | ||||
4153 | NotUnknownSpecialization = !Record->hasAnyDependentBases(); | ||||
4154 | |||||
4155 | if (!NotUnknownSpecialization) { | ||||
4156 | // When the scope specifier can refer to a member of an unknown | ||||
4157 | // specialization, we take it as a type name. | ||||
4158 | BaseType = CheckTypenameType(ETK_None, SourceLocation(), | ||||
4159 | SS.getWithLocInContext(Context), | ||||
4160 | *MemberOrBase, IdLoc); | ||||
4161 | if (BaseType.isNull()) | ||||
4162 | return true; | ||||
4163 | |||||
4164 | TInfo = Context.CreateTypeSourceInfo(BaseType); | ||||
4165 | DependentNameTypeLoc TL = | ||||
4166 | TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); | ||||
4167 | if (!TL.isNull()) { | ||||
4168 | TL.setNameLoc(IdLoc); | ||||
4169 | TL.setElaboratedKeywordLoc(SourceLocation()); | ||||
4170 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||
4171 | } | ||||
4172 | |||||
4173 | R.clear(); | ||||
4174 | R.setLookupName(MemberOrBase); | ||||
4175 | } | ||||
4176 | } | ||||
4177 | |||||
4178 | // If no results were found, try to correct typos. | ||||
4179 | TypoCorrection Corr; | ||||
4180 | MemInitializerValidatorCCC CCC(ClassDecl); | ||||
4181 | if (R.empty() && BaseType.isNull() && | ||||
4182 | (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, | ||||
4183 | CCC, CTK_ErrorRecovery, ClassDecl))) { | ||||
4184 | if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { | ||||
4185 | // We have found a non-static data member with a similar | ||||
4186 | // name to what was typed; complain and initialize that | ||||
4187 | // member. | ||||
4188 | diagnoseTypo(Corr, | ||||
4189 | PDiag(diag::err_mem_init_not_member_or_class_suggest) | ||||
4190 | << MemberOrBase << true); | ||||
4191 | return BuildMemberInitializer(Member, Init, IdLoc); | ||||
4192 | } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { | ||||
4193 | const CXXBaseSpecifier *DirectBaseSpec; | ||||
4194 | const CXXBaseSpecifier *VirtualBaseSpec; | ||||
4195 | if (FindBaseInitializer(*this, ClassDecl, | ||||
4196 | Context.getTypeDeclType(Type), | ||||
4197 | DirectBaseSpec, VirtualBaseSpec)) { | ||||
4198 | // We have found a direct or virtual base class with a | ||||
4199 | // similar name to what was typed; complain and initialize | ||||
4200 | // that base class. | ||||
4201 | diagnoseTypo(Corr, | ||||
4202 | PDiag(diag::err_mem_init_not_member_or_class_suggest) | ||||
4203 | << MemberOrBase << false, | ||||
4204 | PDiag() /*Suppress note, we provide our own.*/); | ||||
4205 | |||||
4206 | const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec | ||||
4207 | : VirtualBaseSpec; | ||||
4208 | Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) | ||||
4209 | << BaseSpec->getType() << BaseSpec->getSourceRange(); | ||||
4210 | |||||
4211 | TyD = Type; | ||||
4212 | } | ||||
4213 | } | ||||
4214 | } | ||||
4215 | |||||
4216 | if (!TyD && BaseType.isNull()) { | ||||
4217 | Diag(IdLoc, diag::err_mem_init_not_member_or_class) | ||||
4218 | << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); | ||||
4219 | return true; | ||||
4220 | } | ||||
4221 | } | ||||
4222 | |||||
4223 | if (BaseType.isNull()) { | ||||
4224 | BaseType = Context.getTypeDeclType(TyD); | ||||
4225 | MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); | ||||
4226 | if (SS.isSet()) { | ||||
4227 | BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), | ||||
4228 | BaseType); | ||||
4229 | TInfo = Context.CreateTypeSourceInfo(BaseType); | ||||
4230 | ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); | ||||
4231 | TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); | ||||
4232 | TL.setElaboratedKeywordLoc(SourceLocation()); | ||||
4233 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||
4234 | } | ||||
4235 | } | ||||
4236 | } | ||||
4237 | |||||
4238 | if (!TInfo) | ||||
4239 | TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); | ||||
4240 | |||||
4241 | return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); | ||||
4242 | } | ||||
4243 | |||||
4244 | MemInitResult | ||||
4245 | Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, | ||||
4246 | SourceLocation IdLoc) { | ||||
4247 | FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); | ||||
4248 | IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); | ||||
4249 | assert((DirectMember || IndirectMember) &&(((DirectMember || IndirectMember) && "Member must be a FieldDecl or IndirectFieldDecl" ) ? static_cast<void> (0) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 4250, __PRETTY_FUNCTION__)) | ||||
4250 | "Member must be a FieldDecl or IndirectFieldDecl")(((DirectMember || IndirectMember) && "Member must be a FieldDecl or IndirectFieldDecl" ) ? static_cast<void> (0) : __assert_fail ("(DirectMember || IndirectMember) && \"Member must be a FieldDecl or IndirectFieldDecl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 4250, __PRETTY_FUNCTION__)); | ||||
4251 | |||||
4252 | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) | ||||
4253 | return true; | ||||
4254 | |||||
4255 | if (Member->isInvalidDecl()) | ||||
4256 | return true; | ||||
4257 | |||||
4258 | MultiExprArg Args; | ||||
4259 | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { | ||||
4260 | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); | ||||
4261 | } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { | ||||
4262 | Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); | ||||
4263 | } else { | ||||
4264 | // Template instantiation doesn't reconstruct ParenListExprs for us. | ||||
4265 | Args = Init; | ||||
4266 | } | ||||
4267 | |||||
4268 | SourceRange InitRange = Init->getSourceRange(); | ||||
4269 | |||||
4270 | if (Member->getType()->isDependentType() || Init->isTypeDependent()) { | ||||
4271 | // Can't check initialization for a member of dependent type or when | ||||
4272 | // any of the arguments are type-dependent expressions. | ||||
4273 | DiscardCleanupsInEvaluationContext(); | ||||
4274 | } else { | ||||
4275 | bool InitList = false; | ||||
4276 | if (isa<InitListExpr>(Init)) { | ||||
4277 | InitList = true; | ||||
4278 | Args = Init; | ||||
4279 | } | ||||
4280 | |||||
4281 | // Initialize the member. | ||||
4282 | InitializedEntity MemberEntity = | ||||
4283 | DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) | ||||
4284 | : InitializedEntity::InitializeMember(IndirectMember, | ||||
4285 | nullptr); | ||||
4286 | InitializationKind Kind = | ||||
4287 | InitList ? InitializationKind::CreateDirectList( | ||||
4288 | IdLoc, Init->getBeginLoc(), Init->getEndLoc()) | ||||
4289 | : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), | ||||
4290 | InitRange.getEnd()); | ||||
4291 | |||||
4292 | InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); | ||||
4293 | ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, | ||||
4294 | nullptr); | ||||
4295 | if (MemberInit.isInvalid()) | ||||
4296 | return true; | ||||
4297 | |||||
4298 | // C++11 [class.base.init]p7: | ||||
4299 | // The initialization of each base and member constitutes a | ||||
4300 | // full-expression. | ||||
4301 | MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), | ||||
4302 | /*DiscardedValue*/ false); | ||||
4303 | if (MemberInit.isInvalid()) | ||||
4304 | return true; | ||||
4305 | |||||
4306 | Init = MemberInit.get(); | ||||
4307 | } | ||||
4308 | |||||
4309 | if (DirectMember) { | ||||
4310 | return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, | ||||
4311 | InitRange.getBegin(), Init, | ||||
4312 | InitRange.getEnd()); | ||||
4313 | } else { | ||||
4314 | return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, | ||||
4315 | InitRange.getBegin(), Init, | ||||
4316 | InitRange.getEnd()); | ||||
4317 | } | ||||
4318 | } | ||||
4319 | |||||
4320 | MemInitResult | ||||
4321 | Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, | ||||
4322 | CXXRecordDecl *ClassDecl) { | ||||
4323 | SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); | ||||
4324 | if (!LangOpts.CPlusPlus11) | ||||
4325 | return Diag(NameLoc, diag::err_delegating_ctor) | ||||
4326 | << TInfo->getTypeLoc().getLocalSourceRange(); | ||||
4327 | Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); | ||||
4328 | |||||
4329 | bool InitList = true; | ||||
4330 | MultiExprArg Args = Init; | ||||
4331 | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { | ||||
4332 | InitList = false; | ||||
4333 | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); | ||||
4334 | } | ||||
4335 | |||||
4336 | SourceRange InitRange = Init->getSourceRange(); | ||||
4337 | // Initialize the object. | ||||
4338 | InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( | ||||
4339 | QualType(ClassDecl->getTypeForDecl(), 0)); | ||||
4340 | InitializationKind Kind = | ||||
4341 | InitList ? InitializationKind::CreateDirectList( | ||||
4342 | NameLoc, Init->getBeginLoc(), Init->getEndLoc()) | ||||
4343 | : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), | ||||
4344 | InitRange.getEnd()); | ||||
4345 | InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); | ||||
4346 | ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, | ||||
4347 | Args, nullptr); | ||||
4348 | if (DelegationInit.isInvalid()) | ||||
4349 | return true; | ||||
4350 | |||||
4351 | assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&((cast<CXXConstructExpr>(DelegationInit.get())->getConstructor () && "Delegating constructor with no target?") ? static_cast <void> (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 4352, __PRETTY_FUNCTION__)) | ||||
4352 | "Delegating constructor with no target?")((cast<CXXConstructExpr>(DelegationInit.get())->getConstructor () && "Delegating constructor with no target?") ? static_cast <void> (0) : __assert_fail ("cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && \"Delegating constructor with no target?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 4352, __PRETTY_FUNCTION__)); | ||||
4353 | |||||
4354 | // C++11 [class.base.init]p7: | ||||
4355 | // The initialization of each base and member constitutes a | ||||
4356 | // full-expression. | ||||
4357 | DelegationInit = ActOnFinishFullExpr( | ||||
4358 | DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); | ||||
4359 | if (DelegationInit.isInvalid()) | ||||
4360 | return true; | ||||
4361 | |||||
4362 | // If we are in a dependent context, template instantiation will | ||||
4363 | // perform this type-checking again. Just save the arguments that we | ||||
4364 | // received in a ParenListExpr. | ||||
4365 | // FIXME: This isn't quite ideal, since our ASTs don't capture all | ||||
4366 | // of the information that we have about the base | ||||
4367 | // initializer. However, deconstructing the ASTs is a dicey process, | ||||
4368 | // and this approach is far more likely to get the corner cases right. | ||||
4369 | if (CurContext->isDependentContext()) | ||||
4370 | DelegationInit = Init; | ||||
4371 | |||||
4372 | return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), | ||||
4373 | DelegationInit.getAs<Expr>(), | ||||
4374 | InitRange.getEnd()); | ||||
4375 | } | ||||
4376 | |||||
4377 | MemInitResult | ||||
4378 | Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, | ||||
4379 | Expr *Init, CXXRecordDecl *ClassDecl, | ||||
4380 | SourceLocation EllipsisLoc) { | ||||
4381 | SourceLocation BaseLoc | ||||
4382 | = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); | ||||
4383 | |||||
4384 | if (!BaseType->isDependentType() && !BaseType->isRecordType()) | ||||
4385 | return Diag(BaseLoc, diag::err_base_init_does_not_name_class) | ||||
4386 | << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); | ||||
4387 | |||||
4388 | // C++ [class.base.init]p2: | ||||
4389 | // [...] Unless the mem-initializer-id names a nonstatic data | ||||
4390 | // member of the constructor's class or a direct or virtual base | ||||
4391 | // of that class, the mem-initializer is ill-formed. A | ||||
4392 | // mem-initializer-list can initialize a base class using any | ||||
4393 | // name that denotes that base class type. | ||||
4394 | bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); | ||||
4395 | |||||
4396 | SourceRange InitRange = Init->getSourceRange(); | ||||
4397 | if (EllipsisLoc.isValid()) { | ||||
4398 | // This is a pack expansion. | ||||
4399 | if (!BaseType->containsUnexpandedParameterPack()) { | ||||
4400 | Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) | ||||
4401 | << SourceRange(BaseLoc, InitRange.getEnd()); | ||||
4402 | |||||
4403 | EllipsisLoc = SourceLocation(); | ||||
4404 | } | ||||
4405 | } else { | ||||
4406 | // Check for any unexpanded parameter packs. | ||||
4407 | if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) | ||||
4408 | return true; | ||||
4409 | |||||
4410 | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) | ||||
4411 | return true; | ||||
4412 | } | ||||
4413 | |||||
4414 | // Check for direct and virtual base classes. | ||||
4415 | const CXXBaseSpecifier *DirectBaseSpec = nullptr; | ||||
4416 | const CXXBaseSpecifier *VirtualBaseSpec = nullptr; | ||||
4417 | if (!Dependent) { | ||||
4418 | if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), | ||||
4419 | BaseType)) | ||||
4420 | return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); | ||||
4421 | |||||
4422 | FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, | ||||
4423 | VirtualBaseSpec); | ||||
4424 | |||||
4425 | // C++ [base.class.init]p2: | ||||
4426 | // Unless the mem-initializer-id names a nonstatic data member of the | ||||
4427 | // constructor's class or a direct or virtual base of that class, the | ||||
4428 | // mem-initializer is ill-formed. | ||||
4429 | if (!DirectBaseSpec && !VirtualBaseSpec) { | ||||
4430 | // If the class has any dependent bases, then it's possible that | ||||
4431 | // one of those types will resolve to the same type as | ||||
4432 | // BaseType. Therefore, just treat this as a dependent base | ||||
4433 | // class initialization. FIXME: Should we try to check the | ||||
4434 | // initialization anyway? It seems odd. | ||||
4435 | if (ClassDecl->hasAnyDependentBases()) | ||||
4436 | Dependent = true; | ||||
4437 | else | ||||
4438 | return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) | ||||
4439 | << BaseType << Context.getTypeDeclType(ClassDecl) | ||||
4440 | << BaseTInfo->getTypeLoc().getLocalSourceRange(); | ||||
4441 | } | ||||
4442 | } | ||||
4443 | |||||
4444 | if (Dependent) { | ||||
4445 | DiscardCleanupsInEvaluationContext(); | ||||
4446 | |||||
4447 | return new (Context) CXXCtorInitializer(Context, BaseTInfo, | ||||
4448 | /*IsVirtual=*/false, | ||||
4449 | InitRange.getBegin(), Init, | ||||
4450 | InitRange.getEnd(), EllipsisLoc); | ||||
4451 | } | ||||
4452 | |||||
4453 | // C++ [base.class.init]p2: | ||||
4454 | // If a mem-initializer-id is ambiguous because it designates both | ||||
4455 | // a direct non-virtual base class and an inherited virtual base | ||||
4456 | // class, the mem-initializer is ill-formed. | ||||
4457 | if (DirectBaseSpec && VirtualBaseSpec) | ||||
4458 | return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) | ||||
4459 | << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); | ||||
4460 | |||||
4461 | const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; | ||||
4462 | if (!BaseSpec) | ||||
4463 | BaseSpec = VirtualBaseSpec; | ||||
4464 | |||||
4465 | // Initialize the base. | ||||
4466 | bool InitList = true; | ||||
4467 | MultiExprArg Args = Init; | ||||
4468 | if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { | ||||
4469 | InitList = false; | ||||
4470 | Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); | ||||
4471 | } | ||||
4472 | |||||
4473 | InitializedEntity BaseEntity = | ||||
4474 | InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); | ||||
4475 | InitializationKind Kind = | ||||
4476 | InitList ? InitializationKind::CreateDirectList(BaseLoc) | ||||
4477 | : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), | ||||
4478 | InitRange.getEnd()); | ||||
4479 | InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); | ||||
4480 | ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); | ||||
4481 | if (BaseInit.isInvalid()) | ||||
4482 | return true; | ||||
4483 | |||||
4484 | // C++11 [class.base.init]p7: | ||||
4485 | // The initialization of each base and member constitutes a | ||||
4486 | // full-expression. | ||||
4487 | BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), | ||||
4488 | /*DiscardedValue*/ false); | ||||
4489 | if (BaseInit.isInvalid()) | ||||
4490 | return true; | ||||
4491 | |||||
4492 | // If we are in a dependent context, template instantiation will | ||||
4493 | // perform this type-checking again. Just save the arguments that we | ||||
4494 | // received in a ParenListExpr. | ||||
4495 | // FIXME: This isn't quite ideal, since our ASTs don't capture all | ||||
4496 | // of the information that we have about the base | ||||
4497 | // initializer. However, deconstructing the ASTs is a dicey process, | ||||
4498 | // and this approach is far more likely to get the corner cases right. | ||||
4499 | if (CurContext->isDependentContext()) | ||||
4500 | BaseInit = Init; | ||||
4501 | |||||
4502 | return new (Context) CXXCtorInitializer(Context, BaseTInfo, | ||||
4503 | BaseSpec->isVirtual(), | ||||
4504 | InitRange.getBegin(), | ||||
4505 | BaseInit.getAs<Expr>(), | ||||
4506 | InitRange.getEnd(), EllipsisLoc); | ||||
4507 | } | ||||
4508 | |||||
4509 | // Create a static_cast\<T&&>(expr). | ||||
4510 | static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { | ||||
4511 | if (T.isNull()) T = E->getType(); | ||||
4512 | QualType TargetType = SemaRef.BuildReferenceType( | ||||
4513 | T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); | ||||
4514 | SourceLocation ExprLoc = E->getBeginLoc(); | ||||
4515 | TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( | ||||
4516 | TargetType, ExprLoc); | ||||
4517 | |||||
4518 | return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, | ||||
4519 | SourceRange(ExprLoc, ExprLoc), | ||||
4520 | E->getSourceRange()).get(); | ||||
4521 | } | ||||
4522 | |||||
4523 | /// ImplicitInitializerKind - How an implicit base or member initializer should | ||||
4524 | /// initialize its base or member. | ||||
4525 | enum ImplicitInitializerKind { | ||||
4526 | IIK_Default, | ||||
4527 | IIK_Copy, | ||||
4528 | IIK_Move, | ||||
4529 | IIK_Inherit | ||||
4530 | }; | ||||
4531 | |||||
4532 | static bool | ||||
4533 | BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, | ||||
4534 | ImplicitInitializerKind ImplicitInitKind, | ||||
4535 | CXXBaseSpecifier *BaseSpec, | ||||
4536 | bool IsInheritedVirtualBase, | ||||
4537 | CXXCtorInitializer *&CXXBaseInit) { | ||||
4538 | InitializedEntity InitEntity | ||||
4539 | = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, | ||||
4540 | IsInheritedVirtualBase); | ||||
4541 | |||||
4542 | ExprResult BaseInit; | ||||
4543 | |||||
4544 | switch (ImplicitInitKind) { | ||||
4545 | case IIK_Inherit: | ||||
4546 | case IIK_Default: { | ||||
4547 | InitializationKind InitKind | ||||
4548 | = InitializationKind::CreateDefault(Constructor->getLocation()); | ||||
4549 | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); | ||||
4550 | BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); | ||||
4551 | break; | ||||
4552 | } | ||||
4553 | |||||
4554 | case IIK_Move: | ||||
4555 | case IIK_Copy: { | ||||
4556 | bool Moving = ImplicitInitKind == IIK_Move; | ||||
4557 | ParmVarDecl *Param = Constructor->getParamDecl(0); | ||||
4558 | QualType ParamType = Param->getType().getNonReferenceType(); | ||||
4559 | |||||
4560 | Expr *CopyCtorArg = | ||||
4561 | DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), | ||||
4562 | SourceLocation(), Param, false, | ||||
4563 | Constructor->getLocation(), ParamType, | ||||
4564 | VK_LValue, nullptr); | ||||
4565 | |||||
4566 | SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); | ||||
4567 | |||||
4568 | // Cast to the base class to avoid ambiguities. | ||||
4569 | QualType ArgTy = | ||||
4570 | SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), | ||||
4571 | ParamType.getQualifiers()); | ||||
4572 | |||||
4573 | if (Moving) { | ||||
4574 | CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); | ||||
4575 | } | ||||
4576 | |||||
4577 | CXXCastPath BasePath; | ||||
4578 | BasePath.push_back(BaseSpec); | ||||
4579 | CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, | ||||
4580 | CK_UncheckedDerivedToBase, | ||||
4581 | Moving ? VK_XValue : VK_LValue, | ||||
4582 | &BasePath).get(); | ||||
4583 | |||||
4584 | InitializationKind InitKind | ||||
4585 | = InitializationKind::CreateDirect(Constructor->getLocation(), | ||||
4586 | SourceLocation(), SourceLocation()); | ||||
4587 | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); | ||||
4588 | BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); | ||||
4589 | break; | ||||
4590 | } | ||||
4591 | } | ||||
4592 | |||||
4593 | BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); | ||||
4594 | if (BaseInit.isInvalid()) | ||||
4595 | return true; | ||||
4596 | |||||
4597 | CXXBaseInit = | ||||
4598 | new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, | ||||
4599 | SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), | ||||
4600 | SourceLocation()), | ||||
4601 | BaseSpec->isVirtual(), | ||||
4602 | SourceLocation(), | ||||
4603 | BaseInit.getAs<Expr>(), | ||||
4604 | SourceLocation(), | ||||
4605 | SourceLocation()); | ||||
4606 | |||||
4607 | return false; | ||||
4608 | } | ||||
4609 | |||||
4610 | static bool RefersToRValueRef(Expr *MemRef) { | ||||
4611 | ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); | ||||
4612 | return Referenced->getType()->isRValueReferenceType(); | ||||
4613 | } | ||||
4614 | |||||
4615 | static bool | ||||
4616 | BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, | ||||
4617 | ImplicitInitializerKind ImplicitInitKind, | ||||
4618 | FieldDecl *Field, IndirectFieldDecl *Indirect, | ||||
4619 | CXXCtorInitializer *&CXXMemberInit) { | ||||
4620 | if (Field->isInvalidDecl()) | ||||
4621 | return true; | ||||
4622 | |||||
4623 | SourceLocation Loc = Constructor->getLocation(); | ||||
4624 | |||||
4625 | if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { | ||||
4626 | bool Moving = ImplicitInitKind == IIK_Move; | ||||
4627 | ParmVarDecl *Param = Constructor->getParamDecl(0); | ||||
4628 | QualType ParamType = Param->getType().getNonReferenceType(); | ||||
4629 | |||||
4630 | // Suppress copying zero-width bitfields. | ||||
4631 | if (Field->isZeroLengthBitField(SemaRef.Context)) | ||||
4632 | return false; | ||||
4633 | |||||
4634 | Expr *MemberExprBase = | ||||
4635 | DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), | ||||
4636 | SourceLocation(), Param, false, | ||||
4637 | Loc, ParamType, VK_LValue, nullptr); | ||||
4638 | |||||
4639 | SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); | ||||
4640 | |||||
4641 | if (Moving) { | ||||
4642 | MemberExprBase = CastForMoving(SemaRef, MemberExprBase); | ||||
4643 | } | ||||
4644 | |||||
4645 | // Build a reference to this field within the parameter. | ||||
4646 | CXXScopeSpec SS; | ||||
4647 | LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, | ||||
4648 | Sema::LookupMemberName); | ||||
4649 | MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) | ||||
4650 | : cast<ValueDecl>(Field), AS_public); | ||||
4651 | MemberLookup.resolveKind(); | ||||
4652 | ExprResult CtorArg | ||||
4653 | = SemaRef.BuildMemberReferenceExpr(MemberExprBase, | ||||
4654 | ParamType, Loc, | ||||
4655 | /*IsArrow=*/false, | ||||
4656 | SS, | ||||
4657 | /*TemplateKWLoc=*/SourceLocation(), | ||||
4658 | /*FirstQualifierInScope=*/nullptr, | ||||
4659 | MemberLookup, | ||||
4660 | /*TemplateArgs=*/nullptr, | ||||
4661 | /*S*/nullptr); | ||||
4662 | if (CtorArg.isInvalid()) | ||||
4663 | return true; | ||||
4664 | |||||
4665 | // C++11 [class.copy]p15: | ||||
4666 | // - if a member m has rvalue reference type T&&, it is direct-initialized | ||||
4667 | // with static_cast<T&&>(x.m); | ||||
4668 | if (RefersToRValueRef(CtorArg.get())) { | ||||
4669 | CtorArg = CastForMoving(SemaRef, CtorArg.get()); | ||||
4670 | } | ||||
4671 | |||||
4672 | InitializedEntity Entity = | ||||
4673 | Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, | ||||
4674 | /*Implicit*/ true) | ||||
4675 | : InitializedEntity::InitializeMember(Field, nullptr, | ||||
4676 | /*Implicit*/ true); | ||||
4677 | |||||
4678 | // Direct-initialize to use the copy constructor. | ||||
4679 | InitializationKind InitKind = | ||||
4680 | InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); | ||||
4681 | |||||
4682 | Expr *CtorArgE = CtorArg.getAs<Expr>(); | ||||
4683 | InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); | ||||
4684 | ExprResult MemberInit = | ||||
4685 | InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); | ||||
4686 | MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); | ||||
4687 | if (MemberInit.isInvalid()) | ||||
4688 | return true; | ||||
4689 | |||||
4690 | if (Indirect) | ||||
4691 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( | ||||
4692 | SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); | ||||
4693 | else | ||||
4694 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( | ||||
4695 | SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); | ||||
4696 | return false; | ||||
4697 | } | ||||
4698 | |||||
4699 | assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&(((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit ) && "Unhandled implicit init kind!") ? static_cast< void> (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 4700, __PRETTY_FUNCTION__)) | ||||
4700 | "Unhandled implicit init kind!")(((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit ) && "Unhandled implicit init kind!") ? static_cast< void> (0) : __assert_fail ("(ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && \"Unhandled implicit init kind!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 4700, __PRETTY_FUNCTION__)); | ||||
4701 | |||||
4702 | QualType FieldBaseElementType = | ||||
4703 | SemaRef.Context.getBaseElementType(Field->getType()); | ||||
4704 | |||||
4705 | if (FieldBaseElementType->isRecordType()) { | ||||
4706 | InitializedEntity InitEntity = | ||||
4707 | Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, | ||||
4708 | /*Implicit*/ true) | ||||
4709 | : InitializedEntity::InitializeMember(Field, nullptr, | ||||
4710 | /*Implicit*/ true); | ||||
4711 | InitializationKind InitKind = | ||||
4712 | InitializationKind::CreateDefault(Loc); | ||||
4713 | |||||
4714 | InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); | ||||
4715 | ExprResult MemberInit = | ||||
4716 | InitSeq.Perform(SemaRef, InitEntity, InitKind, None); | ||||
4717 | |||||
4718 | MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); | ||||
4719 | if (MemberInit.isInvalid()) | ||||
4720 | return true; | ||||
4721 | |||||
4722 | if (Indirect) | ||||
4723 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, | ||||
4724 | Indirect, Loc, | ||||
4725 | Loc, | ||||
4726 | MemberInit.get(), | ||||
4727 | Loc); | ||||
4728 | else | ||||
4729 | CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, | ||||
4730 | Field, Loc, Loc, | ||||
4731 | MemberInit.get(), | ||||
4732 | Loc); | ||||
4733 | return false; | ||||
4734 | } | ||||
4735 | |||||
4736 | if (!Field->getParent()->isUnion()) { | ||||
4737 | if (FieldBaseElementType->isReferenceType()) { | ||||
4738 | SemaRef.Diag(Constructor->getLocation(), | ||||
4739 | diag::err_uninitialized_member_in_ctor) | ||||
4740 | << (int)Constructor->isImplicit() | ||||
4741 | << SemaRef.Context.getTagDeclType(Constructor->getParent()) | ||||
4742 | << 0 << Field->getDeclName(); | ||||
4743 | SemaRef.Diag(Field->getLocation(), diag::note_declared_at); | ||||
4744 | return true; | ||||
4745 | } | ||||
4746 | |||||
4747 | if (FieldBaseElementType.isConstQualified()) { | ||||
4748 | SemaRef.Diag(Constructor->getLocation(), | ||||
4749 | diag::err_uninitialized_member_in_ctor) | ||||
4750 | << (int)Constructor->isImplicit() | ||||
4751 | << SemaRef.Context.getTagDeclType(Constructor->getParent()) | ||||
4752 | << 1 << Field->getDeclName(); | ||||
4753 | SemaRef.Diag(Field->getLocation(), diag::note_declared_at); | ||||
4754 | return true; | ||||
4755 | } | ||||
4756 | } | ||||
4757 | |||||
4758 | if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { | ||||
4759 | // ARC and Weak: | ||||
4760 | // Default-initialize Objective-C pointers to NULL. | ||||
4761 | CXXMemberInit | ||||
4762 | = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, | ||||
4763 | Loc, Loc, | ||||
4764 | new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), | ||||
4765 | Loc); | ||||
4766 | return false; | ||||
4767 | } | ||||
4768 | |||||
4769 | // Nothing to initialize. | ||||
4770 | CXXMemberInit = nullptr; | ||||
4771 | return false; | ||||
4772 | } | ||||
4773 | |||||
4774 | namespace { | ||||
4775 | struct BaseAndFieldInfo { | ||||
4776 | Sema &S; | ||||
4777 | CXXConstructorDecl *Ctor; | ||||
4778 | bool AnyErrorsInInits; | ||||
4779 | ImplicitInitializerKind IIK; | ||||
4780 | llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; | ||||
4781 | SmallVector<CXXCtorInitializer*, 8> AllToInit; | ||||
4782 | llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; | ||||
4783 | |||||
4784 | BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) | ||||
4785 | : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { | ||||
4786 | bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); | ||||
4787 | if (Ctor->getInheritedConstructor()) | ||||
4788 | IIK = IIK_Inherit; | ||||
4789 | else if (Generated && Ctor->isCopyConstructor()) | ||||
4790 | IIK = IIK_Copy; | ||||
4791 | else if (Generated && Ctor->isMoveConstructor()) | ||||
4792 | IIK = IIK_Move; | ||||
4793 | else | ||||
4794 | IIK = IIK_Default; | ||||
4795 | } | ||||
4796 | |||||
4797 | bool isImplicitCopyOrMove() const { | ||||
4798 | switch (IIK) { | ||||
4799 | case IIK_Copy: | ||||
4800 | case IIK_Move: | ||||
4801 | return true; | ||||
4802 | |||||
4803 | case IIK_Default: | ||||
4804 | case IIK_Inherit: | ||||
4805 | return false; | ||||
4806 | } | ||||
4807 | |||||
4808 | llvm_unreachable("Invalid ImplicitInitializerKind!")::llvm::llvm_unreachable_internal("Invalid ImplicitInitializerKind!" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 4808); | ||||
4809 | } | ||||
4810 | |||||
4811 | bool addFieldInitializer(CXXCtorInitializer *Init) { | ||||
4812 | AllToInit.push_back(Init); | ||||
4813 | |||||
4814 | // Check whether this initializer makes the field "used". | ||||
4815 | if (Init->getInit()->HasSideEffects(S.Context)) | ||||
4816 | S.UnusedPrivateFields.remove(Init->getAnyMember()); | ||||
4817 | |||||
4818 | return false; | ||||
4819 | } | ||||
4820 | |||||
4821 | bool isInactiveUnionMember(FieldDecl *Field) { | ||||
4822 | RecordDecl *Record = Field->getParent(); | ||||
4823 | if (!Record->isUnion()) | ||||
4824 | return false; | ||||
4825 | |||||
4826 | if (FieldDecl *Active = | ||||
4827 | ActiveUnionMember.lookup(Record->getCanonicalDecl())) | ||||
4828 | return Active != Field->getCanonicalDecl(); | ||||
4829 | |||||
4830 | // In an implicit copy or move constructor, ignore any in-class initializer. | ||||
4831 | if (isImplicitCopyOrMove()) | ||||
4832 | return true; | ||||
4833 | |||||
4834 | // If there's no explicit initialization, the field is active only if it | ||||
4835 | // has an in-class initializer... | ||||
4836 | if (Field->hasInClassInitializer()) | ||||
4837 | return false; | ||||
4838 | // ... or it's an anonymous struct or union whose class has an in-class | ||||
4839 | // initializer. | ||||
4840 | if (!Field->isAnonymousStructOrUnion()) | ||||
4841 | return true; | ||||
4842 | CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); | ||||
4843 | return !FieldRD->hasInClassInitializer(); | ||||
4844 | } | ||||
4845 | |||||
4846 | /// Determine whether the given field is, or is within, a union member | ||||
4847 | /// that is inactive (because there was an initializer given for a different | ||||
4848 | /// member of the union, or because the union was not initialized at all). | ||||
4849 | bool isWithinInactiveUnionMember(FieldDecl *Field, | ||||
4850 | IndirectFieldDecl *Indirect) { | ||||
4851 | if (!Indirect) | ||||
4852 | return isInactiveUnionMember(Field); | ||||
4853 | |||||
4854 | for (auto *C : Indirect->chain()) { | ||||
4855 | FieldDecl *Field = dyn_cast<FieldDecl>(C); | ||||
4856 | if (Field && isInactiveUnionMember(Field)) | ||||
4857 | return true; | ||||
4858 | } | ||||
4859 | return false; | ||||
4860 | } | ||||
4861 | }; | ||||
4862 | } | ||||
4863 | |||||
4864 | /// Determine whether the given type is an incomplete or zero-lenfgth | ||||
4865 | /// array type. | ||||
4866 | static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { | ||||
4867 | if (T->isIncompleteArrayType()) | ||||
4868 | return true; | ||||
4869 | |||||
4870 | while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { | ||||
4871 | if (!ArrayT->getSize()) | ||||
4872 | return true; | ||||
4873 | |||||
4874 | T = ArrayT->getElementType(); | ||||
4875 | } | ||||
4876 | |||||
4877 | return false; | ||||
4878 | } | ||||
4879 | |||||
4880 | static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, | ||||
4881 | FieldDecl *Field, | ||||
4882 | IndirectFieldDecl *Indirect = nullptr) { | ||||
4883 | if (Field->isInvalidDecl()) | ||||
4884 | return false; | ||||
4885 | |||||
4886 | // Overwhelmingly common case: we have a direct initializer for this field. | ||||
4887 | if (CXXCtorInitializer *Init = | ||||
4888 | Info.AllBaseFields.lookup(Field->getCanonicalDecl())) | ||||
4889 | return Info.addFieldInitializer(Init); | ||||
4890 | |||||
4891 | // C++11 [class.base.init]p8: | ||||
4892 | // if the entity is a non-static data member that has a | ||||
4893 | // brace-or-equal-initializer and either | ||||
4894 | // -- the constructor's class is a union and no other variant member of that | ||||
4895 | // union is designated by a mem-initializer-id or | ||||
4896 | // -- the constructor's class is not a union, and, if the entity is a member | ||||
4897 | // of an anonymous union, no other member of that union is designated by | ||||
4898 | // a mem-initializer-id, | ||||
4899 | // the entity is initialized as specified in [dcl.init]. | ||||
4900 | // | ||||
4901 | // We also apply the same rules to handle anonymous structs within anonymous | ||||
4902 | // unions. | ||||
4903 | if (Info.isWithinInactiveUnionMember(Field, Indirect)) | ||||
4904 | return false; | ||||
4905 | |||||
4906 | if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { | ||||
4907 | ExprResult DIE = | ||||
4908 | SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); | ||||
4909 | if (DIE.isInvalid()) | ||||
4910 | return true; | ||||
4911 | |||||
4912 | auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); | ||||
4913 | SemaRef.checkInitializerLifetime(Entity, DIE.get()); | ||||
4914 | |||||
4915 | CXXCtorInitializer *Init; | ||||
4916 | if (Indirect) | ||||
4917 | Init = new (SemaRef.Context) | ||||
4918 | CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), | ||||
4919 | SourceLocation(), DIE.get(), SourceLocation()); | ||||
4920 | else | ||||
4921 | Init = new (SemaRef.Context) | ||||
4922 | CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), | ||||
4923 | SourceLocation(), DIE.get(), SourceLocation()); | ||||
4924 | return Info.addFieldInitializer(Init); | ||||
4925 | } | ||||
4926 | |||||
4927 | // Don't initialize incomplete or zero-length arrays. | ||||
4928 | if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) | ||||
4929 | return false; | ||||
4930 | |||||
4931 | // Don't try to build an implicit initializer if there were semantic | ||||
4932 | // errors in any of the initializers (and therefore we might be | ||||
4933 | // missing some that the user actually wrote). | ||||
4934 | if (Info.AnyErrorsInInits) | ||||
4935 | return false; | ||||
4936 | |||||
4937 | CXXCtorInitializer *Init = nullptr; | ||||
4938 | if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, | ||||
4939 | Indirect, Init)) | ||||
4940 | return true; | ||||
4941 | |||||
4942 | if (!Init) | ||||
4943 | return false; | ||||
4944 | |||||
4945 | return Info.addFieldInitializer(Init); | ||||
4946 | } | ||||
4947 | |||||
4948 | bool | ||||
4949 | Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, | ||||
4950 | CXXCtorInitializer *Initializer) { | ||||
4951 | assert(Initializer->isDelegatingInitializer())((Initializer->isDelegatingInitializer()) ? static_cast< void> (0) : __assert_fail ("Initializer->isDelegatingInitializer()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 4951, __PRETTY_FUNCTION__)); | ||||
4952 | Constructor->setNumCtorInitializers(1); | ||||
4953 | CXXCtorInitializer **initializer = | ||||
4954 | new (Context) CXXCtorInitializer*[1]; | ||||
4955 | memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); | ||||
4956 | Constructor->setCtorInitializers(initializer); | ||||
4957 | |||||
4958 | if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { | ||||
4959 | MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); | ||||
4960 | DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); | ||||
4961 | } | ||||
4962 | |||||
4963 | DelegatingCtorDecls.push_back(Constructor); | ||||
4964 | |||||
4965 | DiagnoseUninitializedFields(*this, Constructor); | ||||
4966 | |||||
4967 | return false; | ||||
4968 | } | ||||
4969 | |||||
4970 | bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, | ||||
4971 | ArrayRef<CXXCtorInitializer *> Initializers) { | ||||
4972 | if (Constructor->isDependentContext()) { | ||||
4973 | // Just store the initializers as written, they will be checked during | ||||
4974 | // instantiation. | ||||
4975 | if (!Initializers.empty()) { | ||||
4976 | Constructor->setNumCtorInitializers(Initializers.size()); | ||||
4977 | CXXCtorInitializer **baseOrMemberInitializers = | ||||
4978 | new (Context) CXXCtorInitializer*[Initializers.size()]; | ||||
4979 | memcpy(baseOrMemberInitializers, Initializers.data(), | ||||
4980 | Initializers.size() * sizeof(CXXCtorInitializer*)); | ||||
4981 | Constructor->setCtorInitializers(baseOrMemberInitializers); | ||||
4982 | } | ||||
4983 | |||||
4984 | // Let template instantiation know whether we had errors. | ||||
4985 | if (AnyErrors) | ||||
4986 | Constructor->setInvalidDecl(); | ||||
4987 | |||||
4988 | return false; | ||||
4989 | } | ||||
4990 | |||||
4991 | BaseAndFieldInfo Info(*this, Constructor, AnyErrors); | ||||
4992 | |||||
4993 | // We need to build the initializer AST according to order of construction | ||||
4994 | // and not what user specified in the Initializers list. | ||||
4995 | CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); | ||||
4996 | if (!ClassDecl) | ||||
4997 | return true; | ||||
4998 | |||||
4999 | bool HadError = false; | ||||
5000 | |||||
5001 | for (unsigned i = 0; i < Initializers.size(); i++) { | ||||
5002 | CXXCtorInitializer *Member = Initializers[i]; | ||||
5003 | |||||
5004 | if (Member->isBaseInitializer()) | ||||
5005 | Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; | ||||
5006 | else { | ||||
5007 | Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; | ||||
5008 | |||||
5009 | if (IndirectFieldDecl *F = Member->getIndirectMember()) { | ||||
5010 | for (auto *C : F->chain()) { | ||||
5011 | FieldDecl *FD = dyn_cast<FieldDecl>(C); | ||||
5012 | if (FD && FD->getParent()->isUnion()) | ||||
5013 | Info.ActiveUnionMember.insert(std::make_pair( | ||||
5014 | FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); | ||||
5015 | } | ||||
5016 | } else if (FieldDecl *FD = Member->getMember()) { | ||||
5017 | if (FD->getParent()->isUnion()) | ||||
5018 | Info.ActiveUnionMember.insert(std::make_pair( | ||||
5019 | FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); | ||||
5020 | } | ||||
5021 | } | ||||
5022 | } | ||||
5023 | |||||
5024 | // Keep track of the direct virtual bases. | ||||
5025 | llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; | ||||
5026 | for (auto &I : ClassDecl->bases()) { | ||||
5027 | if (I.isVirtual()) | ||||
5028 | DirectVBases.insert(&I); | ||||
5029 | } | ||||
5030 | |||||
5031 | // Push virtual bases before others. | ||||
5032 | for (auto &VBase : ClassDecl->vbases()) { | ||||
5033 | if (CXXCtorInitializer *Value | ||||
5034 | = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { | ||||
5035 | // [class.base.init]p7, per DR257: | ||||
5036 | // A mem-initializer where the mem-initializer-id names a virtual base | ||||
5037 | // class is ignored during execution of a constructor of any class that | ||||
5038 | // is not the most derived class. | ||||
5039 | if (ClassDecl->isAbstract()) { | ||||
5040 | // FIXME: Provide a fixit to remove the base specifier. This requires | ||||
5041 | // tracking the location of the associated comma for a base specifier. | ||||
5042 | Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) | ||||
5043 | << VBase.getType() << ClassDecl; | ||||
5044 | DiagnoseAbstractType(ClassDecl); | ||||
5045 | } | ||||
5046 | |||||
5047 | Info.AllToInit.push_back(Value); | ||||
5048 | } else if (!AnyErrors && !ClassDecl->isAbstract()) { | ||||
5049 | // [class.base.init]p8, per DR257: | ||||
5050 | // If a given [...] base class is not named by a mem-initializer-id | ||||
5051 | // [...] and the entity is not a virtual base class of an abstract | ||||
5052 | // class, then [...] the entity is default-initialized. | ||||
5053 | bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); | ||||
5054 | CXXCtorInitializer *CXXBaseInit; | ||||
5055 | if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, | ||||
5056 | &VBase, IsInheritedVirtualBase, | ||||
5057 | CXXBaseInit)) { | ||||
5058 | HadError = true; | ||||
5059 | continue; | ||||
5060 | } | ||||
5061 | |||||
5062 | Info.AllToInit.push_back(CXXBaseInit); | ||||
5063 | } | ||||
5064 | } | ||||
5065 | |||||
5066 | // Non-virtual bases. | ||||
5067 | for (auto &Base : ClassDecl->bases()) { | ||||
5068 | // Virtuals are in the virtual base list and already constructed. | ||||
5069 | if (Base.isVirtual()) | ||||
5070 | continue; | ||||
5071 | |||||
5072 | if (CXXCtorInitializer *Value | ||||
5073 | = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { | ||||
5074 | Info.AllToInit.push_back(Value); | ||||
5075 | } else if (!AnyErrors) { | ||||
5076 | CXXCtorInitializer *CXXBaseInit; | ||||
5077 | if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, | ||||
5078 | &Base, /*IsInheritedVirtualBase=*/false, | ||||
5079 | CXXBaseInit)) { | ||||
5080 | HadError = true; | ||||
5081 | continue; | ||||
5082 | } | ||||
5083 | |||||
5084 | Info.AllToInit.push_back(CXXBaseInit); | ||||
5085 | } | ||||
5086 | } | ||||
5087 | |||||
5088 | // Fields. | ||||
5089 | for (auto *Mem : ClassDecl->decls()) { | ||||
5090 | if (auto *F = dyn_cast<FieldDecl>(Mem)) { | ||||
5091 | // C++ [class.bit]p2: | ||||
5092 | // A declaration for a bit-field that omits the identifier declares an | ||||
5093 | // unnamed bit-field. Unnamed bit-fields are not members and cannot be | ||||
5094 | // initialized. | ||||
5095 | if (F->isUnnamedBitfield()) | ||||
5096 | continue; | ||||
5097 | |||||
5098 | // If we're not generating the implicit copy/move constructor, then we'll | ||||
5099 | // handle anonymous struct/union fields based on their individual | ||||
5100 | // indirect fields. | ||||
5101 | if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) | ||||
5102 | continue; | ||||
5103 | |||||
5104 | if (CollectFieldInitializer(*this, Info, F)) | ||||
5105 | HadError = true; | ||||
5106 | continue; | ||||
5107 | } | ||||
5108 | |||||
5109 | // Beyond this point, we only consider default initialization. | ||||
5110 | if (Info.isImplicitCopyOrMove()) | ||||
5111 | continue; | ||||
5112 | |||||
5113 | if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { | ||||
5114 | if (F->getType()->isIncompleteArrayType()) { | ||||
5115 | assert(ClassDecl->hasFlexibleArrayMember() &&((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 5116, __PRETTY_FUNCTION__)) | ||||
5116 | "Incomplete array type is not valid")((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 5116, __PRETTY_FUNCTION__)); | ||||
5117 | continue; | ||||
5118 | } | ||||
5119 | |||||
5120 | // Initialize each field of an anonymous struct individually. | ||||
5121 | if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) | ||||
5122 | HadError = true; | ||||
5123 | |||||
5124 | continue; | ||||
5125 | } | ||||
5126 | } | ||||
5127 | |||||
5128 | unsigned NumInitializers = Info.AllToInit.size(); | ||||
5129 | if (NumInitializers > 0) { | ||||
5130 | Constructor->setNumCtorInitializers(NumInitializers); | ||||
5131 | CXXCtorInitializer **baseOrMemberInitializers = | ||||
5132 | new (Context) CXXCtorInitializer*[NumInitializers]; | ||||
5133 | memcpy(baseOrMemberInitializers, Info.AllToInit.data(), | ||||
5134 | NumInitializers * sizeof(CXXCtorInitializer*)); | ||||
5135 | Constructor->setCtorInitializers(baseOrMemberInitializers); | ||||
5136 | |||||
5137 | // Constructors implicitly reference the base and member | ||||
5138 | // destructors. | ||||
5139 | MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), | ||||
5140 | Constructor->getParent()); | ||||
5141 | } | ||||
5142 | |||||
5143 | return HadError; | ||||
5144 | } | ||||
5145 | |||||
5146 | static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { | ||||
5147 | if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { | ||||
5148 | const RecordDecl *RD = RT->getDecl(); | ||||
5149 | if (RD->isAnonymousStructOrUnion()) { | ||||
5150 | for (auto *Field : RD->fields()) | ||||
5151 | PopulateKeysForFields(Field, IdealInits); | ||||
5152 | return; | ||||
5153 | } | ||||
5154 | } | ||||
5155 | IdealInits.push_back(Field->getCanonicalDecl()); | ||||
5156 | } | ||||
5157 | |||||
5158 | static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { | ||||
5159 | return Context.getCanonicalType(BaseType).getTypePtr(); | ||||
5160 | } | ||||
5161 | |||||
5162 | static const void *GetKeyForMember(ASTContext &Context, | ||||
5163 | CXXCtorInitializer *Member) { | ||||
5164 | if (!Member->isAnyMemberInitializer()) | ||||
5165 | return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); | ||||
5166 | |||||
5167 | return Member->getAnyMember()->getCanonicalDecl(); | ||||
5168 | } | ||||
5169 | |||||
5170 | static void DiagnoseBaseOrMemInitializerOrder( | ||||
5171 | Sema &SemaRef, const CXXConstructorDecl *Constructor, | ||||
5172 | ArrayRef<CXXCtorInitializer *> Inits) { | ||||
5173 | if (Constructor->getDeclContext()->isDependentContext()) | ||||
5174 | return; | ||||
5175 | |||||
5176 | // Don't check initializers order unless the warning is enabled at the | ||||
5177 | // location of at least one initializer. | ||||
5178 | bool ShouldCheckOrder = false; | ||||
5179 | for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { | ||||
5180 | CXXCtorInitializer *Init = Inits[InitIndex]; | ||||
5181 | if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, | ||||
5182 | Init->getSourceLocation())) { | ||||
5183 | ShouldCheckOrder = true; | ||||
5184 | break; | ||||
5185 | } | ||||
5186 | } | ||||
5187 | if (!ShouldCheckOrder) | ||||
5188 | return; | ||||
5189 | |||||
5190 | // Build the list of bases and members in the order that they'll | ||||
5191 | // actually be initialized. The explicit initializers should be in | ||||
5192 | // this same order but may be missing things. | ||||
5193 | SmallVector<const void*, 32> IdealInitKeys; | ||||
5194 | |||||
5195 | const CXXRecordDecl *ClassDecl = Constructor->getParent(); | ||||
5196 | |||||
5197 | // 1. Virtual bases. | ||||
5198 | for (const auto &VBase : ClassDecl->vbases()) | ||||
5199 | IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); | ||||
5200 | |||||
5201 | // 2. Non-virtual bases. | ||||
5202 | for (const auto &Base : ClassDecl->bases()) { | ||||
5203 | if (Base.isVirtual()) | ||||
5204 | continue; | ||||
5205 | IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); | ||||
5206 | } | ||||
5207 | |||||
5208 | // 3. Direct fields. | ||||
5209 | for (auto *Field : ClassDecl->fields()) { | ||||
5210 | if (Field->isUnnamedBitfield()) | ||||
5211 | continue; | ||||
5212 | |||||
5213 | PopulateKeysForFields(Field, IdealInitKeys); | ||||
5214 | } | ||||
5215 | |||||
5216 | unsigned NumIdealInits = IdealInitKeys.size(); | ||||
5217 | unsigned IdealIndex = 0; | ||||
5218 | |||||
5219 | CXXCtorInitializer *PrevInit = nullptr; | ||||
5220 | for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { | ||||
5221 | CXXCtorInitializer *Init = Inits[InitIndex]; | ||||
5222 | const void *InitKey = GetKeyForMember(SemaRef.Context, Init); | ||||
5223 | |||||
5224 | // Scan forward to try to find this initializer in the idealized | ||||
5225 | // initializers list. | ||||
5226 | for (; IdealIndex != NumIdealInits; ++IdealIndex) | ||||
5227 | if (InitKey == IdealInitKeys[IdealIndex]) | ||||
5228 | break; | ||||
5229 | |||||
5230 | // If we didn't find this initializer, it must be because we | ||||
5231 | // scanned past it on a previous iteration. That can only | ||||
5232 | // happen if we're out of order; emit a warning. | ||||
5233 | if (IdealIndex == NumIdealInits && PrevInit) { | ||||
5234 | Sema::SemaDiagnosticBuilder D = | ||||
5235 | SemaRef.Diag(PrevInit->getSourceLocation(), | ||||
5236 | diag::warn_initializer_out_of_order); | ||||
5237 | |||||
5238 | if (PrevInit->isAnyMemberInitializer()) | ||||
5239 | D << 0 << PrevInit->getAnyMember()->getDeclName(); | ||||
5240 | else | ||||
5241 | D << 1 << PrevInit->getTypeSourceInfo()->getType(); | ||||
5242 | |||||
5243 | if (Init->isAnyMemberInitializer()) | ||||
5244 | D << 0 << Init->getAnyMember()->getDeclName(); | ||||
5245 | else | ||||
5246 | D << 1 << Init->getTypeSourceInfo()->getType(); | ||||
5247 | |||||
5248 | // Move back to the initializer's location in the ideal list. | ||||
5249 | for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) | ||||
5250 | if (InitKey == IdealInitKeys[IdealIndex]) | ||||
5251 | break; | ||||
5252 | |||||
5253 | assert(IdealIndex < NumIdealInits &&((IdealIndex < NumIdealInits && "initializer not found in initializer list" ) ? static_cast<void> (0) : __assert_fail ("IdealIndex < NumIdealInits && \"initializer not found in initializer list\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 5254, __PRETTY_FUNCTION__)) | ||||
5254 | "initializer not found in initializer list")((IdealIndex < NumIdealInits && "initializer not found in initializer list" ) ? static_cast<void> (0) : __assert_fail ("IdealIndex < NumIdealInits && \"initializer not found in initializer list\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 5254, __PRETTY_FUNCTION__)); | ||||
5255 | } | ||||
5256 | |||||
5257 | PrevInit = Init; | ||||
5258 | } | ||||
5259 | } | ||||
5260 | |||||
5261 | namespace { | ||||
5262 | bool CheckRedundantInit(Sema &S, | ||||
5263 | CXXCtorInitializer *Init, | ||||
5264 | CXXCtorInitializer *&PrevInit) { | ||||
5265 | if (!PrevInit) { | ||||
5266 | PrevInit = Init; | ||||
5267 | return false; | ||||
5268 | } | ||||
5269 | |||||
5270 | if (FieldDecl *Field = Init->getAnyMember()) | ||||
5271 | S.Diag(Init->getSourceLocation(), | ||||
5272 | diag::err_multiple_mem_initialization) | ||||
5273 | << Field->getDeclName() | ||||
5274 | << Init->getSourceRange(); | ||||
5275 | else { | ||||
5276 | const Type *BaseClass = Init->getBaseClass(); | ||||
5277 | assert(BaseClass && "neither field nor base")((BaseClass && "neither field nor base") ? static_cast <void> (0) : __assert_fail ("BaseClass && \"neither field nor base\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 5277, __PRETTY_FUNCTION__)); | ||||
5278 | S.Diag(Init->getSourceLocation(), | ||||
5279 | diag::err_multiple_base_initialization) | ||||
5280 | << QualType(BaseClass, 0) | ||||
5281 | << Init->getSourceRange(); | ||||
5282 | } | ||||
5283 | S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) | ||||
5284 | << 0 << PrevInit->getSourceRange(); | ||||
5285 | |||||
5286 | return true; | ||||
5287 | } | ||||
5288 | |||||
5289 | typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; | ||||
5290 | typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; | ||||
5291 | |||||
5292 | bool CheckRedundantUnionInit(Sema &S, | ||||
5293 | CXXCtorInitializer *Init, | ||||
5294 | RedundantUnionMap &Unions) { | ||||
5295 | FieldDecl *Field = Init->getAnyMember(); | ||||
5296 | RecordDecl *Parent = Field->getParent(); | ||||
5297 | NamedDecl *Child = Field; | ||||
5298 | |||||
5299 | while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { | ||||
5300 | if (Parent->isUnion()) { | ||||
5301 | UnionEntry &En = Unions[Parent]; | ||||
5302 | if (En.first && En.first != Child) { | ||||
5303 | S.Diag(Init->getSourceLocation(), | ||||
5304 | diag::err_multiple_mem_union_initialization) | ||||
5305 | << Field->getDeclName() | ||||
5306 | << Init->getSourceRange(); | ||||
5307 | S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) | ||||
5308 | << 0 << En.second->getSourceRange(); | ||||
5309 | return true; | ||||
5310 | } | ||||
5311 | if (!En.first) { | ||||
5312 | En.first = Child; | ||||
5313 | En.second = Init; | ||||
5314 | } | ||||
5315 | if (!Parent->isAnonymousStructOrUnion()) | ||||
5316 | return false; | ||||
5317 | } | ||||
5318 | |||||
5319 | Child = Parent; | ||||
5320 | Parent = cast<RecordDecl>(Parent->getDeclContext()); | ||||
5321 | } | ||||
5322 | |||||
5323 | return false; | ||||
5324 | } | ||||
5325 | } | ||||
5326 | |||||
5327 | /// ActOnMemInitializers - Handle the member initializers for a constructor. | ||||
5328 | void Sema::ActOnMemInitializers(Decl *ConstructorDecl, | ||||
5329 | SourceLocation ColonLoc, | ||||
5330 | ArrayRef<CXXCtorInitializer*> MemInits, | ||||
5331 | bool AnyErrors) { | ||||
5332 | if (!ConstructorDecl) | ||||
5333 | return; | ||||
5334 | |||||
5335 | AdjustDeclIfTemplate(ConstructorDecl); | ||||
5336 | |||||
5337 | CXXConstructorDecl *Constructor | ||||
5338 | = dyn_cast<CXXConstructorDecl>(ConstructorDecl); | ||||
5339 | |||||
5340 | if (!Constructor) { | ||||
5341 | Diag(ColonLoc, diag::err_only_constructors_take_base_inits); | ||||
5342 | return; | ||||
5343 | } | ||||
5344 | |||||
5345 | // Mapping for the duplicate initializers check. | ||||
5346 | // For member initializers, this is keyed with a FieldDecl*. | ||||
5347 | // For base initializers, this is keyed with a Type*. | ||||
5348 | llvm::DenseMap<const void *, CXXCtorInitializer *> Members; | ||||
5349 | |||||
5350 | // Mapping for the inconsistent anonymous-union initializers check. | ||||
5351 | RedundantUnionMap MemberUnions; | ||||
5352 | |||||
5353 | bool HadError = false; | ||||
5354 | for (unsigned i = 0; i < MemInits.size(); i++) { | ||||
5355 | CXXCtorInitializer *Init = MemInits[i]; | ||||
5356 | |||||
5357 | // Set the source order index. | ||||
5358 | Init->setSourceOrder(i); | ||||
5359 | |||||
5360 | if (Init->isAnyMemberInitializer()) { | ||||
5361 | const void *Key = GetKeyForMember(Context, Init); | ||||
5362 | if (CheckRedundantInit(*this, Init, Members[Key]) || | ||||
5363 | CheckRedundantUnionInit(*this, Init, MemberUnions)) | ||||
5364 | HadError = true; | ||||
5365 | } else if (Init->isBaseInitializer()) { | ||||
5366 | const void *Key = GetKeyForMember(Context, Init); | ||||
5367 | if (CheckRedundantInit(*this, Init, Members[Key])) | ||||
5368 | HadError = true; | ||||
5369 | } else { | ||||
5370 | assert(Init->isDelegatingInitializer())((Init->isDelegatingInitializer()) ? static_cast<void> (0) : __assert_fail ("Init->isDelegatingInitializer()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 5370, __PRETTY_FUNCTION__)); | ||||
5371 | // This must be the only initializer | ||||
5372 | if (MemInits.size() != 1) { | ||||
5373 | Diag(Init->getSourceLocation(), | ||||
5374 | diag::err_delegating_initializer_alone) | ||||
5375 | << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); | ||||
5376 | // We will treat this as being the only initializer. | ||||
5377 | } | ||||
5378 | SetDelegatingInitializer(Constructor, MemInits[i]); | ||||
5379 | // Return immediately as the initializer is set. | ||||
5380 | return; | ||||
5381 | } | ||||
5382 | } | ||||
5383 | |||||
5384 | if (HadError) | ||||
5385 | return; | ||||
5386 | |||||
5387 | DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); | ||||
5388 | |||||
5389 | SetCtorInitializers(Constructor, AnyErrors, MemInits); | ||||
5390 | |||||
5391 | DiagnoseUninitializedFields(*this, Constructor); | ||||
5392 | } | ||||
5393 | |||||
5394 | void | ||||
5395 | Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, | ||||
5396 | CXXRecordDecl *ClassDecl) { | ||||
5397 | // Ignore dependent contexts. Also ignore unions, since their members never | ||||
5398 | // have destructors implicitly called. | ||||
5399 | if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) | ||||
5400 | return; | ||||
5401 | |||||
5402 | // FIXME: all the access-control diagnostics are positioned on the | ||||
5403 | // field/base declaration. That's probably good; that said, the | ||||
5404 | // user might reasonably want to know why the destructor is being | ||||
5405 | // emitted, and we currently don't say. | ||||
5406 | |||||
5407 | // Non-static data members. | ||||
5408 | for (auto *Field : ClassDecl->fields()) { | ||||
5409 | if (Field->isInvalidDecl()) | ||||
5410 | continue; | ||||
5411 | |||||
5412 | // Don't destroy incomplete or zero-length arrays. | ||||
5413 | if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) | ||||
5414 | continue; | ||||
5415 | |||||
5416 | QualType FieldType = Context.getBaseElementType(Field->getType()); | ||||
5417 | |||||
5418 | const RecordType* RT = FieldType->getAs<RecordType>(); | ||||
5419 | if (!RT) | ||||
5420 | continue; | ||||
5421 | |||||
5422 | CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); | ||||
5423 | if (FieldClassDecl->isInvalidDecl()) | ||||
5424 | continue; | ||||
5425 | if (FieldClassDecl->hasIrrelevantDestructor()) | ||||
5426 | continue; | ||||
5427 | // The destructor for an implicit anonymous union member is never invoked. | ||||
5428 | if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) | ||||
5429 | continue; | ||||
5430 | |||||
5431 | CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); | ||||
5432 | assert(Dtor && "No dtor found for FieldClassDecl!")((Dtor && "No dtor found for FieldClassDecl!") ? static_cast <void> (0) : __assert_fail ("Dtor && \"No dtor found for FieldClassDecl!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 5432, __PRETTY_FUNCTION__)); | ||||
5433 | CheckDestructorAccess(Field->getLocation(), Dtor, | ||||
5434 | PDiag(diag::err_access_dtor_field) | ||||
5435 | << Field->getDeclName() | ||||
5436 | << FieldType); | ||||
5437 | |||||
5438 | MarkFunctionReferenced(Location, Dtor); | ||||
5439 | DiagnoseUseOfDecl(Dtor, Location); | ||||
5440 | } | ||||
5441 | |||||
5442 | // We only potentially invoke the destructors of potentially constructed | ||||
5443 | // subobjects. | ||||
5444 | bool VisitVirtualBases = !ClassDecl->isAbstract(); | ||||
5445 | |||||
5446 | llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; | ||||
5447 | |||||
5448 | // Bases. | ||||
5449 | for (const auto &Base : ClassDecl->bases()) { | ||||
5450 | // Bases are always records in a well-formed non-dependent class. | ||||
5451 | const RecordType *RT = Base.getType()->getAs<RecordType>(); | ||||
5452 | |||||
5453 | // Remember direct virtual bases. | ||||
5454 | if (Base.isVirtual()) { | ||||
5455 | if (!VisitVirtualBases) | ||||
5456 | continue; | ||||
5457 | DirectVirtualBases.insert(RT); | ||||
5458 | } | ||||
5459 | |||||
5460 | CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); | ||||
5461 | // If our base class is invalid, we probably can't get its dtor anyway. | ||||
5462 | if (BaseClassDecl->isInvalidDecl()) | ||||
5463 | continue; | ||||
5464 | if (BaseClassDecl->hasIrrelevantDestructor()) | ||||
5465 | continue; | ||||
5466 | |||||
5467 | CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); | ||||
5468 | assert(Dtor && "No dtor found for BaseClassDecl!")((Dtor && "No dtor found for BaseClassDecl!") ? static_cast <void> (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 5468, __PRETTY_FUNCTION__)); | ||||
5469 | |||||
5470 | // FIXME: caret should be on the start of the class name | ||||
5471 | CheckDestructorAccess(Base.getBeginLoc(), Dtor, | ||||
5472 | PDiag(diag::err_access_dtor_base) | ||||
5473 | << Base.getType() << Base.getSourceRange(), | ||||
5474 | Context.getTypeDeclType(ClassDecl)); | ||||
5475 | |||||
5476 | MarkFunctionReferenced(Location, Dtor); | ||||
5477 | DiagnoseUseOfDecl(Dtor, Location); | ||||
5478 | } | ||||
5479 | |||||
5480 | if (!VisitVirtualBases) | ||||
5481 | return; | ||||
5482 | |||||
5483 | // Virtual bases. | ||||
5484 | for (const auto &VBase : ClassDecl->vbases()) { | ||||
5485 | // Bases are always records in a well-formed non-dependent class. | ||||
5486 | const RecordType *RT = VBase.getType()->castAs<RecordType>(); | ||||
5487 | |||||
5488 | // Ignore direct virtual bases. | ||||
5489 | if (DirectVirtualBases.count(RT)) | ||||
5490 | continue; | ||||
5491 | |||||
5492 | CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); | ||||
5493 | // If our base class is invalid, we probably can't get its dtor anyway. | ||||
5494 | if (BaseClassDecl->isInvalidDecl()) | ||||
5495 | continue; | ||||
5496 | if (BaseClassDecl->hasIrrelevantDestructor()) | ||||
5497 | continue; | ||||
5498 | |||||
5499 | CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); | ||||
5500 | assert(Dtor && "No dtor found for BaseClassDecl!")((Dtor && "No dtor found for BaseClassDecl!") ? static_cast <void> (0) : __assert_fail ("Dtor && \"No dtor found for BaseClassDecl!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 5500, __PRETTY_FUNCTION__)); | ||||
5501 | if (CheckDestructorAccess( | ||||
5502 | ClassDecl->getLocation(), Dtor, | ||||
5503 | PDiag(diag::err_access_dtor_vbase) | ||||
5504 | << Context.getTypeDeclType(ClassDecl) << VBase.getType(), | ||||
5505 | Context.getTypeDeclType(ClassDecl)) == | ||||
5506 | AR_accessible) { | ||||
5507 | CheckDerivedToBaseConversion( | ||||
5508 | Context.getTypeDeclType(ClassDecl), VBase.getType(), | ||||
5509 | diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), | ||||
5510 | SourceRange(), DeclarationName(), nullptr); | ||||
5511 | } | ||||
5512 | |||||
5513 | MarkFunctionReferenced(Location, Dtor); | ||||
5514 | DiagnoseUseOfDecl(Dtor, Location); | ||||
5515 | } | ||||
5516 | } | ||||
5517 | |||||
5518 | void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { | ||||
5519 | if (!CDtorDecl) | ||||
5520 | return; | ||||
5521 | |||||
5522 | if (CXXConstructorDecl *Constructor | ||||
5523 | = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { | ||||
5524 | SetCtorInitializers(Constructor, /*AnyErrors=*/false); | ||||
5525 | DiagnoseUninitializedFields(*this, Constructor); | ||||
5526 | } | ||||
5527 | } | ||||
5528 | |||||
5529 | bool Sema::isAbstractType(SourceLocation Loc, QualType T) { | ||||
5530 | if (!getLangOpts().CPlusPlus) | ||||
5531 | return false; | ||||
5532 | |||||
5533 | const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); | ||||
5534 | if (!RD) | ||||
5535 | return false; | ||||
5536 | |||||
5537 | // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a | ||||
5538 | // class template specialization here, but doing so breaks a lot of code. | ||||
5539 | |||||
5540 | // We can't answer whether something is abstract until it has a | ||||
5541 | // definition. If it's currently being defined, we'll walk back | ||||
5542 | // over all the declarations when we have a full definition. | ||||
5543 | const CXXRecordDecl *Def = RD->getDefinition(); | ||||
5544 | if (!Def || Def->isBeingDefined()) | ||||
5545 | return false; | ||||
5546 | |||||
5547 | return RD->isAbstract(); | ||||
5548 | } | ||||
5549 | |||||
5550 | bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, | ||||
5551 | TypeDiagnoser &Diagnoser) { | ||||
5552 | if (!isAbstractType(Loc, T)) | ||||
5553 | return false; | ||||
5554 | |||||
5555 | T = Context.getBaseElementType(T); | ||||
5556 | Diagnoser.diagnose(*this, Loc, T); | ||||
5557 | DiagnoseAbstractType(T->getAsCXXRecordDecl()); | ||||
5558 | return true; | ||||
5559 | } | ||||
5560 | |||||
5561 | void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { | ||||
5562 | // Check if we've already emitted the list of pure virtual functions | ||||
5563 | // for this class. | ||||
5564 | if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) | ||||
5565 | return; | ||||
5566 | |||||
5567 | // If the diagnostic is suppressed, don't emit the notes. We're only | ||||
5568 | // going to emit them once, so try to attach them to a diagnostic we're | ||||
5569 | // actually going to show. | ||||
5570 | if (Diags.isLastDiagnosticIgnored()) | ||||
5571 | return; | ||||
5572 | |||||
5573 | CXXFinalOverriderMap FinalOverriders; | ||||
5574 | RD->getFinalOverriders(FinalOverriders); | ||||
5575 | |||||
5576 | // Keep a set of seen pure methods so we won't diagnose the same method | ||||
5577 | // more than once. | ||||
5578 | llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; | ||||
5579 | |||||
5580 | for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), | ||||
5581 | MEnd = FinalOverriders.end(); | ||||
5582 | M != MEnd; | ||||
5583 | ++M) { | ||||
5584 | for (OverridingMethods::iterator SO = M->second.begin(), | ||||
5585 | SOEnd = M->second.end(); | ||||
5586 | SO != SOEnd; ++SO) { | ||||
5587 | // C++ [class.abstract]p4: | ||||
5588 | // A class is abstract if it contains or inherits at least one | ||||
5589 | // pure virtual function for which the final overrider is pure | ||||
5590 | // virtual. | ||||
5591 | |||||
5592 | // | ||||
5593 | if (SO->second.size() != 1) | ||||
5594 | continue; | ||||
5595 | |||||
5596 | if (!SO->second.front().Method->isPure()) | ||||
5597 | continue; | ||||
5598 | |||||
5599 | if (!SeenPureMethods.insert(SO->second.front().Method).second) | ||||
5600 | continue; | ||||
5601 | |||||
5602 | Diag(SO->second.front().Method->getLocation(), | ||||
5603 | diag::note_pure_virtual_function) | ||||
5604 | << SO->second.front().Method->getDeclName() << RD->getDeclName(); | ||||
5605 | } | ||||
5606 | } | ||||
5607 | |||||
5608 | if (!PureVirtualClassDiagSet) | ||||
5609 | PureVirtualClassDiagSet.reset(new RecordDeclSetTy); | ||||
5610 | PureVirtualClassDiagSet->insert(RD); | ||||
5611 | } | ||||
5612 | |||||
5613 | namespace { | ||||
5614 | struct AbstractUsageInfo { | ||||
5615 | Sema &S; | ||||
5616 | CXXRecordDecl *Record; | ||||
5617 | CanQualType AbstractType; | ||||
5618 | bool Invalid; | ||||
5619 | |||||
5620 | AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) | ||||
5621 | : S(S), Record(Record), | ||||
5622 | AbstractType(S.Context.getCanonicalType( | ||||
5623 | S.Context.getTypeDeclType(Record))), | ||||
5624 | Invalid(false) {} | ||||
5625 | |||||
5626 | void DiagnoseAbstractType() { | ||||
5627 | if (Invalid) return; | ||||
5628 | S.DiagnoseAbstractType(Record); | ||||
5629 | Invalid = true; | ||||
5630 | } | ||||
5631 | |||||
5632 | void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); | ||||
5633 | }; | ||||
5634 | |||||
5635 | struct CheckAbstractUsage { | ||||
5636 | AbstractUsageInfo &Info; | ||||
5637 | const NamedDecl *Ctx; | ||||
5638 | |||||
5639 | CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) | ||||
5640 | : Info(Info), Ctx(Ctx) {} | ||||
5641 | |||||
5642 | void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { | ||||
5643 | switch (TL.getTypeLocClass()) { | ||||
5644 | #define ABSTRACT_TYPELOC(CLASS, PARENT) | ||||
5645 | #define TYPELOC(CLASS, PARENT) \ | ||||
5646 | case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; | ||||
5647 | #include "clang/AST/TypeLocNodes.def" | ||||
5648 | } | ||||
5649 | } | ||||
5650 | |||||
5651 | void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { | ||||
5652 | Visit(TL.getReturnLoc(), Sema::AbstractReturnType); | ||||
5653 | for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { | ||||
5654 | if (!TL.getParam(I)) | ||||
5655 | continue; | ||||
5656 | |||||
5657 | TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); | ||||
5658 | if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); | ||||
5659 | } | ||||
5660 | } | ||||
5661 | |||||
5662 | void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { | ||||
5663 | Visit(TL.getElementLoc(), Sema::AbstractArrayType); | ||||
5664 | } | ||||
5665 | |||||
5666 | void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { | ||||
5667 | // Visit the type parameters from a permissive context. | ||||
5668 | for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { | ||||
5669 | TemplateArgumentLoc TAL = TL.getArgLoc(I); | ||||
5670 | if (TAL.getArgument().getKind() == TemplateArgument::Type) | ||||
5671 | if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) | ||||
5672 | Visit(TSI->getTypeLoc(), Sema::AbstractNone); | ||||
5673 | // TODO: other template argument types? | ||||
5674 | } | ||||
5675 | } | ||||
5676 | |||||
5677 | // Visit pointee types from a permissive context. | ||||
5678 | #define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc (), Sema::AbstractNone); } \ | ||||
5679 | void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ | ||||
5680 | Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ | ||||
5681 | } | ||||
5682 | CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit (TL.getNextTypeLoc(), Sema::AbstractNone); } | ||||
5683 | CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); } | ||||
5684 | CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel ) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); } | ||||
5685 | CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel ) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); } | ||||
5686 | CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit (TL.getNextTypeLoc(), Sema::AbstractNone); } | ||||
5687 | |||||
5688 | /// Handle all the types we haven't given a more specific | ||||
5689 | /// implementation for above. | ||||
5690 | void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { | ||||
5691 | // Every other kind of type that we haven't called out already | ||||
5692 | // that has an inner type is either (1) sugar or (2) contains that | ||||
5693 | // inner type in some way as a subobject. | ||||
5694 | if (TypeLoc Next = TL.getNextTypeLoc()) | ||||
5695 | return Visit(Next, Sel); | ||||
5696 | |||||
5697 | // If there's no inner type and we're in a permissive context, | ||||
5698 | // don't diagnose. | ||||
5699 | if (Sel == Sema::AbstractNone) return; | ||||
5700 | |||||
5701 | // Check whether the type matches the abstract type. | ||||
5702 | QualType T = TL.getType(); | ||||
5703 | if (T->isArrayType()) { | ||||
5704 | Sel = Sema::AbstractArrayType; | ||||
5705 | T = Info.S.Context.getBaseElementType(T); | ||||
5706 | } | ||||
5707 | CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); | ||||
5708 | if (CT != Info.AbstractType) return; | ||||
5709 | |||||
5710 | // It matched; do some magic. | ||||
5711 | if (Sel == Sema::AbstractArrayType) { | ||||
5712 | Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) | ||||
5713 | << T << TL.getSourceRange(); | ||||
5714 | } else { | ||||
5715 | Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) | ||||
5716 | << Sel << T << TL.getSourceRange(); | ||||
5717 | } | ||||
5718 | Info.DiagnoseAbstractType(); | ||||
5719 | } | ||||
5720 | }; | ||||
5721 | |||||
5722 | void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, | ||||
5723 | Sema::AbstractDiagSelID Sel) { | ||||
5724 | CheckAbstractUsage(*this, D).Visit(TL, Sel); | ||||
5725 | } | ||||
5726 | |||||
5727 | } | ||||
5728 | |||||
5729 | /// Check for invalid uses of an abstract type in a method declaration. | ||||
5730 | static void CheckAbstractClassUsage(AbstractUsageInfo &Info, | ||||
5731 | CXXMethodDecl *MD) { | ||||
5732 | // No need to do the check on definitions, which require that | ||||
5733 | // the return/param types be complete. | ||||
5734 | if (MD->doesThisDeclarationHaveABody()) | ||||
5735 | return; | ||||
5736 | |||||
5737 | // For safety's sake, just ignore it if we don't have type source | ||||
5738 | // information. This should never happen for non-implicit methods, | ||||
5739 | // but... | ||||
5740 | if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) | ||||
5741 | Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); | ||||
5742 | } | ||||
5743 | |||||
5744 | /// Check for invalid uses of an abstract type within a class definition. | ||||
5745 | static void CheckAbstractClassUsage(AbstractUsageInfo &Info, | ||||
5746 | CXXRecordDecl *RD) { | ||||
5747 | for (auto *D : RD->decls()) { | ||||
5748 | if (D->isImplicit()) continue; | ||||
5749 | |||||
5750 | // Methods and method templates. | ||||
5751 | if (isa<CXXMethodDecl>(D)) { | ||||
5752 | CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); | ||||
5753 | } else if (isa<FunctionTemplateDecl>(D)) { | ||||
5754 | FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); | ||||
5755 | CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); | ||||
5756 | |||||
5757 | // Fields and static variables. | ||||
5758 | } else if (isa<FieldDecl>(D)) { | ||||
5759 | FieldDecl *FD = cast<FieldDecl>(D); | ||||
5760 | if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) | ||||
5761 | Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); | ||||
5762 | } else if (isa<VarDecl>(D)) { | ||||
5763 | VarDecl *VD = cast<VarDecl>(D); | ||||
5764 | if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) | ||||
5765 | Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); | ||||
5766 | |||||
5767 | // Nested classes and class templates. | ||||
5768 | } else if (isa<CXXRecordDecl>(D)) { | ||||
5769 | CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); | ||||
5770 | } else if (isa<ClassTemplateDecl>(D)) { | ||||
5771 | CheckAbstractClassUsage(Info, | ||||
5772 | cast<ClassTemplateDecl>(D)->getTemplatedDecl()); | ||||
5773 | } | ||||
5774 | } | ||||
5775 | } | ||||
5776 | |||||
5777 | static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { | ||||
5778 | Attr *ClassAttr = getDLLAttr(Class); | ||||
5779 | if (!ClassAttr) | ||||
5780 | return; | ||||
5781 | |||||
5782 | assert(ClassAttr->getKind() == attr::DLLExport)((ClassAttr->getKind() == attr::DLLExport) ? static_cast< void> (0) : __assert_fail ("ClassAttr->getKind() == attr::DLLExport" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 5782, __PRETTY_FUNCTION__)); | ||||
5783 | |||||
5784 | TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); | ||||
5785 | |||||
5786 | if (TSK == TSK_ExplicitInstantiationDeclaration) | ||||
5787 | // Don't go any further if this is just an explicit instantiation | ||||
5788 | // declaration. | ||||
5789 | return; | ||||
5790 | |||||
5791 | if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) | ||||
5792 | S.MarkVTableUsed(Class->getLocation(), Class, true); | ||||
5793 | |||||
5794 | for (Decl *Member : Class->decls()) { | ||||
5795 | // Defined static variables that are members of an exported base | ||||
5796 | // class must be marked export too. | ||||
5797 | auto *VD = dyn_cast<VarDecl>(Member); | ||||
5798 | if (VD && Member->getAttr<DLLExportAttr>() && | ||||
5799 | VD->getStorageClass() == SC_Static && | ||||
5800 | TSK == TSK_ImplicitInstantiation) | ||||
5801 | S.MarkVariableReferenced(VD->getLocation(), VD); | ||||
5802 | |||||
5803 | auto *MD = dyn_cast<CXXMethodDecl>(Member); | ||||
5804 | if (!MD) | ||||
5805 | continue; | ||||
5806 | |||||
5807 | if (Member->getAttr<DLLExportAttr>()) { | ||||
5808 | if (MD->isUserProvided()) { | ||||
5809 | // Instantiate non-default class member functions ... | ||||
5810 | |||||
5811 | // .. except for certain kinds of template specializations. | ||||
5812 | if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) | ||||
5813 | continue; | ||||
5814 | |||||
5815 | S.MarkFunctionReferenced(Class->getLocation(), MD); | ||||
5816 | |||||
5817 | // The function will be passed to the consumer when its definition is | ||||
5818 | // encountered. | ||||
5819 | } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || | ||||
5820 | MD->isCopyAssignmentOperator() || | ||||
5821 | MD->isMoveAssignmentOperator()) { | ||||
5822 | // Synthesize and instantiate non-trivial implicit methods, explicitly | ||||
5823 | // defaulted methods, and the copy and move assignment operators. The | ||||
5824 | // latter are exported even if they are trivial, because the address of | ||||
5825 | // an operator can be taken and should compare equal across libraries. | ||||
5826 | DiagnosticErrorTrap Trap(S.Diags); | ||||
5827 | S.MarkFunctionReferenced(Class->getLocation(), MD); | ||||
5828 | if (Trap.hasErrorOccurred()) { | ||||
5829 | S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) | ||||
5830 | << Class << !S.getLangOpts().CPlusPlus11; | ||||
5831 | break; | ||||
5832 | } | ||||
5833 | |||||
5834 | // There is no later point when we will see the definition of this | ||||
5835 | // function, so pass it to the consumer now. | ||||
5836 | S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); | ||||
5837 | } | ||||
5838 | } | ||||
5839 | } | ||||
5840 | } | ||||
5841 | |||||
5842 | static void checkForMultipleExportedDefaultConstructors(Sema &S, | ||||
5843 | CXXRecordDecl *Class) { | ||||
5844 | // Only the MS ABI has default constructor closures, so we don't need to do | ||||
5845 | // this semantic checking anywhere else. | ||||
5846 | if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) | ||||
5847 | return; | ||||
5848 | |||||
5849 | CXXConstructorDecl *LastExportedDefaultCtor = nullptr; | ||||
5850 | for (Decl *Member : Class->decls()) { | ||||
5851 | // Look for exported default constructors. | ||||
5852 | auto *CD = dyn_cast<CXXConstructorDecl>(Member); | ||||
5853 | if (!CD || !CD->isDefaultConstructor()) | ||||
5854 | continue; | ||||
5855 | auto *Attr = CD->getAttr<DLLExportAttr>(); | ||||
5856 | if (!Attr) | ||||
5857 | continue; | ||||
5858 | |||||
5859 | // If the class is non-dependent, mark the default arguments as ODR-used so | ||||
5860 | // that we can properly codegen the constructor closure. | ||||
5861 | if (!Class->isDependentContext()) { | ||||
5862 | for (ParmVarDecl *PD : CD->parameters()) { | ||||
5863 | (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); | ||||
5864 | S.DiscardCleanupsInEvaluationContext(); | ||||
5865 | } | ||||
5866 | } | ||||
5867 | |||||
5868 | if (LastExportedDefaultCtor) { | ||||
5869 | S.Diag(LastExportedDefaultCtor->getLocation(), | ||||
5870 | diag::err_attribute_dll_ambiguous_default_ctor) | ||||
5871 | << Class; | ||||
5872 | S.Diag(CD->getLocation(), diag::note_entity_declared_at) | ||||
5873 | << CD->getDeclName(); | ||||
5874 | return; | ||||
5875 | } | ||||
5876 | LastExportedDefaultCtor = CD; | ||||
5877 | } | ||||
5878 | } | ||||
5879 | |||||
5880 | void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { | ||||
5881 | // Mark any compiler-generated routines with the implicit code_seg attribute. | ||||
5882 | for (auto *Method : Class->methods()) { | ||||
5883 | if (Method->isUserProvided()) | ||||
5884 | continue; | ||||
5885 | if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) | ||||
5886 | Method->addAttr(A); | ||||
5887 | } | ||||
5888 | } | ||||
5889 | |||||
5890 | /// Check class-level dllimport/dllexport attribute. | ||||
5891 | void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { | ||||
5892 | Attr *ClassAttr = getDLLAttr(Class); | ||||
5893 | |||||
5894 | // MSVC inherits DLL attributes to partial class template specializations. | ||||
5895 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { | ||||
5896 | if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { | ||||
5897 | if (Attr *TemplateAttr = | ||||
5898 | getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { | ||||
5899 | auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); | ||||
5900 | A->setInherited(true); | ||||
5901 | ClassAttr = A; | ||||
5902 | } | ||||
5903 | } | ||||
5904 | } | ||||
5905 | |||||
5906 | if (!ClassAttr) | ||||
5907 | return; | ||||
5908 | |||||
5909 | if (!Class->isExternallyVisible()) { | ||||
5910 | Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) | ||||
5911 | << Class << ClassAttr; | ||||
5912 | return; | ||||
5913 | } | ||||
5914 | |||||
5915 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && | ||||
5916 | !ClassAttr->isInherited()) { | ||||
5917 | // Diagnose dll attributes on members of class with dll attribute. | ||||
5918 | for (Decl *Member : Class->decls()) { | ||||
5919 | if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) | ||||
5920 | continue; | ||||
5921 | InheritableAttr *MemberAttr = getDLLAttr(Member); | ||||
5922 | if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) | ||||
5923 | continue; | ||||
5924 | |||||
5925 | Diag(MemberAttr->getLocation(), | ||||
5926 | diag::err_attribute_dll_member_of_dll_class) | ||||
5927 | << MemberAttr << ClassAttr; | ||||
5928 | Diag(ClassAttr->getLocation(), diag::note_previous_attribute); | ||||
5929 | Member->setInvalidDecl(); | ||||
5930 | } | ||||
5931 | } | ||||
5932 | |||||
5933 | if (Class->getDescribedClassTemplate()) | ||||
5934 | // Don't inherit dll attribute until the template is instantiated. | ||||
5935 | return; | ||||
5936 | |||||
5937 | // The class is either imported or exported. | ||||
5938 | const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; | ||||
5939 | |||||
5940 | // Check if this was a dllimport attribute propagated from a derived class to | ||||
5941 | // a base class template specialization. We don't apply these attributes to | ||||
5942 | // static data members. | ||||
5943 | const bool PropagatedImport = | ||||
5944 | !ClassExported && | ||||
5945 | cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); | ||||
5946 | |||||
5947 | TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); | ||||
5948 | |||||
5949 | // Ignore explicit dllexport on explicit class template instantiation | ||||
5950 | // declarations, except in MinGW mode. | ||||
5951 | if (ClassExported && !ClassAttr->isInherited() && | ||||
5952 | TSK == TSK_ExplicitInstantiationDeclaration && | ||||
5953 | !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { | ||||
5954 | Class->dropAttr<DLLExportAttr>(); | ||||
5955 | return; | ||||
5956 | } | ||||
5957 | |||||
5958 | // Force declaration of implicit members so they can inherit the attribute. | ||||
5959 | ForceDeclarationOfImplicitMembers(Class); | ||||
5960 | |||||
5961 | // FIXME: MSVC's docs say all bases must be exportable, but this doesn't | ||||
5962 | // seem to be true in practice? | ||||
5963 | |||||
5964 | for (Decl *Member : Class->decls()) { | ||||
5965 | VarDecl *VD = dyn_cast<VarDecl>(Member); | ||||
5966 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); | ||||
5967 | |||||
5968 | // Only methods and static fields inherit the attributes. | ||||
5969 | if (!VD && !MD) | ||||
5970 | continue; | ||||
5971 | |||||
5972 | if (MD) { | ||||
5973 | // Don't process deleted methods. | ||||
5974 | if (MD->isDeleted()) | ||||
5975 | continue; | ||||
5976 | |||||
5977 | if (MD->isInlined()) { | ||||
5978 | // MinGW does not import or export inline methods. But do it for | ||||
5979 | // template instantiations. | ||||
5980 | if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && | ||||
5981 | !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() && | ||||
5982 | TSK != TSK_ExplicitInstantiationDeclaration && | ||||
5983 | TSK != TSK_ExplicitInstantiationDefinition) | ||||
5984 | continue; | ||||
5985 | |||||
5986 | // MSVC versions before 2015 don't export the move assignment operators | ||||
5987 | // and move constructor, so don't attempt to import/export them if | ||||
5988 | // we have a definition. | ||||
5989 | auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); | ||||
5990 | if ((MD->isMoveAssignmentOperator() || | ||||
5991 | (Ctor && Ctor->isMoveConstructor())) && | ||||
5992 | !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) | ||||
5993 | continue; | ||||
5994 | |||||
5995 | // MSVC2015 doesn't export trivial defaulted x-tor but copy assign | ||||
5996 | // operator is exported anyway. | ||||
5997 | if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && | ||||
5998 | (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) | ||||
5999 | continue; | ||||
6000 | } | ||||
6001 | } | ||||
6002 | |||||
6003 | // Don't apply dllimport attributes to static data members of class template | ||||
6004 | // instantiations when the attribute is propagated from a derived class. | ||||
6005 | if (VD && PropagatedImport) | ||||
6006 | continue; | ||||
6007 | |||||
6008 | if (!cast<NamedDecl>(Member)->isExternallyVisible()) | ||||
6009 | continue; | ||||
6010 | |||||
6011 | if (!getDLLAttr(Member)) { | ||||
6012 | InheritableAttr *NewAttr = nullptr; | ||||
6013 | |||||
6014 | // Do not export/import inline function when -fno-dllexport-inlines is | ||||
6015 | // passed. But add attribute for later local static var check. | ||||
6016 | if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && | ||||
6017 | TSK != TSK_ExplicitInstantiationDeclaration && | ||||
6018 | TSK != TSK_ExplicitInstantiationDefinition) { | ||||
6019 | if (ClassExported) { | ||||
6020 | NewAttr = ::new (getASTContext()) | ||||
6021 | DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); | ||||
6022 | } else { | ||||
6023 | NewAttr = ::new (getASTContext()) | ||||
6024 | DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); | ||||
6025 | } | ||||
6026 | } else { | ||||
6027 | NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); | ||||
6028 | } | ||||
6029 | |||||
6030 | NewAttr->setInherited(true); | ||||
6031 | Member->addAttr(NewAttr); | ||||
6032 | |||||
6033 | if (MD) { | ||||
6034 | // Propagate DLLAttr to friend re-declarations of MD that have already | ||||
6035 | // been constructed. | ||||
6036 | for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; | ||||
6037 | FD = FD->getPreviousDecl()) { | ||||
6038 | if (FD->getFriendObjectKind() == Decl::FOK_None) | ||||
6039 | continue; | ||||
6040 | assert(!getDLLAttr(FD) &&((!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr" ) ? static_cast<void> (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 6041, __PRETTY_FUNCTION__)) | ||||
6041 | "friend re-decl should not already have a DLLAttr")((!getDLLAttr(FD) && "friend re-decl should not already have a DLLAttr" ) ? static_cast<void> (0) : __assert_fail ("!getDLLAttr(FD) && \"friend re-decl should not already have a DLLAttr\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 6041, __PRETTY_FUNCTION__)); | ||||
6042 | NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); | ||||
6043 | NewAttr->setInherited(true); | ||||
6044 | FD->addAttr(NewAttr); | ||||
6045 | } | ||||
6046 | } | ||||
6047 | } | ||||
6048 | } | ||||
6049 | |||||
6050 | if (ClassExported) | ||||
6051 | DelayedDllExportClasses.push_back(Class); | ||||
6052 | } | ||||
6053 | |||||
6054 | /// Perform propagation of DLL attributes from a derived class to a | ||||
6055 | /// templated base class for MS compatibility. | ||||
6056 | void Sema::propagateDLLAttrToBaseClassTemplate( | ||||
6057 | CXXRecordDecl *Class, Attr *ClassAttr, | ||||
6058 | ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { | ||||
6059 | if (getDLLAttr( | ||||
6060 | BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { | ||||
6061 | // If the base class template has a DLL attribute, don't try to change it. | ||||
6062 | return; | ||||
6063 | } | ||||
6064 | |||||
6065 | auto TSK = BaseTemplateSpec->getSpecializationKind(); | ||||
6066 | if (!getDLLAttr(BaseTemplateSpec) && | ||||
6067 | (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || | ||||
6068 | TSK == TSK_ImplicitInstantiation)) { | ||||
6069 | // The template hasn't been instantiated yet (or it has, but only as an | ||||
6070 | // explicit instantiation declaration or implicit instantiation, which means | ||||
6071 | // we haven't codegenned any members yet), so propagate the attribute. | ||||
6072 | auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); | ||||
6073 | NewAttr->setInherited(true); | ||||
6074 | BaseTemplateSpec->addAttr(NewAttr); | ||||
6075 | |||||
6076 | // If this was an import, mark that we propagated it from a derived class to | ||||
6077 | // a base class template specialization. | ||||
6078 | if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) | ||||
6079 | ImportAttr->setPropagatedToBaseTemplate(); | ||||
6080 | |||||
6081 | // If the template is already instantiated, checkDLLAttributeRedeclaration() | ||||
6082 | // needs to be run again to work see the new attribute. Otherwise this will | ||||
6083 | // get run whenever the template is instantiated. | ||||
6084 | if (TSK != TSK_Undeclared) | ||||
6085 | checkClassLevelDLLAttribute(BaseTemplateSpec); | ||||
6086 | |||||
6087 | return; | ||||
6088 | } | ||||
6089 | |||||
6090 | if (getDLLAttr(BaseTemplateSpec)) { | ||||
6091 | // The template has already been specialized or instantiated with an | ||||
6092 | // attribute, explicitly or through propagation. We should not try to change | ||||
6093 | // it. | ||||
6094 | return; | ||||
6095 | } | ||||
6096 | |||||
6097 | // The template was previously instantiated or explicitly specialized without | ||||
6098 | // a dll attribute, It's too late for us to add an attribute, so warn that | ||||
6099 | // this is unsupported. | ||||
6100 | Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) | ||||
6101 | << BaseTemplateSpec->isExplicitSpecialization(); | ||||
6102 | Diag(ClassAttr->getLocation(), diag::note_attribute); | ||||
6103 | if (BaseTemplateSpec->isExplicitSpecialization()) { | ||||
6104 | Diag(BaseTemplateSpec->getLocation(), | ||||
6105 | diag::note_template_class_explicit_specialization_was_here) | ||||
6106 | << BaseTemplateSpec; | ||||
6107 | } else { | ||||
6108 | Diag(BaseTemplateSpec->getPointOfInstantiation(), | ||||
6109 | diag::note_template_class_instantiation_was_here) | ||||
6110 | << BaseTemplateSpec; | ||||
6111 | } | ||||
6112 | } | ||||
6113 | |||||
6114 | /// Determine the kind of defaulting that would be done for a given function. | ||||
6115 | /// | ||||
6116 | /// If the function is both a default constructor and a copy / move constructor | ||||
6117 | /// (due to having a default argument for the first parameter), this picks | ||||
6118 | /// CXXDefaultConstructor. | ||||
6119 | /// | ||||
6120 | /// FIXME: Check that case is properly handled by all callers. | ||||
6121 | Sema::DefaultedFunctionKind | ||||
6122 | Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { | ||||
6123 | if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { | ||||
6124 | if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { | ||||
6125 | if (Ctor->isDefaultConstructor()) | ||||
6126 | return Sema::CXXDefaultConstructor; | ||||
6127 | |||||
6128 | if (Ctor->isCopyConstructor()) | ||||
6129 | return Sema::CXXCopyConstructor; | ||||
6130 | |||||
6131 | if (Ctor->isMoveConstructor()) | ||||
6132 | return Sema::CXXMoveConstructor; | ||||
6133 | } | ||||
6134 | |||||
6135 | if (MD->isCopyAssignmentOperator()) | ||||
6136 | return Sema::CXXCopyAssignment; | ||||
6137 | |||||
6138 | if (MD->isMoveAssignmentOperator()) | ||||
6139 | return Sema::CXXMoveAssignment; | ||||
6140 | |||||
6141 | if (isa<CXXDestructorDecl>(FD)) | ||||
6142 | return Sema::CXXDestructor; | ||||
6143 | } | ||||
6144 | |||||
6145 | switch (FD->getDeclName().getCXXOverloadedOperator()) { | ||||
6146 | case OO_EqualEqual: | ||||
6147 | return DefaultedComparisonKind::Equal; | ||||
6148 | |||||
6149 | case OO_ExclaimEqual: | ||||
6150 | return DefaultedComparisonKind::NotEqual; | ||||
6151 | |||||
6152 | case OO_Spaceship: | ||||
6153 | // No point allowing this if <=> doesn't exist in the current language mode. | ||||
6154 | if (!getLangOpts().CPlusPlus2a) | ||||
6155 | break; | ||||
6156 | return DefaultedComparisonKind::ThreeWay; | ||||
6157 | |||||
6158 | case OO_Less: | ||||
6159 | case OO_LessEqual: | ||||
6160 | case OO_Greater: | ||||
6161 | case OO_GreaterEqual: | ||||
6162 | // No point allowing this if <=> doesn't exist in the current language mode. | ||||
6163 | if (!getLangOpts().CPlusPlus2a) | ||||
6164 | break; | ||||
6165 | return DefaultedComparisonKind::Relational; | ||||
6166 | |||||
6167 | default: | ||||
6168 | break; | ||||
6169 | } | ||||
6170 | |||||
6171 | // Not defaultable. | ||||
6172 | return DefaultedFunctionKind(); | ||||
6173 | } | ||||
6174 | |||||
6175 | static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, | ||||
6176 | SourceLocation DefaultLoc) { | ||||
6177 | switch (S.getSpecialMember(MD)) { | ||||
6178 | case Sema::CXXDefaultConstructor: | ||||
6179 | S.DefineImplicitDefaultConstructor(DefaultLoc, | ||||
6180 | cast<CXXConstructorDecl>(MD)); | ||||
6181 | break; | ||||
6182 | case Sema::CXXCopyConstructor: | ||||
6183 | S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); | ||||
6184 | break; | ||||
6185 | case Sema::CXXCopyAssignment: | ||||
6186 | S.DefineImplicitCopyAssignment(DefaultLoc, MD); | ||||
6187 | break; | ||||
6188 | case Sema::CXXDestructor: | ||||
6189 | S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); | ||||
6190 | break; | ||||
6191 | case Sema::CXXMoveConstructor: | ||||
6192 | S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); | ||||
6193 | break; | ||||
6194 | case Sema::CXXMoveAssignment: | ||||
6195 | S.DefineImplicitMoveAssignment(DefaultLoc, MD); | ||||
6196 | break; | ||||
6197 | case Sema::CXXInvalid: | ||||
6198 | llvm_unreachable("Invalid special member.")::llvm::llvm_unreachable_internal("Invalid special member.", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 6198); | ||||
6199 | } | ||||
6200 | } | ||||
6201 | |||||
6202 | /// Determine whether a type is permitted to be passed or returned in | ||||
6203 | /// registers, per C++ [class.temporary]p3. | ||||
6204 | static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, | ||||
6205 | TargetInfo::CallingConvKind CCK) { | ||||
6206 | if (D->isDependentType() || D->isInvalidDecl()) | ||||
6207 | return false; | ||||
6208 | |||||
6209 | // Clang <= 4 used the pre-C++11 rule, which ignores move operations. | ||||
6210 | // The PS4 platform ABI follows the behavior of Clang 3.2. | ||||
6211 | if (CCK == TargetInfo::CCK_ClangABI4OrPS4) | ||||
6212 | return !D->hasNonTrivialDestructorForCall() && | ||||
6213 | !D->hasNonTrivialCopyConstructorForCall(); | ||||
6214 | |||||
6215 | if (CCK == TargetInfo::CCK_MicrosoftWin64) { | ||||
6216 | bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; | ||||
6217 | bool DtorIsTrivialForCall = false; | ||||
6218 | |||||
6219 | // If a class has at least one non-deleted, trivial copy constructor, it | ||||
6220 | // is passed according to the C ABI. Otherwise, it is passed indirectly. | ||||
6221 | // | ||||
6222 | // Note: This permits classes with non-trivial copy or move ctors to be | ||||
6223 | // passed in registers, so long as they *also* have a trivial copy ctor, | ||||
6224 | // which is non-conforming. | ||||
6225 | if (D->needsImplicitCopyConstructor()) { | ||||
6226 | if (!D->defaultedCopyConstructorIsDeleted()) { | ||||
6227 | if (D->hasTrivialCopyConstructor()) | ||||
6228 | CopyCtorIsTrivial = true; | ||||
6229 | if (D->hasTrivialCopyConstructorForCall()) | ||||
6230 | CopyCtorIsTrivialForCall = true; | ||||
6231 | } | ||||
6232 | } else { | ||||
6233 | for (const CXXConstructorDecl *CD : D->ctors()) { | ||||
6234 | if (CD->isCopyConstructor() && !CD->isDeleted()) { | ||||
6235 | if (CD->isTrivial()) | ||||
6236 | CopyCtorIsTrivial = true; | ||||
6237 | if (CD->isTrivialForCall()) | ||||
6238 | CopyCtorIsTrivialForCall = true; | ||||
6239 | } | ||||
6240 | } | ||||
6241 | } | ||||
6242 | |||||
6243 | if (D->needsImplicitDestructor()) { | ||||
6244 | if (!D->defaultedDestructorIsDeleted() && | ||||
6245 | D->hasTrivialDestructorForCall()) | ||||
6246 | DtorIsTrivialForCall = true; | ||||
6247 | } else if (const auto *DD = D->getDestructor()) { | ||||
6248 | if (!DD->isDeleted() && DD->isTrivialForCall()) | ||||
6249 | DtorIsTrivialForCall = true; | ||||
6250 | } | ||||
6251 | |||||
6252 | // If the copy ctor and dtor are both trivial-for-calls, pass direct. | ||||
6253 | if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) | ||||
6254 | return true; | ||||
6255 | |||||
6256 | // If a class has a destructor, we'd really like to pass it indirectly | ||||
6257 | // because it allows us to elide copies. Unfortunately, MSVC makes that | ||||
6258 | // impossible for small types, which it will pass in a single register or | ||||
6259 | // stack slot. Most objects with dtors are large-ish, so handle that early. | ||||
6260 | // We can't call out all large objects as being indirect because there are | ||||
6261 | // multiple x64 calling conventions and the C++ ABI code shouldn't dictate | ||||
6262 | // how we pass large POD types. | ||||
6263 | |||||
6264 | // Note: This permits small classes with nontrivial destructors to be | ||||
6265 | // passed in registers, which is non-conforming. | ||||
6266 | bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); | ||||
6267 | uint64_t TypeSize = isAArch64 ? 128 : 64; | ||||
6268 | |||||
6269 | if (CopyCtorIsTrivial && | ||||
6270 | S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) | ||||
6271 | return true; | ||||
6272 | return false; | ||||
6273 | } | ||||
6274 | |||||
6275 | // Per C++ [class.temporary]p3, the relevant condition is: | ||||
6276 | // each copy constructor, move constructor, and destructor of X is | ||||
6277 | // either trivial or deleted, and X has at least one non-deleted copy | ||||
6278 | // or move constructor | ||||
6279 | bool HasNonDeletedCopyOrMove = false; | ||||
6280 | |||||
6281 | if (D->needsImplicitCopyConstructor() && | ||||
6282 | !D->defaultedCopyConstructorIsDeleted()) { | ||||
6283 | if (!D->hasTrivialCopyConstructorForCall()) | ||||
6284 | return false; | ||||
6285 | HasNonDeletedCopyOrMove = true; | ||||
6286 | } | ||||
6287 | |||||
6288 | if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && | ||||
6289 | !D->defaultedMoveConstructorIsDeleted()) { | ||||
6290 | if (!D->hasTrivialMoveConstructorForCall()) | ||||
6291 | return false; | ||||
6292 | HasNonDeletedCopyOrMove = true; | ||||
6293 | } | ||||
6294 | |||||
6295 | if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && | ||||
6296 | !D->hasTrivialDestructorForCall()) | ||||
6297 | return false; | ||||
6298 | |||||
6299 | for (const CXXMethodDecl *MD : D->methods()) { | ||||
6300 | if (MD->isDeleted()) | ||||
6301 | continue; | ||||
6302 | |||||
6303 | auto *CD = dyn_cast<CXXConstructorDecl>(MD); | ||||
6304 | if (CD && CD->isCopyOrMoveConstructor()) | ||||
6305 | HasNonDeletedCopyOrMove = true; | ||||
6306 | else if (!isa<CXXDestructorDecl>(MD)) | ||||
6307 | continue; | ||||
6308 | |||||
6309 | if (!MD->isTrivialForCall()) | ||||
6310 | return false; | ||||
6311 | } | ||||
6312 | |||||
6313 | return HasNonDeletedCopyOrMove; | ||||
6314 | } | ||||
6315 | |||||
6316 | /// Perform semantic checks on a class definition that has been | ||||
6317 | /// completing, introducing implicitly-declared members, checking for | ||||
6318 | /// abstract types, etc. | ||||
6319 | /// | ||||
6320 | /// \param S The scope in which the class was parsed. Null if we didn't just | ||||
6321 | /// parse a class definition. | ||||
6322 | /// \param Record The completed class. | ||||
6323 | void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { | ||||
6324 | if (!Record) | ||||
6325 | return; | ||||
6326 | |||||
6327 | if (Record->isAbstract() && !Record->isInvalidDecl()) { | ||||
6328 | AbstractUsageInfo Info(*this, Record); | ||||
6329 | CheckAbstractClassUsage(Info, Record); | ||||
6330 | } | ||||
6331 | |||||
6332 | // If this is not an aggregate type and has no user-declared constructor, | ||||
6333 | // complain about any non-static data members of reference or const scalar | ||||
6334 | // type, since they will never get initializers. | ||||
6335 | if (!Record->isInvalidDecl() && !Record->isDependentType() && | ||||
6336 | !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && | ||||
6337 | !Record->isLambda()) { | ||||
6338 | bool Complained = false; | ||||
6339 | for (const auto *F : Record->fields()) { | ||||
6340 | if (F->hasInClassInitializer() || F->isUnnamedBitfield()) | ||||
6341 | continue; | ||||
6342 | |||||
6343 | if (F->getType()->isReferenceType() || | ||||
6344 | (F->getType().isConstQualified() && F->getType()->isScalarType())) { | ||||
6345 | if (!Complained) { | ||||
6346 | Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) | ||||
6347 | << Record->getTagKind() << Record; | ||||
6348 | Complained = true; | ||||
6349 | } | ||||
6350 | |||||
6351 | Diag(F->getLocation(), diag::note_refconst_member_not_initialized) | ||||
6352 | << F->getType()->isReferenceType() | ||||
6353 | << F->getDeclName(); | ||||
6354 | } | ||||
6355 | } | ||||
6356 | } | ||||
6357 | |||||
6358 | if (Record->getIdentifier()) { | ||||
6359 | // C++ [class.mem]p13: | ||||
6360 | // If T is the name of a class, then each of the following shall have a | ||||
6361 | // name different from T: | ||||
6362 | // - every member of every anonymous union that is a member of class T. | ||||
6363 | // | ||||
6364 | // C++ [class.mem]p14: | ||||
6365 | // In addition, if class T has a user-declared constructor (12.1), every | ||||
6366 | // non-static data member of class T shall have a name different from T. | ||||
6367 | DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); | ||||
6368 | for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; | ||||
6369 | ++I) { | ||||
6370 | NamedDecl *D = (*I)->getUnderlyingDecl(); | ||||
6371 | if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && | ||||
6372 | Record->hasUserDeclaredConstructor()) || | ||||
6373 | isa<IndirectFieldDecl>(D)) { | ||||
6374 | Diag((*I)->getLocation(), diag::err_member_name_of_class) | ||||
6375 | << D->getDeclName(); | ||||
6376 | break; | ||||
6377 | } | ||||
6378 | } | ||||
6379 | } | ||||
6380 | |||||
6381 | // Warn if the class has virtual methods but non-virtual public destructor. | ||||
6382 | if (Record->isPolymorphic() && !Record->isDependentType()) { | ||||
6383 | CXXDestructorDecl *dtor = Record->getDestructor(); | ||||
6384 | if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && | ||||
6385 | !Record->hasAttr<FinalAttr>()) | ||||
6386 | Diag(dtor ? dtor->getLocation() : Record->getLocation(), | ||||
6387 | diag::warn_non_virtual_dtor) << Context.getRecordType(Record); | ||||
6388 | } | ||||
6389 | |||||
6390 | if (Record->isAbstract()) { | ||||
6391 | if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { | ||||
6392 | Diag(Record->getLocation(), diag::warn_abstract_final_class) | ||||
6393 | << FA->isSpelledAsSealed(); | ||||
6394 | DiagnoseAbstractType(Record); | ||||
6395 | } | ||||
6396 | } | ||||
6397 | |||||
6398 | // Warn if the class has a final destructor but is not itself marked final. | ||||
6399 | if (!Record->hasAttr<FinalAttr>()) { | ||||
6400 | if (const CXXDestructorDecl *dtor = Record->getDestructor()) { | ||||
6401 | if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { | ||||
6402 | Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) | ||||
6403 | << FA->isSpelledAsSealed() | ||||
6404 | << FixItHint::CreateInsertion( | ||||
6405 | getLocForEndOfToken(Record->getLocation()), | ||||
6406 | (FA->isSpelledAsSealed() ? " sealed" : " final")); | ||||
6407 | Diag(Record->getLocation(), | ||||
6408 | diag::note_final_dtor_non_final_class_silence) | ||||
6409 | << Context.getRecordType(Record) << FA->isSpelledAsSealed(); | ||||
6410 | } | ||||
6411 | } | ||||
6412 | } | ||||
6413 | |||||
6414 | // See if trivial_abi has to be dropped. | ||||
6415 | if (Record->hasAttr<TrivialABIAttr>()) | ||||
6416 | checkIllFormedTrivialABIStruct(*Record); | ||||
6417 | |||||
6418 | // Set HasTrivialSpecialMemberForCall if the record has attribute | ||||
6419 | // "trivial_abi". | ||||
6420 | bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); | ||||
6421 | |||||
6422 | if (HasTrivialABI) | ||||
6423 | Record->setHasTrivialSpecialMemberForCall(); | ||||
6424 | |||||
6425 | // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). | ||||
6426 | // We check these last because they can depend on the properties of the | ||||
6427 | // primary comparison functions (==, <=>). | ||||
6428 | llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; | ||||
6429 | |||||
6430 | auto CheckForDefaultedFunction = [&](FunctionDecl *FD) { | ||||
6431 | if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) | ||||
6432 | return; | ||||
6433 | |||||
6434 | DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); | ||||
6435 | if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || | ||||
6436 | DFK.asComparison() == DefaultedComparisonKind::Relational) | ||||
6437 | DefaultedSecondaryComparisons.push_back(FD); | ||||
6438 | else | ||||
6439 | CheckExplicitlyDefaultedFunction(S, FD); | ||||
6440 | }; | ||||
6441 | |||||
6442 | auto CompleteMemberFunction = [&](CXXMethodDecl *M) { | ||||
6443 | // Check whether the explicitly-defaulted members are valid. | ||||
6444 | CheckForDefaultedFunction(M); | ||||
6445 | |||||
6446 | // Skip the rest of the checks for a member of a dependent class. | ||||
6447 | if (Record->isDependentType()) | ||||
6448 | return; | ||||
6449 | |||||
6450 | // For an explicitly defaulted or deleted special member, we defer | ||||
6451 | // determining triviality until the class is complete. That time is now! | ||||
6452 | CXXSpecialMember CSM = getSpecialMember(M); | ||||
6453 | if (!M->isImplicit() && !M->isUserProvided()) { | ||||
6454 | if (CSM != CXXInvalid) { | ||||
6455 | M->setTrivial(SpecialMemberIsTrivial(M, CSM)); | ||||
6456 | // Inform the class that we've finished declaring this member. | ||||
6457 | Record->finishedDefaultedOrDeletedMember(M); | ||||
6458 | M->setTrivialForCall( | ||||
6459 | HasTrivialABI || | ||||
6460 | SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); | ||||
6461 | Record->setTrivialForCallFlags(M); | ||||
6462 | } | ||||
6463 | } | ||||
6464 | |||||
6465 | // Set triviality for the purpose of calls if this is a user-provided | ||||
6466 | // copy/move constructor or destructor. | ||||
6467 | if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || | ||||
6468 | CSM == CXXDestructor) && M->isUserProvided()) { | ||||
6469 | M->setTrivialForCall(HasTrivialABI); | ||||
6470 | Record->setTrivialForCallFlags(M); | ||||
6471 | } | ||||
6472 | |||||
6473 | if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && | ||||
6474 | M->hasAttr<DLLExportAttr>()) { | ||||
6475 | if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && | ||||
6476 | M->isTrivial() && | ||||
6477 | (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || | ||||
6478 | CSM == CXXDestructor)) | ||||
6479 | M->dropAttr<DLLExportAttr>(); | ||||
6480 | |||||
6481 | if (M->hasAttr<DLLExportAttr>()) { | ||||
6482 | // Define after any fields with in-class initializers have been parsed. | ||||
6483 | DelayedDllExportMemberFunctions.push_back(M); | ||||
6484 | } | ||||
6485 | } | ||||
6486 | |||||
6487 | // Define defaulted constexpr virtual functions that override a base class | ||||
6488 | // function right away. | ||||
6489 | // FIXME: We can defer doing this until the vtable is marked as used. | ||||
6490 | if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) | ||||
6491 | DefineImplicitSpecialMember(*this, M, M->getLocation()); | ||||
6492 | }; | ||||
6493 | |||||
6494 | // Check the destructor before any other member function. We need to | ||||
6495 | // determine whether it's trivial in order to determine whether the claas | ||||
6496 | // type is a literal type, which is a prerequisite for determining whether | ||||
6497 | // other special member functions are valid and whether they're implicitly | ||||
6498 | // 'constexpr'. | ||||
6499 | if (CXXDestructorDecl *Dtor = Record->getDestructor()) | ||||
6500 | CompleteMemberFunction(Dtor); | ||||
6501 | |||||
6502 | bool HasMethodWithOverrideControl = false, | ||||
6503 | HasOverridingMethodWithoutOverrideControl = false; | ||||
6504 | for (auto *D : Record->decls()) { | ||||
6505 | if (auto *M = dyn_cast<CXXMethodDecl>(D)) { | ||||
6506 | // FIXME: We could do this check for dependent types with non-dependent | ||||
6507 | // bases. | ||||
6508 | if (!Record->isDependentType()) { | ||||
6509 | // See if a method overloads virtual methods in a base | ||||
6510 | // class without overriding any. | ||||
6511 | if (!M->isStatic()) | ||||
6512 | DiagnoseHiddenVirtualMethods(M); | ||||
6513 | if (M->hasAttr<OverrideAttr>()) | ||||
6514 | HasMethodWithOverrideControl = true; | ||||
6515 | else if (M->size_overridden_methods() > 0) | ||||
6516 | HasOverridingMethodWithoutOverrideControl = true; | ||||
6517 | } | ||||
6518 | |||||
6519 | if (!isa<CXXDestructorDecl>(M)) | ||||
6520 | CompleteMemberFunction(M); | ||||
6521 | } else if (auto *F = dyn_cast<FriendDecl>(D)) { | ||||
6522 | CheckForDefaultedFunction( | ||||
6523 | dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); | ||||
6524 | } | ||||
6525 | } | ||||
6526 | |||||
6527 | if (HasMethodWithOverrideControl && | ||||
6528 | HasOverridingMethodWithoutOverrideControl) { | ||||
6529 | // At least one method has the 'override' control declared. | ||||
6530 | // Diagnose all other overridden methods which do not have 'override' | ||||
6531 | // specified on them. | ||||
6532 | for (auto *M : Record->methods()) | ||||
6533 | DiagnoseAbsenceOfOverrideControl(M); | ||||
6534 | } | ||||
6535 | |||||
6536 | // Check the defaulted secondary comparisons after any other member functions. | ||||
6537 | for (FunctionDecl *FD : DefaultedSecondaryComparisons) | ||||
6538 | CheckExplicitlyDefaultedFunction(S, FD); | ||||
6539 | |||||
6540 | // ms_struct is a request to use the same ABI rules as MSVC. Check | ||||
6541 | // whether this class uses any C++ features that are implemented | ||||
6542 | // completely differently in MSVC, and if so, emit a diagnostic. | ||||
6543 | // That diagnostic defaults to an error, but we allow projects to | ||||
6544 | // map it down to a warning (or ignore it). It's a fairly common | ||||
6545 | // practice among users of the ms_struct pragma to mass-annotate | ||||
6546 | // headers, sweeping up a bunch of types that the project doesn't | ||||
6547 | // really rely on MSVC-compatible layout for. We must therefore | ||||
6548 | // support "ms_struct except for C++ stuff" as a secondary ABI. | ||||
6549 | if (Record->isMsStruct(Context) && | ||||
6550 | (Record->isPolymorphic() || Record->getNumBases())) { | ||||
6551 | Diag(Record->getLocation(), diag::warn_cxx_ms_struct); | ||||
6552 | } | ||||
6553 | |||||
6554 | checkClassLevelDLLAttribute(Record); | ||||
6555 | checkClassLevelCodeSegAttribute(Record); | ||||
6556 | |||||
6557 | bool ClangABICompat4 = | ||||
6558 | Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; | ||||
6559 | TargetInfo::CallingConvKind CCK = | ||||
6560 | Context.getTargetInfo().getCallingConvKind(ClangABICompat4); | ||||
6561 | bool CanPass = canPassInRegisters(*this, Record, CCK); | ||||
6562 | |||||
6563 | // Do not change ArgPassingRestrictions if it has already been set to | ||||
6564 | // APK_CanNeverPassInRegs. | ||||
6565 | if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) | ||||
6566 | Record->setArgPassingRestrictions(CanPass | ||||
6567 | ? RecordDecl::APK_CanPassInRegs | ||||
6568 | : RecordDecl::APK_CannotPassInRegs); | ||||
6569 | |||||
6570 | // If canPassInRegisters returns true despite the record having a non-trivial | ||||
6571 | // destructor, the record is destructed in the callee. This happens only when | ||||
6572 | // the record or one of its subobjects has a field annotated with trivial_abi | ||||
6573 | // or a field qualified with ObjC __strong/__weak. | ||||
6574 | if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) | ||||
6575 | Record->setParamDestroyedInCallee(true); | ||||
6576 | else if (Record->hasNonTrivialDestructor()) | ||||
6577 | Record->setParamDestroyedInCallee(CanPass); | ||||
6578 | |||||
6579 | if (getLangOpts().ForceEmitVTables) { | ||||
6580 | // If we want to emit all the vtables, we need to mark it as used. This | ||||
6581 | // is especially required for cases like vtable assumption loads. | ||||
6582 | MarkVTableUsed(Record->getInnerLocStart(), Record); | ||||
6583 | } | ||||
6584 | } | ||||
6585 | |||||
6586 | /// Look up the special member function that would be called by a special | ||||
6587 | /// member function for a subobject of class type. | ||||
6588 | /// | ||||
6589 | /// \param Class The class type of the subobject. | ||||
6590 | /// \param CSM The kind of special member function. | ||||
6591 | /// \param FieldQuals If the subobject is a field, its cv-qualifiers. | ||||
6592 | /// \param ConstRHS True if this is a copy operation with a const object | ||||
6593 | /// on its RHS, that is, if the argument to the outer special member | ||||
6594 | /// function is 'const' and this is not a field marked 'mutable'. | ||||
6595 | static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( | ||||
6596 | Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, | ||||
6597 | unsigned FieldQuals, bool ConstRHS) { | ||||
6598 | unsigned LHSQuals = 0; | ||||
6599 | if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) | ||||
6600 | LHSQuals = FieldQuals; | ||||
6601 | |||||
6602 | unsigned RHSQuals = FieldQuals; | ||||
6603 | if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) | ||||
6604 | RHSQuals = 0; | ||||
6605 | else if (ConstRHS) | ||||
6606 | RHSQuals |= Qualifiers::Const; | ||||
6607 | |||||
6608 | return S.LookupSpecialMember(Class, CSM, | ||||
6609 | RHSQuals & Qualifiers::Const, | ||||
6610 | RHSQuals & Qualifiers::Volatile, | ||||
6611 | false, | ||||
6612 | LHSQuals & Qualifiers::Const, | ||||
6613 | LHSQuals & Qualifiers::Volatile); | ||||
6614 | } | ||||
6615 | |||||
6616 | class Sema::InheritedConstructorInfo { | ||||
6617 | Sema &S; | ||||
6618 | SourceLocation UseLoc; | ||||
6619 | |||||
6620 | /// A mapping from the base classes through which the constructor was | ||||
6621 | /// inherited to the using shadow declaration in that base class (or a null | ||||
6622 | /// pointer if the constructor was declared in that base class). | ||||
6623 | llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> | ||||
6624 | InheritedFromBases; | ||||
6625 | |||||
6626 | public: | ||||
6627 | InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, | ||||
6628 | ConstructorUsingShadowDecl *Shadow) | ||||
6629 | : S(S), UseLoc(UseLoc) { | ||||
6630 | bool DiagnosedMultipleConstructedBases = false; | ||||
6631 | CXXRecordDecl *ConstructedBase = nullptr; | ||||
6632 | UsingDecl *ConstructedBaseUsing = nullptr; | ||||
6633 | |||||
6634 | // Find the set of such base class subobjects and check that there's a | ||||
6635 | // unique constructed subobject. | ||||
6636 | for (auto *D : Shadow->redecls()) { | ||||
6637 | auto *DShadow = cast<ConstructorUsingShadowDecl>(D); | ||||
6638 | auto *DNominatedBase = DShadow->getNominatedBaseClass(); | ||||
6639 | auto *DConstructedBase = DShadow->getConstructedBaseClass(); | ||||
6640 | |||||
6641 | InheritedFromBases.insert( | ||||
6642 | std::make_pair(DNominatedBase->getCanonicalDecl(), | ||||
6643 | DShadow->getNominatedBaseClassShadowDecl())); | ||||
6644 | if (DShadow->constructsVirtualBase()) | ||||
6645 | InheritedFromBases.insert( | ||||
6646 | std::make_pair(DConstructedBase->getCanonicalDecl(), | ||||
6647 | DShadow->getConstructedBaseClassShadowDecl())); | ||||
6648 | else | ||||
6649 | assert(DNominatedBase == DConstructedBase)((DNominatedBase == DConstructedBase) ? static_cast<void> (0) : __assert_fail ("DNominatedBase == DConstructedBase", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 6649, __PRETTY_FUNCTION__)); | ||||
6650 | |||||
6651 | // [class.inhctor.init]p2: | ||||
6652 | // If the constructor was inherited from multiple base class subobjects | ||||
6653 | // of type B, the program is ill-formed. | ||||
6654 | if (!ConstructedBase) { | ||||
6655 | ConstructedBase = DConstructedBase; | ||||
6656 | ConstructedBaseUsing = D->getUsingDecl(); | ||||
6657 | } else if (ConstructedBase != DConstructedBase && | ||||
6658 | !Shadow->isInvalidDecl()) { | ||||
6659 | if (!DiagnosedMultipleConstructedBases) { | ||||
6660 | S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) | ||||
6661 | << Shadow->getTargetDecl(); | ||||
6662 | S.Diag(ConstructedBaseUsing->getLocation(), | ||||
6663 | diag::note_ambiguous_inherited_constructor_using) | ||||
6664 | << ConstructedBase; | ||||
6665 | DiagnosedMultipleConstructedBases = true; | ||||
6666 | } | ||||
6667 | S.Diag(D->getUsingDecl()->getLocation(), | ||||
6668 | diag::note_ambiguous_inherited_constructor_using) | ||||
6669 | << DConstructedBase; | ||||
6670 | } | ||||
6671 | } | ||||
6672 | |||||
6673 | if (DiagnosedMultipleConstructedBases) | ||||
6674 | Shadow->setInvalidDecl(); | ||||
6675 | } | ||||
6676 | |||||
6677 | /// Find the constructor to use for inherited construction of a base class, | ||||
6678 | /// and whether that base class constructor inherits the constructor from a | ||||
6679 | /// virtual base class (in which case it won't actually invoke it). | ||||
6680 | std::pair<CXXConstructorDecl *, bool> | ||||
6681 | findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { | ||||
6682 | auto It = InheritedFromBases.find(Base->getCanonicalDecl()); | ||||
6683 | if (It == InheritedFromBases.end()) | ||||
6684 | return std::make_pair(nullptr, false); | ||||
6685 | |||||
6686 | // This is an intermediary class. | ||||
6687 | if (It->second) | ||||
6688 | return std::make_pair( | ||||
6689 | S.findInheritingConstructor(UseLoc, Ctor, It->second), | ||||
6690 | It->second->constructsVirtualBase()); | ||||
6691 | |||||
6692 | // This is the base class from which the constructor was inherited. | ||||
6693 | return std::make_pair(Ctor, false); | ||||
6694 | } | ||||
6695 | }; | ||||
6696 | |||||
6697 | /// Is the special member function which would be selected to perform the | ||||
6698 | /// specified operation on the specified class type a constexpr constructor? | ||||
6699 | static bool | ||||
6700 | specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, | ||||
6701 | Sema::CXXSpecialMember CSM, unsigned Quals, | ||||
6702 | bool ConstRHS, | ||||
6703 | CXXConstructorDecl *InheritedCtor = nullptr, | ||||
6704 | Sema::InheritedConstructorInfo *Inherited = nullptr) { | ||||
6705 | // If we're inheriting a constructor, see if we need to call it for this base | ||||
6706 | // class. | ||||
6707 | if (InheritedCtor) { | ||||
6708 | assert(CSM == Sema::CXXDefaultConstructor)((CSM == Sema::CXXDefaultConstructor) ? static_cast<void> (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 6708, __PRETTY_FUNCTION__)); | ||||
6709 | auto BaseCtor = | ||||
6710 | Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; | ||||
6711 | if (BaseCtor) | ||||
6712 | return BaseCtor->isConstexpr(); | ||||
6713 | } | ||||
6714 | |||||
6715 | if (CSM == Sema::CXXDefaultConstructor) | ||||
6716 | return ClassDecl->hasConstexprDefaultConstructor(); | ||||
6717 | if (CSM == Sema::CXXDestructor) | ||||
6718 | return ClassDecl->hasConstexprDestructor(); | ||||
6719 | |||||
6720 | Sema::SpecialMemberOverloadResult SMOR = | ||||
6721 | lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); | ||||
6722 | if (!SMOR.getMethod()) | ||||
6723 | // A constructor we wouldn't select can't be "involved in initializing" | ||||
6724 | // anything. | ||||
6725 | return true; | ||||
6726 | return SMOR.getMethod()->isConstexpr(); | ||||
6727 | } | ||||
6728 | |||||
6729 | /// Determine whether the specified special member function would be constexpr | ||||
6730 | /// if it were implicitly defined. | ||||
6731 | static bool defaultedSpecialMemberIsConstexpr( | ||||
6732 | Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, | ||||
6733 | bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, | ||||
6734 | Sema::InheritedConstructorInfo *Inherited = nullptr) { | ||||
6735 | if (!S.getLangOpts().CPlusPlus11) | ||||
6736 | return false; | ||||
6737 | |||||
6738 | // C++11 [dcl.constexpr]p4: | ||||
6739 | // In the definition of a constexpr constructor [...] | ||||
6740 | bool Ctor = true; | ||||
6741 | switch (CSM) { | ||||
6742 | case Sema::CXXDefaultConstructor: | ||||
6743 | if (Inherited) | ||||
6744 | break; | ||||
6745 | // Since default constructor lookup is essentially trivial (and cannot | ||||
6746 | // involve, for instance, template instantiation), we compute whether a | ||||
6747 | // defaulted default constructor is constexpr directly within CXXRecordDecl. | ||||
6748 | // | ||||
6749 | // This is important for performance; we need to know whether the default | ||||
6750 | // constructor is constexpr to determine whether the type is a literal type. | ||||
6751 | return ClassDecl->defaultedDefaultConstructorIsConstexpr(); | ||||
6752 | |||||
6753 | case Sema::CXXCopyConstructor: | ||||
6754 | case Sema::CXXMoveConstructor: | ||||
6755 | // For copy or move constructors, we need to perform overload resolution. | ||||
6756 | break; | ||||
6757 | |||||
6758 | case Sema::CXXCopyAssignment: | ||||
6759 | case Sema::CXXMoveAssignment: | ||||
6760 | if (!S.getLangOpts().CPlusPlus14) | ||||
6761 | return false; | ||||
6762 | // In C++1y, we need to perform overload resolution. | ||||
6763 | Ctor = false; | ||||
6764 | break; | ||||
6765 | |||||
6766 | case Sema::CXXDestructor: | ||||
6767 | return ClassDecl->defaultedDestructorIsConstexpr(); | ||||
6768 | |||||
6769 | case Sema::CXXInvalid: | ||||
6770 | return false; | ||||
6771 | } | ||||
6772 | |||||
6773 | // -- if the class is a non-empty union, or for each non-empty anonymous | ||||
6774 | // union member of a non-union class, exactly one non-static data member | ||||
6775 | // shall be initialized; [DR1359] | ||||
6776 | // | ||||
6777 | // If we squint, this is guaranteed, since exactly one non-static data member | ||||
6778 | // will be initialized (if the constructor isn't deleted), we just don't know | ||||
6779 | // which one. | ||||
6780 | if (Ctor && ClassDecl->isUnion()) | ||||
6781 | return CSM == Sema::CXXDefaultConstructor | ||||
6782 | ? ClassDecl->hasInClassInitializer() || | ||||
6783 | !ClassDecl->hasVariantMembers() | ||||
6784 | : true; | ||||
6785 | |||||
6786 | // -- the class shall not have any virtual base classes; | ||||
6787 | if (Ctor && ClassDecl->getNumVBases()) | ||||
6788 | return false; | ||||
6789 | |||||
6790 | // C++1y [class.copy]p26: | ||||
6791 | // -- [the class] is a literal type, and | ||||
6792 | if (!Ctor && !ClassDecl->isLiteral()) | ||||
6793 | return false; | ||||
6794 | |||||
6795 | // -- every constructor involved in initializing [...] base class | ||||
6796 | // sub-objects shall be a constexpr constructor; | ||||
6797 | // -- the assignment operator selected to copy/move each direct base | ||||
6798 | // class is a constexpr function, and | ||||
6799 | for (const auto &B : ClassDecl->bases()) { | ||||
6800 | const RecordType *BaseType = B.getType()->getAs<RecordType>(); | ||||
6801 | if (!BaseType) continue; | ||||
6802 | |||||
6803 | CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); | ||||
6804 | if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, | ||||
6805 | InheritedCtor, Inherited)) | ||||
6806 | return false; | ||||
6807 | } | ||||
6808 | |||||
6809 | // -- every constructor involved in initializing non-static data members | ||||
6810 | // [...] shall be a constexpr constructor; | ||||
6811 | // -- every non-static data member and base class sub-object shall be | ||||
6812 | // initialized | ||||
6813 | // -- for each non-static data member of X that is of class type (or array | ||||
6814 | // thereof), the assignment operator selected to copy/move that member is | ||||
6815 | // a constexpr function | ||||
6816 | for (const auto *F : ClassDecl->fields()) { | ||||
6817 | if (F->isInvalidDecl()) | ||||
6818 | continue; | ||||
6819 | if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) | ||||
6820 | continue; | ||||
6821 | QualType BaseType = S.Context.getBaseElementType(F->getType()); | ||||
6822 | if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { | ||||
6823 | CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); | ||||
6824 | if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, | ||||
6825 | BaseType.getCVRQualifiers(), | ||||
6826 | ConstArg && !F->isMutable())) | ||||
6827 | return false; | ||||
6828 | } else if (CSM == Sema::CXXDefaultConstructor) { | ||||
6829 | return false; | ||||
6830 | } | ||||
6831 | } | ||||
6832 | |||||
6833 | // All OK, it's constexpr! | ||||
6834 | return true; | ||||
6835 | } | ||||
6836 | |||||
6837 | namespace { | ||||
6838 | /// RAII object to register a defaulted function as having its exception | ||||
6839 | /// specification computed. | ||||
6840 | struct ComputingExceptionSpec { | ||||
6841 | Sema &S; | ||||
6842 | |||||
6843 | ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) | ||||
6844 | : S(S) { | ||||
6845 | Sema::CodeSynthesisContext Ctx; | ||||
6846 | Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; | ||||
6847 | Ctx.PointOfInstantiation = Loc; | ||||
6848 | Ctx.Entity = FD; | ||||
6849 | S.pushCodeSynthesisContext(Ctx); | ||||
6850 | } | ||||
6851 | ~ComputingExceptionSpec() { | ||||
6852 | S.popCodeSynthesisContext(); | ||||
6853 | } | ||||
6854 | }; | ||||
6855 | } | ||||
6856 | |||||
6857 | static Sema::ImplicitExceptionSpecification | ||||
6858 | ComputeDefaultedSpecialMemberExceptionSpec( | ||||
6859 | Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, | ||||
6860 | Sema::InheritedConstructorInfo *ICI); | ||||
6861 | |||||
6862 | static Sema::ImplicitExceptionSpecification | ||||
6863 | ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, | ||||
6864 | FunctionDecl *FD, | ||||
6865 | Sema::DefaultedComparisonKind DCK); | ||||
6866 | |||||
6867 | static Sema::ImplicitExceptionSpecification | ||||
6868 | computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { | ||||
6869 | auto DFK = S.getDefaultedFunctionKind(FD); | ||||
6870 | if (DFK.isSpecialMember()) | ||||
6871 | return ComputeDefaultedSpecialMemberExceptionSpec( | ||||
6872 | S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); | ||||
6873 | if (DFK.isComparison()) | ||||
6874 | return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, | ||||
6875 | DFK.asComparison()); | ||||
6876 | |||||
6877 | auto *CD = cast<CXXConstructorDecl>(FD); | ||||
6878 | assert(CD->getInheritedConstructor() &&((CD->getInheritedConstructor() && "only defaulted functions and inherited constructors have implicit " "exception specs") ? static_cast<void> (0) : __assert_fail ("CD->getInheritedConstructor() && \"only defaulted functions and inherited constructors have implicit \" \"exception specs\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 6880, __PRETTY_FUNCTION__)) | ||||
6879 | "only defaulted functions and inherited constructors have implicit "((CD->getInheritedConstructor() && "only defaulted functions and inherited constructors have implicit " "exception specs") ? static_cast<void> (0) : __assert_fail ("CD->getInheritedConstructor() && \"only defaulted functions and inherited constructors have implicit \" \"exception specs\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 6880, __PRETTY_FUNCTION__)) | ||||
6880 | "exception specs")((CD->getInheritedConstructor() && "only defaulted functions and inherited constructors have implicit " "exception specs") ? static_cast<void> (0) : __assert_fail ("CD->getInheritedConstructor() && \"only defaulted functions and inherited constructors have implicit \" \"exception specs\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 6880, __PRETTY_FUNCTION__)); | ||||
6881 | Sema::InheritedConstructorInfo ICI( | ||||
6882 | S, Loc, CD->getInheritedConstructor().getShadowDecl()); | ||||
6883 | return ComputeDefaultedSpecialMemberExceptionSpec( | ||||
6884 | S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); | ||||
6885 | } | ||||
6886 | |||||
6887 | static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, | ||||
6888 | CXXMethodDecl *MD) { | ||||
6889 | FunctionProtoType::ExtProtoInfo EPI; | ||||
6890 | |||||
6891 | // Build an exception specification pointing back at this member. | ||||
6892 | EPI.ExceptionSpec.Type = EST_Unevaluated; | ||||
6893 | EPI.ExceptionSpec.SourceDecl = MD; | ||||
6894 | |||||
6895 | // Set the calling convention to the default for C++ instance methods. | ||||
6896 | EPI.ExtInfo = EPI.ExtInfo.withCallingConv( | ||||
6897 | S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, | ||||
6898 | /*IsCXXMethod=*/true)); | ||||
6899 | return EPI; | ||||
6900 | } | ||||
6901 | |||||
6902 | void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { | ||||
6903 | const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); | ||||
6904 | if (FPT->getExceptionSpecType() != EST_Unevaluated) | ||||
6905 | return; | ||||
6906 | |||||
6907 | // Evaluate the exception specification. | ||||
6908 | auto IES = computeImplicitExceptionSpec(*this, Loc, FD); | ||||
6909 | auto ESI = IES.getExceptionSpec(); | ||||
6910 | |||||
6911 | // Update the type of the special member to use it. | ||||
6912 | UpdateExceptionSpec(FD, ESI); | ||||
6913 | } | ||||
6914 | |||||
6915 | void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { | ||||
6916 | assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted")((FD->isExplicitlyDefaulted() && "not explicitly-defaulted" ) ? static_cast<void> (0) : __assert_fail ("FD->isExplicitlyDefaulted() && \"not explicitly-defaulted\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 6916, __PRETTY_FUNCTION__)); | ||||
6917 | |||||
6918 | DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); | ||||
6919 | if (!DefKind) { | ||||
6920 | assert(FD->getDeclContext()->isDependentContext())((FD->getDeclContext()->isDependentContext()) ? static_cast <void> (0) : __assert_fail ("FD->getDeclContext()->isDependentContext()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 6920, __PRETTY_FUNCTION__)); | ||||
6921 | return; | ||||
6922 | } | ||||
6923 | |||||
6924 | if (DefKind.isSpecialMember() | ||||
6925 | ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), | ||||
6926 | DefKind.asSpecialMember()) | ||||
6927 | : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) | ||||
6928 | FD->setInvalidDecl(); | ||||
6929 | } | ||||
6930 | |||||
6931 | bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, | ||||
6932 | CXXSpecialMember CSM) { | ||||
6933 | CXXRecordDecl *RD = MD->getParent(); | ||||
6934 | |||||
6935 | assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&((MD->isExplicitlyDefaulted() && CSM != CXXInvalid && "not an explicitly-defaulted special member") ? static_cast <void> (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 6936, __PRETTY_FUNCTION__)) | ||||
6936 | "not an explicitly-defaulted special member")((MD->isExplicitlyDefaulted() && CSM != CXXInvalid && "not an explicitly-defaulted special member") ? static_cast <void> (0) : __assert_fail ("MD->isExplicitlyDefaulted() && CSM != CXXInvalid && \"not an explicitly-defaulted special member\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 6936, __PRETTY_FUNCTION__)); | ||||
6937 | |||||
6938 | // Defer all checking for special members of a dependent type. | ||||
6939 | if (RD->isDependentType()) | ||||
6940 | return false; | ||||
6941 | |||||
6942 | // Whether this was the first-declared instance of the constructor. | ||||
6943 | // This affects whether we implicitly add an exception spec and constexpr. | ||||
6944 | bool First = MD == MD->getCanonicalDecl(); | ||||
6945 | |||||
6946 | bool HadError = false; | ||||
6947 | |||||
6948 | // C++11 [dcl.fct.def.default]p1: | ||||
6949 | // A function that is explicitly defaulted shall | ||||
6950 | // -- be a special member function [...] (checked elsewhere), | ||||
6951 | // -- have the same type (except for ref-qualifiers, and except that a | ||||
6952 | // copy operation can take a non-const reference) as an implicit | ||||
6953 | // declaration, and | ||||
6954 | // -- not have default arguments. | ||||
6955 | // C++2a changes the second bullet to instead delete the function if it's | ||||
6956 | // defaulted on its first declaration, unless it's "an assignment operator, | ||||
6957 | // and its return type differs or its parameter type is not a reference". | ||||
6958 | bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First; | ||||
6959 | bool ShouldDeleteForTypeMismatch = false; | ||||
6960 | unsigned ExpectedParams = 1; | ||||
6961 | if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) | ||||
6962 | ExpectedParams = 0; | ||||
6963 | if (MD->getNumParams() != ExpectedParams) { | ||||
6964 | // This checks for default arguments: a copy or move constructor with a | ||||
6965 | // default argument is classified as a default constructor, and assignment | ||||
6966 | // operations and destructors can't have default arguments. | ||||
6967 | Diag(MD->getLocation(), diag::err_defaulted_special_member_params) | ||||
6968 | << CSM << MD->getSourceRange(); | ||||
6969 | HadError = true; | ||||
6970 | } else if (MD->isVariadic()) { | ||||
6971 | if (DeleteOnTypeMismatch) | ||||
6972 | ShouldDeleteForTypeMismatch = true; | ||||
6973 | else { | ||||
6974 | Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) | ||||
6975 | << CSM << MD->getSourceRange(); | ||||
6976 | HadError = true; | ||||
6977 | } | ||||
6978 | } | ||||
6979 | |||||
6980 | const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); | ||||
6981 | |||||
6982 | bool CanHaveConstParam = false; | ||||
6983 | if (CSM == CXXCopyConstructor) | ||||
6984 | CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); | ||||
6985 | else if (CSM == CXXCopyAssignment) | ||||
6986 | CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); | ||||
6987 | |||||
6988 | QualType ReturnType = Context.VoidTy; | ||||
6989 | if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { | ||||
6990 | // Check for return type matching. | ||||
6991 | ReturnType = Type->getReturnType(); | ||||
6992 | |||||
6993 | QualType DeclType = Context.getTypeDeclType(RD); | ||||
6994 | DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); | ||||
6995 | QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); | ||||
6996 | |||||
6997 | if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { | ||||
6998 | Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) | ||||
6999 | << (CSM == CXXMoveAssignment) << ExpectedReturnType; | ||||
7000 | HadError = true; | ||||
7001 | } | ||||
7002 | |||||
7003 | // A defaulted special member cannot have cv-qualifiers. | ||||
7004 | if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { | ||||
7005 | if (DeleteOnTypeMismatch) | ||||
7006 | ShouldDeleteForTypeMismatch = true; | ||||
7007 | else { | ||||
7008 | Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) | ||||
7009 | << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; | ||||
7010 | HadError = true; | ||||
7011 | } | ||||
7012 | } | ||||
7013 | } | ||||
7014 | |||||
7015 | // Check for parameter type matching. | ||||
7016 | QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); | ||||
7017 | bool HasConstParam = false; | ||||
7018 | if (ExpectedParams && ArgType->isReferenceType()) { | ||||
7019 | // Argument must be reference to possibly-const T. | ||||
7020 | QualType ReferentType = ArgType->getPointeeType(); | ||||
7021 | HasConstParam = ReferentType.isConstQualified(); | ||||
7022 | |||||
7023 | if (ReferentType.isVolatileQualified()) { | ||||
7024 | if (DeleteOnTypeMismatch) | ||||
7025 | ShouldDeleteForTypeMismatch = true; | ||||
7026 | else { | ||||
7027 | Diag(MD->getLocation(), | ||||
7028 | diag::err_defaulted_special_member_volatile_param) << CSM; | ||||
7029 | HadError = true; | ||||
7030 | } | ||||
7031 | } | ||||
7032 | |||||
7033 | if (HasConstParam && !CanHaveConstParam) { | ||||
7034 | if (DeleteOnTypeMismatch) | ||||
7035 | ShouldDeleteForTypeMismatch = true; | ||||
7036 | else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { | ||||
7037 | Diag(MD->getLocation(), | ||||
7038 | diag::err_defaulted_special_member_copy_const_param) | ||||
7039 | << (CSM == CXXCopyAssignment); | ||||
7040 | // FIXME: Explain why this special member can't be const. | ||||
7041 | HadError = true; | ||||
7042 | } else { | ||||
7043 | Diag(MD->getLocation(), | ||||
7044 | diag::err_defaulted_special_member_move_const_param) | ||||
7045 | << (CSM == CXXMoveAssignment); | ||||
7046 | HadError = true; | ||||
7047 | } | ||||
7048 | } | ||||
7049 | } else if (ExpectedParams) { | ||||
7050 | // A copy assignment operator can take its argument by value, but a | ||||
7051 | // defaulted one cannot. | ||||
7052 | assert(CSM == CXXCopyAssignment && "unexpected non-ref argument")((CSM == CXXCopyAssignment && "unexpected non-ref argument" ) ? static_cast<void> (0) : __assert_fail ("CSM == CXXCopyAssignment && \"unexpected non-ref argument\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7052, __PRETTY_FUNCTION__)); | ||||
7053 | Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); | ||||
7054 | HadError = true; | ||||
7055 | } | ||||
7056 | |||||
7057 | // C++11 [dcl.fct.def.default]p2: | ||||
7058 | // An explicitly-defaulted function may be declared constexpr only if it | ||||
7059 | // would have been implicitly declared as constexpr, | ||||
7060 | // Do not apply this rule to members of class templates, since core issue 1358 | ||||
7061 | // makes such functions always instantiate to constexpr functions. For | ||||
7062 | // functions which cannot be constexpr (for non-constructors in C++11 and for | ||||
7063 | // destructors in C++14 and C++17), this is checked elsewhere. | ||||
7064 | // | ||||
7065 | // FIXME: This should not apply if the member is deleted. | ||||
7066 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, | ||||
7067 | HasConstParam); | ||||
7068 | if ((getLangOpts().CPlusPlus2a || | ||||
7069 | (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) | ||||
7070 | : isa<CXXConstructorDecl>(MD))) && | ||||
7071 | MD->isConstexpr() && !Constexpr && | ||||
7072 | MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { | ||||
7073 | Diag(MD->getBeginLoc(), MD->isConsteval() | ||||
7074 | ? diag::err_incorrect_defaulted_consteval | ||||
7075 | : diag::err_incorrect_defaulted_constexpr) | ||||
7076 | << CSM; | ||||
7077 | // FIXME: Explain why the special member can't be constexpr. | ||||
7078 | HadError = true; | ||||
7079 | } | ||||
7080 | |||||
7081 | if (First) { | ||||
7082 | // C++2a [dcl.fct.def.default]p3: | ||||
7083 | // If a function is explicitly defaulted on its first declaration, it is | ||||
7084 | // implicitly considered to be constexpr if the implicit declaration | ||||
7085 | // would be. | ||||
7086 | MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified); | ||||
7087 | |||||
7088 | if (!Type->hasExceptionSpec()) { | ||||
7089 | // C++2a [except.spec]p3: | ||||
7090 | // If a declaration of a function does not have a noexcept-specifier | ||||
7091 | // [and] is defaulted on its first declaration, [...] the exception | ||||
7092 | // specification is as specified below | ||||
7093 | FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); | ||||
7094 | EPI.ExceptionSpec.Type = EST_Unevaluated; | ||||
7095 | EPI.ExceptionSpec.SourceDecl = MD; | ||||
7096 | MD->setType(Context.getFunctionType(ReturnType, | ||||
7097 | llvm::makeArrayRef(&ArgType, | ||||
7098 | ExpectedParams), | ||||
7099 | EPI)); | ||||
7100 | } | ||||
7101 | } | ||||
7102 | |||||
7103 | if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { | ||||
7104 | if (First) { | ||||
7105 | SetDeclDeleted(MD, MD->getLocation()); | ||||
7106 | if (!inTemplateInstantiation() && !HadError) { | ||||
7107 | Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; | ||||
7108 | if (ShouldDeleteForTypeMismatch) { | ||||
7109 | Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; | ||||
7110 | } else { | ||||
7111 | ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); | ||||
7112 | } | ||||
7113 | } | ||||
7114 | if (ShouldDeleteForTypeMismatch && !HadError) { | ||||
7115 | Diag(MD->getLocation(), | ||||
7116 | diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; | ||||
7117 | } | ||||
7118 | } else { | ||||
7119 | // C++11 [dcl.fct.def.default]p4: | ||||
7120 | // [For a] user-provided explicitly-defaulted function [...] if such a | ||||
7121 | // function is implicitly defined as deleted, the program is ill-formed. | ||||
7122 | Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; | ||||
7123 | assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl")((!ShouldDeleteForTypeMismatch && "deleted non-first decl" ) ? static_cast<void> (0) : __assert_fail ("!ShouldDeleteForTypeMismatch && \"deleted non-first decl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7123, __PRETTY_FUNCTION__)); | ||||
7124 | ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); | ||||
7125 | HadError = true; | ||||
7126 | } | ||||
7127 | } | ||||
7128 | |||||
7129 | return HadError; | ||||
7130 | } | ||||
7131 | |||||
7132 | namespace { | ||||
7133 | /// Helper class for building and checking a defaulted comparison. | ||||
7134 | /// | ||||
7135 | /// Defaulted functions are built in two phases: | ||||
7136 | /// | ||||
7137 | /// * First, the set of operations that the function will perform are | ||||
7138 | /// identified, and some of them are checked. If any of the checked | ||||
7139 | /// operations is invalid in certain ways, the comparison function is | ||||
7140 | /// defined as deleted and no body is built. | ||||
7141 | /// * Then, if the function is not defined as deleted, the body is built. | ||||
7142 | /// | ||||
7143 | /// This is accomplished by performing two visitation steps over the eventual | ||||
7144 | /// body of the function. | ||||
7145 | template<typename Derived, typename ResultList, typename Result, | ||||
7146 | typename Subobject> | ||||
7147 | class DefaultedComparisonVisitor { | ||||
7148 | public: | ||||
7149 | using DefaultedComparisonKind = Sema::DefaultedComparisonKind; | ||||
7150 | |||||
7151 | DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, | ||||
7152 | DefaultedComparisonKind DCK) | ||||
7153 | : S(S), RD(RD), FD(FD), DCK(DCK) { | ||||
7154 | if (auto *Info = FD->getDefaultedFunctionInfo()) { | ||||
7155 | // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an | ||||
7156 | // UnresolvedSet to avoid this copy. | ||||
7157 | Fns.assign(Info->getUnqualifiedLookups().begin(), | ||||
7158 | Info->getUnqualifiedLookups().end()); | ||||
7159 | } | ||||
7160 | } | ||||
7161 | |||||
7162 | ResultList visit() { | ||||
7163 | // The type of an lvalue naming a parameter of this function. | ||||
7164 | QualType ParamLvalType = | ||||
7165 | FD->getParamDecl(0)->getType().getNonReferenceType(); | ||||
7166 | |||||
7167 | ResultList Results; | ||||
7168 | |||||
7169 | switch (DCK) { | ||||
7170 | case DefaultedComparisonKind::None: | ||||
7171 | llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7171); | ||||
7172 | |||||
7173 | case DefaultedComparisonKind::Equal: | ||||
7174 | case DefaultedComparisonKind::ThreeWay: | ||||
7175 | getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); | ||||
7176 | return Results; | ||||
7177 | |||||
7178 | case DefaultedComparisonKind::NotEqual: | ||||
7179 | case DefaultedComparisonKind::Relational: | ||||
7180 | Results.add(getDerived().visitExpandedSubobject( | ||||
7181 | ParamLvalType, getDerived().getCompleteObject())); | ||||
7182 | return Results; | ||||
7183 | } | ||||
7184 | llvm_unreachable("")::llvm::llvm_unreachable_internal("", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7184); | ||||
7185 | } | ||||
7186 | |||||
7187 | protected: | ||||
7188 | Derived &getDerived() { return static_cast<Derived&>(*this); } | ||||
7189 | |||||
7190 | /// Visit the expanded list of subobjects of the given type, as specified in | ||||
7191 | /// C++2a [class.compare.default]. | ||||
7192 | /// | ||||
7193 | /// \return \c true if the ResultList object said we're done, \c false if not. | ||||
7194 | bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, | ||||
7195 | Qualifiers Quals) { | ||||
7196 | // C++2a [class.compare.default]p4: | ||||
7197 | // The direct base class subobjects of C | ||||
7198 | for (CXXBaseSpecifier &Base : Record->bases()) | ||||
7199 | if (Results.add(getDerived().visitSubobject( | ||||
7200 | S.Context.getQualifiedType(Base.getType(), Quals), | ||||
7201 | getDerived().getBase(&Base)))) | ||||
7202 | return true; | ||||
7203 | |||||
7204 | // followed by the non-static data members of C | ||||
7205 | for (FieldDecl *Field : Record->fields()) { | ||||
7206 | // Recursively expand anonymous structs. | ||||
7207 | if (Field->isAnonymousStructOrUnion()) { | ||||
7208 | if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), | ||||
7209 | Quals)) | ||||
7210 | return true; | ||||
7211 | continue; | ||||
7212 | } | ||||
7213 | |||||
7214 | // Figure out the type of an lvalue denoting this field. | ||||
7215 | Qualifiers FieldQuals = Quals; | ||||
7216 | if (Field->isMutable()) | ||||
7217 | FieldQuals.removeConst(); | ||||
7218 | QualType FieldType = | ||||
7219 | S.Context.getQualifiedType(Field->getType(), FieldQuals); | ||||
7220 | |||||
7221 | if (Results.add(getDerived().visitSubobject( | ||||
7222 | FieldType, getDerived().getField(Field)))) | ||||
7223 | return true; | ||||
7224 | } | ||||
7225 | |||||
7226 | // form a list of subobjects. | ||||
7227 | return false; | ||||
7228 | } | ||||
7229 | |||||
7230 | Result visitSubobject(QualType Type, Subobject Subobj) { | ||||
7231 | // In that list, any subobject of array type is recursively expanded | ||||
7232 | const ArrayType *AT = S.Context.getAsArrayType(Type); | ||||
7233 | if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) | ||||
7234 | return getDerived().visitSubobjectArray(CAT->getElementType(), | ||||
7235 | CAT->getSize(), Subobj); | ||||
7236 | return getDerived().visitExpandedSubobject(Type, Subobj); | ||||
7237 | } | ||||
7238 | |||||
7239 | Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, | ||||
7240 | Subobject Subobj) { | ||||
7241 | return getDerived().visitSubobject(Type, Subobj); | ||||
7242 | } | ||||
7243 | |||||
7244 | protected: | ||||
7245 | Sema &S; | ||||
7246 | CXXRecordDecl *RD; | ||||
7247 | FunctionDecl *FD; | ||||
7248 | DefaultedComparisonKind DCK; | ||||
7249 | UnresolvedSet<16> Fns; | ||||
7250 | }; | ||||
7251 | |||||
7252 | /// Information about a defaulted comparison, as determined by | ||||
7253 | /// DefaultedComparisonAnalyzer. | ||||
7254 | struct DefaultedComparisonInfo { | ||||
7255 | bool Deleted = false; | ||||
7256 | bool Constexpr = true; | ||||
7257 | ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; | ||||
7258 | |||||
7259 | static DefaultedComparisonInfo deleted() { | ||||
7260 | DefaultedComparisonInfo Deleted; | ||||
7261 | Deleted.Deleted = true; | ||||
7262 | return Deleted; | ||||
7263 | } | ||||
7264 | |||||
7265 | bool add(const DefaultedComparisonInfo &R) { | ||||
7266 | Deleted |= R.Deleted; | ||||
7267 | Constexpr &= R.Constexpr; | ||||
7268 | Category = commonComparisonType(Category, R.Category); | ||||
7269 | return Deleted; | ||||
7270 | } | ||||
7271 | }; | ||||
7272 | |||||
7273 | /// An element in the expanded list of subobjects of a defaulted comparison, as | ||||
7274 | /// specified in C++2a [class.compare.default]p4. | ||||
7275 | struct DefaultedComparisonSubobject { | ||||
7276 | enum { CompleteObject, Member, Base } Kind; | ||||
7277 | NamedDecl *Decl; | ||||
7278 | SourceLocation Loc; | ||||
7279 | }; | ||||
7280 | |||||
7281 | /// A visitor over the notional body of a defaulted comparison that determines | ||||
7282 | /// whether that body would be deleted or constexpr. | ||||
7283 | class DefaultedComparisonAnalyzer | ||||
7284 | : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, | ||||
7285 | DefaultedComparisonInfo, | ||||
7286 | DefaultedComparisonInfo, | ||||
7287 | DefaultedComparisonSubobject> { | ||||
7288 | public: | ||||
7289 | enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; | ||||
7290 | |||||
7291 | private: | ||||
7292 | DiagnosticKind Diagnose; | ||||
7293 | |||||
7294 | public: | ||||
7295 | using Base = DefaultedComparisonVisitor; | ||||
7296 | using Result = DefaultedComparisonInfo; | ||||
7297 | using Subobject = DefaultedComparisonSubobject; | ||||
7298 | |||||
7299 | friend Base; | ||||
7300 | |||||
7301 | DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, | ||||
7302 | DefaultedComparisonKind DCK, | ||||
7303 | DiagnosticKind Diagnose = NoDiagnostics) | ||||
7304 | : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} | ||||
7305 | |||||
7306 | Result visit() { | ||||
7307 | if ((DCK == DefaultedComparisonKind::Equal || | ||||
7308 | DCK == DefaultedComparisonKind::ThreeWay) && | ||||
7309 | RD->hasVariantMembers()) { | ||||
7310 | // C++2a [class.compare.default]p2 [P2002R0]: | ||||
7311 | // A defaulted comparison operator function for class C is defined as | ||||
7312 | // deleted if [...] C has variant members. | ||||
7313 | if (Diagnose == ExplainDeleted) { | ||||
7314 | S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) | ||||
7315 | << FD << RD->isUnion() << RD; | ||||
7316 | } | ||||
7317 | return Result::deleted(); | ||||
7318 | } | ||||
7319 | |||||
7320 | return Base::visit(); | ||||
7321 | } | ||||
7322 | |||||
7323 | private: | ||||
7324 | Subobject getCompleteObject() { | ||||
7325 | return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()}; | ||||
7326 | } | ||||
7327 | |||||
7328 | Subobject getBase(CXXBaseSpecifier *Base) { | ||||
7329 | return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), | ||||
7330 | Base->getBaseTypeLoc()}; | ||||
7331 | } | ||||
7332 | |||||
7333 | Subobject getField(FieldDecl *Field) { | ||||
7334 | return Subobject{Subobject::Member, Field, Field->getLocation()}; | ||||
7335 | } | ||||
7336 | |||||
7337 | Result visitExpandedSubobject(QualType Type, Subobject Subobj) { | ||||
7338 | // C++2a [class.compare.default]p2 [P2002R0]: | ||||
7339 | // A defaulted <=> or == operator function for class C is defined as | ||||
7340 | // deleted if any non-static data member of C is of reference type | ||||
7341 | if (Type->isReferenceType()) { | ||||
7342 | if (Diagnose == ExplainDeleted) { | ||||
7343 | S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) | ||||
7344 | << FD << RD; | ||||
7345 | } | ||||
7346 | return Result::deleted(); | ||||
7347 | } | ||||
7348 | |||||
7349 | // [...] Let xi be an lvalue denoting the ith element [...] | ||||
7350 | OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); | ||||
7351 | Expr *Args[] = {&Xi, &Xi}; | ||||
7352 | |||||
7353 | // All operators start by trying to apply that same operator recursively. | ||||
7354 | OverloadedOperatorKind OO = FD->getOverloadedOperator(); | ||||
7355 | assert(OO != OO_None && "not an overloaded operator!")((OO != OO_None && "not an overloaded operator!") ? static_cast <void> (0) : __assert_fail ("OO != OO_None && \"not an overloaded operator!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7355, __PRETTY_FUNCTION__)); | ||||
7356 | return visitBinaryOperator(OO, Args, Subobj); | ||||
7357 | } | ||||
7358 | |||||
7359 | Result | ||||
7360 | visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, | ||||
7361 | Subobject Subobj, | ||||
7362 | OverloadCandidateSet *SpaceshipCandidates = nullptr) { | ||||
7363 | // Note that there is no need to consider rewritten candidates here if | ||||
7364 | // we've already found there is no viable 'operator<=>' candidate (and are | ||||
7365 | // considering synthesizing a '<=>' from '==' and '<'). | ||||
7366 | OverloadCandidateSet CandidateSet( | ||||
7367 | FD->getLocation(), OverloadCandidateSet::CSK_Operator, | ||||
7368 | OverloadCandidateSet::OperatorRewriteInfo( | ||||
7369 | OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); | ||||
7370 | |||||
7371 | /// C++2a [class.compare.default]p1 [P2002R0]: | ||||
7372 | /// [...] the defaulted function itself is never a candidate for overload | ||||
7373 | /// resolution [...] | ||||
7374 | CandidateSet.exclude(FD); | ||||
7375 | |||||
7376 | S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); | ||||
7377 | |||||
7378 | Result R; | ||||
7379 | |||||
7380 | OverloadCandidateSet::iterator Best; | ||||
7381 | switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { | ||||
7382 | case OR_Success: { | ||||
7383 | // C++2a [class.compare.secondary]p2 [P2002R0]: | ||||
7384 | // The operator function [...] is defined as deleted if [...] the | ||||
7385 | // candidate selected by overload resolution is not a rewritten | ||||
7386 | // candidate. | ||||
7387 | if ((DCK == DefaultedComparisonKind::NotEqual || | ||||
7388 | DCK == DefaultedComparisonKind::Relational) && | ||||
7389 | !Best->RewriteKind) { | ||||
7390 | if (Diagnose == ExplainDeleted) { | ||||
7391 | S.Diag(Best->Function->getLocation(), | ||||
7392 | diag::note_defaulted_comparison_not_rewritten_callee) | ||||
7393 | << FD; | ||||
7394 | } | ||||
7395 | return Result::deleted(); | ||||
7396 | } | ||||
7397 | |||||
7398 | // Throughout C++2a [class.compare]: if overload resolution does not | ||||
7399 | // result in a usable function, the candidate function is defined as | ||||
7400 | // deleted. This requires that we selected an accessible function. | ||||
7401 | // | ||||
7402 | // Note that this only considers the access of the function when named | ||||
7403 | // within the type of the subobject, and not the access path for any | ||||
7404 | // derived-to-base conversion. | ||||
7405 | CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); | ||||
7406 | if (ArgClass && Best->FoundDecl.getDecl() && | ||||
7407 | Best->FoundDecl.getDecl()->isCXXClassMember()) { | ||||
7408 | QualType ObjectType = Subobj.Kind == Subobject::Member | ||||
7409 | ? Args[0]->getType() | ||||
7410 | : S.Context.getRecordType(RD); | ||||
7411 | if (!S.isMemberAccessibleForDeletion( | ||||
7412 | ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, | ||||
7413 | Diagnose == ExplainDeleted | ||||
7414 | ? S.PDiag(diag::note_defaulted_comparison_inaccessible) | ||||
7415 | << FD << Subobj.Kind << Subobj.Decl | ||||
7416 | : S.PDiag())) | ||||
7417 | return Result::deleted(); | ||||
7418 | } | ||||
7419 | |||||
7420 | // C++2a [class.compare.default]p3 [P2002R0]: | ||||
7421 | // A defaulted comparison function is constexpr-compatible if [...] | ||||
7422 | // no overlod resolution performed [...] results in a non-constexpr | ||||
7423 | // function. | ||||
7424 | if (FunctionDecl *BestFD = Best->Function) { | ||||
7425 | assert(!BestFD->isDeleted() && "wrong overload resolution result")((!BestFD->isDeleted() && "wrong overload resolution result" ) ? static_cast<void> (0) : __assert_fail ("!BestFD->isDeleted() && \"wrong overload resolution result\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7425, __PRETTY_FUNCTION__)); | ||||
7426 | // If it's not constexpr, explain why not. | ||||
7427 | if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { | ||||
7428 | if (Subobj.Kind != Subobject::CompleteObject) | ||||
7429 | S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) | ||||
7430 | << Subobj.Kind << Subobj.Decl; | ||||
7431 | S.Diag(BestFD->getLocation(), | ||||
7432 | diag::note_defaulted_comparison_not_constexpr_here); | ||||
7433 | // Bail out after explaining; we don't want any more notes. | ||||
7434 | return Result::deleted(); | ||||
7435 | } | ||||
7436 | R.Constexpr &= BestFD->isConstexpr(); | ||||
7437 | } | ||||
7438 | |||||
7439 | if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) { | ||||
7440 | if (auto *BestFD = Best->Function) { | ||||
7441 | if (auto *Info = S.Context.CompCategories.lookupInfoForType( | ||||
7442 | BestFD->getCallResultType())) { | ||||
7443 | R.Category = Info->Kind; | ||||
7444 | } else { | ||||
7445 | if (Diagnose == ExplainDeleted) { | ||||
7446 | S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) | ||||
7447 | << Subobj.Kind << Subobj.Decl | ||||
7448 | << BestFD->getCallResultType().withoutLocalFastQualifiers(); | ||||
7449 | S.Diag(BestFD->getLocation(), | ||||
7450 | diag::note_defaulted_comparison_cannot_deduce_callee) | ||||
7451 | << Subobj.Kind << Subobj.Decl; | ||||
7452 | } | ||||
7453 | return Result::deleted(); | ||||
7454 | } | ||||
7455 | } else { | ||||
7456 | Optional<ComparisonCategoryType> Cat = | ||||
7457 | getComparisonCategoryForBuiltinCmp(Args[0]->getType()); | ||||
7458 | assert(Cat && "no category for builtin comparison?")((Cat && "no category for builtin comparison?") ? static_cast <void> (0) : __assert_fail ("Cat && \"no category for builtin comparison?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7458, __PRETTY_FUNCTION__)); | ||||
7459 | R.Category = *Cat; | ||||
7460 | } | ||||
7461 | } | ||||
7462 | |||||
7463 | // Note that we might be rewriting to a different operator. That call is | ||||
7464 | // not considered until we come to actually build the comparison function. | ||||
7465 | break; | ||||
7466 | } | ||||
7467 | |||||
7468 | case OR_Ambiguous: | ||||
7469 | if (Diagnose == ExplainDeleted) { | ||||
7470 | unsigned Kind = 0; | ||||
7471 | if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) | ||||
7472 | Kind = OO == OO_EqualEqual ? 1 : 2; | ||||
7473 | CandidateSet.NoteCandidates( | ||||
7474 | PartialDiagnosticAt( | ||||
7475 | Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) | ||||
7476 | << FD << Kind << Subobj.Kind << Subobj.Decl), | ||||
7477 | S, OCD_AmbiguousCandidates, Args); | ||||
7478 | } | ||||
7479 | R = Result::deleted(); | ||||
7480 | break; | ||||
7481 | |||||
7482 | case OR_Deleted: | ||||
7483 | if (Diagnose == ExplainDeleted) { | ||||
7484 | if ((DCK == DefaultedComparisonKind::NotEqual || | ||||
7485 | DCK == DefaultedComparisonKind::Relational) && | ||||
7486 | !Best->RewriteKind) { | ||||
7487 | S.Diag(Best->Function->getLocation(), | ||||
7488 | diag::note_defaulted_comparison_not_rewritten_callee) | ||||
7489 | << FD; | ||||
7490 | } else { | ||||
7491 | S.Diag(Subobj.Loc, | ||||
7492 | diag::note_defaulted_comparison_calls_deleted) | ||||
7493 | << FD << Subobj.Kind << Subobj.Decl; | ||||
7494 | S.NoteDeletedFunction(Best->Function); | ||||
7495 | } | ||||
7496 | } | ||||
7497 | R = Result::deleted(); | ||||
7498 | break; | ||||
7499 | |||||
7500 | case OR_No_Viable_Function: | ||||
7501 | // If there's no usable candidate, we're done unless we can rewrite a | ||||
7502 | // '<=>' in terms of '==' and '<'. | ||||
7503 | if (OO == OO_Spaceship && | ||||
7504 | S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { | ||||
7505 | // For any kind of comparison category return type, we need a usable | ||||
7506 | // '==' and a usable '<'. | ||||
7507 | if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, | ||||
7508 | &CandidateSet))) | ||||
7509 | R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); | ||||
7510 | break; | ||||
7511 | } | ||||
7512 | |||||
7513 | if (Diagnose == ExplainDeleted) { | ||||
7514 | S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) | ||||
7515 | << FD << Subobj.Kind << Subobj.Decl; | ||||
7516 | |||||
7517 | // For a three-way comparison, list both the candidates for the | ||||
7518 | // original operator and the candidates for the synthesized operator. | ||||
7519 | if (SpaceshipCandidates) { | ||||
7520 | SpaceshipCandidates->NoteCandidates( | ||||
7521 | S, Args, | ||||
7522 | SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, | ||||
7523 | Args, FD->getLocation())); | ||||
7524 | S.Diag(Subobj.Loc, | ||||
7525 | diag::note_defaulted_comparison_no_viable_function_synthesized) | ||||
7526 | << (OO == OO_EqualEqual ? 0 : 1); | ||||
7527 | } | ||||
7528 | |||||
7529 | CandidateSet.NoteCandidates( | ||||
7530 | S, Args, | ||||
7531 | CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, | ||||
7532 | FD->getLocation())); | ||||
7533 | } | ||||
7534 | R = Result::deleted(); | ||||
7535 | break; | ||||
7536 | } | ||||
7537 | |||||
7538 | return R; | ||||
7539 | } | ||||
7540 | }; | ||||
7541 | |||||
7542 | /// A list of statements. | ||||
7543 | struct StmtListResult { | ||||
7544 | bool IsInvalid = false; | ||||
7545 | llvm::SmallVector<Stmt*, 16> Stmts; | ||||
7546 | |||||
7547 | bool add(const StmtResult &S) { | ||||
7548 | IsInvalid |= S.isInvalid(); | ||||
7549 | if (IsInvalid) | ||||
7550 | return true; | ||||
7551 | Stmts.push_back(S.get()); | ||||
7552 | return false; | ||||
7553 | } | ||||
7554 | }; | ||||
7555 | |||||
7556 | /// A visitor over the notional body of a defaulted comparison that synthesizes | ||||
7557 | /// the actual body. | ||||
7558 | class DefaultedComparisonSynthesizer | ||||
7559 | : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, | ||||
7560 | StmtListResult, StmtResult, | ||||
7561 | std::pair<ExprResult, ExprResult>> { | ||||
7562 | SourceLocation Loc; | ||||
7563 | unsigned ArrayDepth = 0; | ||||
7564 | |||||
7565 | public: | ||||
7566 | using Base = DefaultedComparisonVisitor; | ||||
7567 | using ExprPair = std::pair<ExprResult, ExprResult>; | ||||
7568 | |||||
7569 | friend Base; | ||||
7570 | |||||
7571 | DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, | ||||
7572 | DefaultedComparisonKind DCK, | ||||
7573 | SourceLocation BodyLoc) | ||||
7574 | : Base(S, RD, FD, DCK), Loc(BodyLoc) {} | ||||
7575 | |||||
7576 | /// Build a suitable function body for this defaulted comparison operator. | ||||
7577 | StmtResult build() { | ||||
7578 | Sema::CompoundScopeRAII CompoundScope(S); | ||||
7579 | |||||
7580 | StmtListResult Stmts = visit(); | ||||
7581 | if (Stmts.IsInvalid) | ||||
7582 | return StmtError(); | ||||
7583 | |||||
7584 | ExprResult RetVal; | ||||
7585 | switch (DCK) { | ||||
7586 | case DefaultedComparisonKind::None: | ||||
7587 | llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7587); | ||||
7588 | |||||
7589 | case DefaultedComparisonKind::Equal: { | ||||
7590 | // C++2a [class.eq]p3: | ||||
7591 | // [...] compar[e] the corresponding elements [...] until the first | ||||
7592 | // index i where xi == yi yields [...] false. If no such index exists, | ||||
7593 | // V is true. Otherwise, V is false. | ||||
7594 | // | ||||
7595 | // Join the comparisons with '&&'s and return the result. Use a right | ||||
7596 | // fold (traversing the conditions right-to-left), because that | ||||
7597 | // short-circuits more naturally. | ||||
7598 | auto OldStmts = std::move(Stmts.Stmts); | ||||
7599 | Stmts.Stmts.clear(); | ||||
7600 | ExprResult CmpSoFar; | ||||
7601 | // Finish a particular comparison chain. | ||||
7602 | auto FinishCmp = [&] { | ||||
7603 | if (Expr *Prior = CmpSoFar.get()) { | ||||
7604 | // Convert the last expression to 'return ...;' | ||||
7605 | if (RetVal.isUnset() && Stmts.Stmts.empty()) | ||||
7606 | RetVal = CmpSoFar; | ||||
7607 | // Convert any prior comparison to 'if (!(...)) return false;' | ||||
7608 | else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) | ||||
7609 | return true; | ||||
7610 | CmpSoFar = ExprResult(); | ||||
7611 | } | ||||
7612 | return false; | ||||
7613 | }; | ||||
7614 | for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { | ||||
7615 | Expr *E = dyn_cast<Expr>(EAsStmt); | ||||
7616 | if (!E) { | ||||
7617 | // Found an array comparison. | ||||
7618 | if (FinishCmp() || Stmts.add(EAsStmt)) | ||||
7619 | return StmtError(); | ||||
7620 | continue; | ||||
7621 | } | ||||
7622 | |||||
7623 | if (CmpSoFar.isUnset()) { | ||||
7624 | CmpSoFar = E; | ||||
7625 | continue; | ||||
7626 | } | ||||
7627 | CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); | ||||
7628 | if (CmpSoFar.isInvalid()) | ||||
7629 | return StmtError(); | ||||
7630 | } | ||||
7631 | if (FinishCmp()) | ||||
7632 | return StmtError(); | ||||
7633 | std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); | ||||
7634 | // If no such index exists, V is true. | ||||
7635 | if (RetVal.isUnset()) | ||||
7636 | RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); | ||||
7637 | break; | ||||
7638 | } | ||||
7639 | |||||
7640 | case DefaultedComparisonKind::ThreeWay: { | ||||
7641 | // Per C++2a [class.spaceship]p3, as a fallback add: | ||||
7642 | // return static_cast<R>(std::strong_ordering::equal); | ||||
7643 | QualType StrongOrdering = S.CheckComparisonCategoryType( | ||||
7644 | ComparisonCategoryType::StrongOrdering, Loc, | ||||
7645 | Sema::ComparisonCategoryUsage::DefaultedOperator); | ||||
7646 | if (StrongOrdering.isNull()) | ||||
7647 | return StmtError(); | ||||
7648 | VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) | ||||
7649 | .getValueInfo(ComparisonCategoryResult::Equal) | ||||
7650 | ->VD; | ||||
7651 | RetVal = getDecl(EqualVD); | ||||
7652 | if (RetVal.isInvalid()) | ||||
7653 | return StmtError(); | ||||
7654 | RetVal = buildStaticCastToR(RetVal.get()); | ||||
7655 | break; | ||||
7656 | } | ||||
7657 | |||||
7658 | case DefaultedComparisonKind::NotEqual: | ||||
7659 | case DefaultedComparisonKind::Relational: | ||||
7660 | RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); | ||||
7661 | break; | ||||
7662 | } | ||||
7663 | |||||
7664 | // Build the final return statement. | ||||
7665 | if (RetVal.isInvalid()) | ||||
7666 | return StmtError(); | ||||
7667 | StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); | ||||
7668 | if (ReturnStmt.isInvalid()) | ||||
7669 | return StmtError(); | ||||
7670 | Stmts.Stmts.push_back(ReturnStmt.get()); | ||||
7671 | |||||
7672 | return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); | ||||
7673 | } | ||||
7674 | |||||
7675 | private: | ||||
7676 | ExprResult getDecl(ValueDecl *VD) { | ||||
7677 | return S.BuildDeclarationNameExpr( | ||||
7678 | CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); | ||||
7679 | } | ||||
7680 | |||||
7681 | ExprResult getParam(unsigned I) { | ||||
7682 | ParmVarDecl *PD = FD->getParamDecl(I); | ||||
7683 | return getDecl(PD); | ||||
7684 | } | ||||
7685 | |||||
7686 | ExprPair getCompleteObject() { | ||||
7687 | unsigned Param = 0; | ||||
7688 | ExprResult LHS; | ||||
7689 | if (isa<CXXMethodDecl>(FD)) { | ||||
7690 | // LHS is '*this'. | ||||
7691 | LHS = S.ActOnCXXThis(Loc); | ||||
7692 | if (!LHS.isInvalid()) | ||||
7693 | LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); | ||||
7694 | } else { | ||||
7695 | LHS = getParam(Param++); | ||||
7696 | } | ||||
7697 | ExprResult RHS = getParam(Param++); | ||||
7698 | assert(Param == FD->getNumParams())((Param == FD->getNumParams()) ? static_cast<void> ( 0) : __assert_fail ("Param == FD->getNumParams()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7698, __PRETTY_FUNCTION__)); | ||||
7699 | return {LHS, RHS}; | ||||
7700 | } | ||||
7701 | |||||
7702 | ExprPair getBase(CXXBaseSpecifier *Base) { | ||||
7703 | ExprPair Obj = getCompleteObject(); | ||||
7704 | if (Obj.first.isInvalid() || Obj.second.isInvalid()) | ||||
7705 | return {ExprError(), ExprError()}; | ||||
7706 | CXXCastPath Path = {Base}; | ||||
7707 | return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), | ||||
7708 | CK_DerivedToBase, VK_LValue, &Path), | ||||
7709 | S.ImpCastExprToType(Obj.second.get(), Base->getType(), | ||||
7710 | CK_DerivedToBase, VK_LValue, &Path)}; | ||||
7711 | } | ||||
7712 | |||||
7713 | ExprPair getField(FieldDecl *Field) { | ||||
7714 | ExprPair Obj = getCompleteObject(); | ||||
7715 | if (Obj.first.isInvalid() || Obj.second.isInvalid()) | ||||
7716 | return {ExprError(), ExprError()}; | ||||
7717 | |||||
7718 | DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); | ||||
7719 | DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); | ||||
7720 | return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, | ||||
7721 | CXXScopeSpec(), Field, Found, NameInfo), | ||||
7722 | S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, | ||||
7723 | CXXScopeSpec(), Field, Found, NameInfo)}; | ||||
7724 | } | ||||
7725 | |||||
7726 | // FIXME: When expanding a subobject, register a note in the code synthesis | ||||
7727 | // stack to say which subobject we're comparing. | ||||
7728 | |||||
7729 | StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { | ||||
7730 | if (Cond.isInvalid()) | ||||
7731 | return StmtError(); | ||||
7732 | |||||
7733 | ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); | ||||
7734 | if (NotCond.isInvalid()) | ||||
7735 | return StmtError(); | ||||
7736 | |||||
7737 | ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); | ||||
7738 | assert(!False.isInvalid() && "should never fail")((!False.isInvalid() && "should never fail") ? static_cast <void> (0) : __assert_fail ("!False.isInvalid() && \"should never fail\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7738, __PRETTY_FUNCTION__)); | ||||
7739 | StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); | ||||
7740 | if (ReturnFalse.isInvalid()) | ||||
7741 | return StmtError(); | ||||
7742 | |||||
7743 | return S.ActOnIfStmt(Loc, false, nullptr, | ||||
7744 | S.ActOnCondition(nullptr, Loc, NotCond.get(), | ||||
7745 | Sema::ConditionKind::Boolean), | ||||
7746 | ReturnFalse.get(), SourceLocation(), nullptr); | ||||
7747 | } | ||||
7748 | |||||
7749 | StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, | ||||
7750 | ExprPair Subobj) { | ||||
7751 | QualType SizeType = S.Context.getSizeType(); | ||||
7752 | Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); | ||||
7753 | |||||
7754 | // Build 'size_t i$n = 0'. | ||||
7755 | IdentifierInfo *IterationVarName = nullptr; | ||||
7756 | { | ||||
7757 | SmallString<8> Str; | ||||
7758 | llvm::raw_svector_ostream OS(Str); | ||||
7759 | OS << "i" << ArrayDepth; | ||||
7760 | IterationVarName = &S.Context.Idents.get(OS.str()); | ||||
7761 | } | ||||
7762 | VarDecl *IterationVar = VarDecl::Create( | ||||
7763 | S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, | ||||
7764 | S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); | ||||
7765 | llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); | ||||
7766 | IterationVar->setInit( | ||||
7767 | IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); | ||||
7768 | Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); | ||||
7769 | |||||
7770 | auto IterRef = [&] { | ||||
7771 | ExprResult Ref = S.BuildDeclarationNameExpr( | ||||
7772 | CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), | ||||
7773 | IterationVar); | ||||
7774 | assert(!Ref.isInvalid() && "can't reference our own variable?")((!Ref.isInvalid() && "can't reference our own variable?" ) ? static_cast<void> (0) : __assert_fail ("!Ref.isInvalid() && \"can't reference our own variable?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7774, __PRETTY_FUNCTION__)); | ||||
7775 | return Ref.get(); | ||||
7776 | }; | ||||
7777 | |||||
7778 | // Build 'i$n != Size'. | ||||
7779 | ExprResult Cond = S.CreateBuiltinBinOp( | ||||
7780 | Loc, BO_NE, IterRef(), | ||||
7781 | IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); | ||||
7782 | assert(!Cond.isInvalid() && "should never fail")((!Cond.isInvalid() && "should never fail") ? static_cast <void> (0) : __assert_fail ("!Cond.isInvalid() && \"should never fail\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7782, __PRETTY_FUNCTION__)); | ||||
7783 | |||||
7784 | // Build '++i$n'. | ||||
7785 | ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); | ||||
7786 | assert(!Inc.isInvalid() && "should never fail")((!Inc.isInvalid() && "should never fail") ? static_cast <void> (0) : __assert_fail ("!Inc.isInvalid() && \"should never fail\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7786, __PRETTY_FUNCTION__)); | ||||
7787 | |||||
7788 | // Build 'a[i$n]' and 'b[i$n]'. | ||||
7789 | auto Index = [&](ExprResult E) { | ||||
7790 | if (E.isInvalid()) | ||||
7791 | return ExprError(); | ||||
7792 | return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); | ||||
7793 | }; | ||||
7794 | Subobj.first = Index(Subobj.first); | ||||
7795 | Subobj.second = Index(Subobj.second); | ||||
7796 | |||||
7797 | // Compare the array elements. | ||||
7798 | ++ArrayDepth; | ||||
7799 | StmtResult Substmt = visitSubobject(Type, Subobj); | ||||
7800 | --ArrayDepth; | ||||
7801 | |||||
7802 | if (Substmt.isInvalid()) | ||||
7803 | return StmtError(); | ||||
7804 | |||||
7805 | // For the inner level of an 'operator==', build 'if (!cmp) return false;'. | ||||
7806 | // For outer levels or for an 'operator<=>' we already have a suitable | ||||
7807 | // statement that returns as necessary. | ||||
7808 | if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { | ||||
7809 | assert(DCK == DefaultedComparisonKind::Equal &&((DCK == DefaultedComparisonKind::Equal && "should have non-expression statement" ) ? static_cast<void> (0) : __assert_fail ("DCK == DefaultedComparisonKind::Equal && \"should have non-expression statement\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7810, __PRETTY_FUNCTION__)) | ||||
7810 | "should have non-expression statement")((DCK == DefaultedComparisonKind::Equal && "should have non-expression statement" ) ? static_cast<void> (0) : __assert_fail ("DCK == DefaultedComparisonKind::Equal && \"should have non-expression statement\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7810, __PRETTY_FUNCTION__)); | ||||
7811 | Substmt = buildIfNotCondReturnFalse(ElemCmp); | ||||
7812 | if (Substmt.isInvalid()) | ||||
7813 | return StmtError(); | ||||
7814 | } | ||||
7815 | |||||
7816 | // Build 'for (...) ...' | ||||
7817 | return S.ActOnForStmt(Loc, Loc, Init, | ||||
7818 | S.ActOnCondition(nullptr, Loc, Cond.get(), | ||||
7819 | Sema::ConditionKind::Boolean), | ||||
7820 | S.MakeFullDiscardedValueExpr(Inc.get()), Loc, | ||||
7821 | Substmt.get()); | ||||
7822 | } | ||||
7823 | |||||
7824 | StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { | ||||
7825 | if (Obj.first.isInvalid() || Obj.second.isInvalid()) | ||||
7826 | return StmtError(); | ||||
7827 | |||||
7828 | OverloadedOperatorKind OO = FD->getOverloadedOperator(); | ||||
7829 | ExprResult Op = S.CreateOverloadedBinOp( | ||||
7830 | Loc, BinaryOperator::getOverloadedOpcode(OO), Fns, | ||||
7831 | Obj.first.get(), Obj.second.get(), /*PerformADL=*/true, | ||||
7832 | /*AllowRewrittenCandidates=*/true, FD); | ||||
7833 | if (Op.isInvalid()) | ||||
7834 | return StmtError(); | ||||
7835 | |||||
7836 | switch (DCK) { | ||||
7837 | case DefaultedComparisonKind::None: | ||||
7838 | llvm_unreachable("not a defaulted comparison")::llvm::llvm_unreachable_internal("not a defaulted comparison" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7838); | ||||
7839 | |||||
7840 | case DefaultedComparisonKind::Equal: | ||||
7841 | // Per C++2a [class.eq]p2, each comparison is individually contextually | ||||
7842 | // converted to bool. | ||||
7843 | Op = S.PerformContextuallyConvertToBool(Op.get()); | ||||
7844 | if (Op.isInvalid()) | ||||
7845 | return StmtError(); | ||||
7846 | return Op.get(); | ||||
7847 | |||||
7848 | case DefaultedComparisonKind::ThreeWay: { | ||||
7849 | // Per C++2a [class.spaceship]p3, form: | ||||
7850 | // if (R cmp = static_cast<R>(op); cmp != 0) | ||||
7851 | // return cmp; | ||||
7852 | QualType R = FD->getReturnType(); | ||||
7853 | Op = buildStaticCastToR(Op.get()); | ||||
7854 | if (Op.isInvalid()) | ||||
7855 | return StmtError(); | ||||
7856 | |||||
7857 | // R cmp = ...; | ||||
7858 | IdentifierInfo *Name = &S.Context.Idents.get("cmp"); | ||||
7859 | VarDecl *VD = | ||||
7860 | VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, | ||||
7861 | S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); | ||||
7862 | S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); | ||||
7863 | Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); | ||||
7864 | |||||
7865 | // cmp != 0 | ||||
7866 | ExprResult VDRef = getDecl(VD); | ||||
7867 | if (VDRef.isInvalid()) | ||||
7868 | return StmtError(); | ||||
7869 | llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); | ||||
7870 | Expr *Zero = | ||||
7871 | IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); | ||||
7872 | ExprResult Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), | ||||
7873 | Zero, true, true, FD); | ||||
7874 | if (Comp.isInvalid()) | ||||
7875 | return StmtError(); | ||||
7876 | Sema::ConditionResult Cond = S.ActOnCondition( | ||||
7877 | nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); | ||||
7878 | if (Cond.isInvalid()) | ||||
7879 | return StmtError(); | ||||
7880 | |||||
7881 | // return cmp; | ||||
7882 | VDRef = getDecl(VD); | ||||
7883 | if (VDRef.isInvalid()) | ||||
7884 | return StmtError(); | ||||
7885 | StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); | ||||
7886 | if (ReturnStmt.isInvalid()) | ||||
7887 | return StmtError(); | ||||
7888 | |||||
7889 | // if (...) | ||||
7890 | return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, InitStmt, Cond, | ||||
7891 | ReturnStmt.get(), /*ElseLoc=*/SourceLocation(), | ||||
7892 | /*Else=*/nullptr); | ||||
7893 | } | ||||
7894 | |||||
7895 | case DefaultedComparisonKind::NotEqual: | ||||
7896 | case DefaultedComparisonKind::Relational: | ||||
7897 | // C++2a [class.compare.secondary]p2: | ||||
7898 | // Otherwise, the operator function yields x @ y. | ||||
7899 | return Op.get(); | ||||
7900 | } | ||||
7901 | llvm_unreachable("")::llvm::llvm_unreachable_internal("", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7901); | ||||
7902 | } | ||||
7903 | |||||
7904 | /// Build "static_cast<R>(E)". | ||||
7905 | ExprResult buildStaticCastToR(Expr *E) { | ||||
7906 | QualType R = FD->getReturnType(); | ||||
7907 | assert(!R->isUndeducedType() && "type should have been deduced already")((!R->isUndeducedType() && "type should have been deduced already" ) ? static_cast<void> (0) : __assert_fail ("!R->isUndeducedType() && \"type should have been deduced already\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7907, __PRETTY_FUNCTION__)); | ||||
7908 | |||||
7909 | // Don't bother forming a no-op cast in the common case. | ||||
7910 | if (E->isRValue() && S.Context.hasSameType(E->getType(), R)) | ||||
7911 | return E; | ||||
7912 | return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, | ||||
7913 | S.Context.getTrivialTypeSourceInfo(R, Loc), E, | ||||
7914 | SourceRange(Loc, Loc), SourceRange(Loc, Loc)); | ||||
7915 | } | ||||
7916 | }; | ||||
7917 | } | ||||
7918 | |||||
7919 | /// Perform the unqualified lookups that might be needed to form a defaulted | ||||
7920 | /// comparison function for the given operator. | ||||
7921 | static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, | ||||
7922 | UnresolvedSetImpl &Operators, | ||||
7923 | OverloadedOperatorKind Op) { | ||||
7924 | auto Lookup = [&](OverloadedOperatorKind OO) { | ||||
7925 | Self.LookupOverloadedOperatorName(OO, S, QualType(), QualType(), Operators); | ||||
7926 | }; | ||||
7927 | |||||
7928 | // Every defaulted operator looks up itself. | ||||
7929 | Lookup(Op); | ||||
7930 | // ... and the rewritten form of itself, if any. | ||||
7931 | if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) | ||||
7932 | Lookup(ExtraOp); | ||||
7933 | |||||
7934 | // For 'operator<=>', we also form a 'cmp != 0' expression, and might | ||||
7935 | // synthesize a three-way comparison from '<' and '=='. In a dependent | ||||
7936 | // context, we also need to look up '==' in case we implicitly declare a | ||||
7937 | // defaulted 'operator=='. | ||||
7938 | if (Op == OO_Spaceship) { | ||||
7939 | Lookup(OO_ExclaimEqual); | ||||
7940 | Lookup(OO_Less); | ||||
7941 | Lookup(OO_EqualEqual); | ||||
7942 | } | ||||
7943 | } | ||||
7944 | |||||
7945 | bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, | ||||
7946 | DefaultedComparisonKind DCK) { | ||||
7947 | assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison")((DCK != DefaultedComparisonKind::None && "not a defaulted comparison" ) ? static_cast<void> (0) : __assert_fail ("DCK != DefaultedComparisonKind::None && \"not a defaulted comparison\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7947, __PRETTY_FUNCTION__)); | ||||
7948 | |||||
7949 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); | ||||
7950 | assert(RD && "defaulted comparison is not defaulted in a class")((RD && "defaulted comparison is not defaulted in a class" ) ? static_cast<void> (0) : __assert_fail ("RD && \"defaulted comparison is not defaulted in a class\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 7950, __PRETTY_FUNCTION__)); | ||||
7951 | |||||
7952 | // Perform any unqualified lookups we're going to need to default this | ||||
7953 | // function. | ||||
7954 | if (S) { | ||||
7955 | UnresolvedSet<32> Operators; | ||||
7956 | lookupOperatorsForDefaultedComparison(*this, S, Operators, | ||||
7957 | FD->getOverloadedOperator()); | ||||
7958 | FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( | ||||
7959 | Context, Operators.pairs())); | ||||
7960 | } | ||||
7961 | |||||
7962 | // C++2a [class.compare.default]p1: | ||||
7963 | // A defaulted comparison operator function for some class C shall be a | ||||
7964 | // non-template function declared in the member-specification of C that is | ||||
7965 | // -- a non-static const member of C having one parameter of type | ||||
7966 | // const C&, or | ||||
7967 | // -- a friend of C having two parameters of type const C& or two | ||||
7968 | // parameters of type C. | ||||
7969 | QualType ExpectedParmType1 = Context.getRecordType(RD); | ||||
7970 | QualType ExpectedParmType2 = | ||||
7971 | Context.getLValueReferenceType(ExpectedParmType1.withConst()); | ||||
7972 | if (isa<CXXMethodDecl>(FD)) | ||||
7973 | ExpectedParmType1 = ExpectedParmType2; | ||||
7974 | for (const ParmVarDecl *Param : FD->parameters()) { | ||||
7975 | if (!Param->getType()->isDependentType() && | ||||
7976 | !Context.hasSameType(Param->getType(), ExpectedParmType1) && | ||||
7977 | !Context.hasSameType(Param->getType(), ExpectedParmType2)) { | ||||
7978 | // Don't diagnose an implicit 'operator=='; we will have diagnosed the | ||||
7979 | // corresponding defaulted 'operator<=>' already. | ||||
7980 | if (!FD->isImplicit()) { | ||||
7981 | Diag(FD->getLocation(), diag::err_defaulted_comparison_param) | ||||
7982 | << (int)DCK << Param->getType() << ExpectedParmType1 | ||||
7983 | << !isa<CXXMethodDecl>(FD) | ||||
7984 | << ExpectedParmType2 << Param->getSourceRange(); | ||||
7985 | } | ||||
7986 | return true; | ||||
7987 | } | ||||
7988 | } | ||||
7989 | if (FD->getNumParams() == 2 && | ||||
7990 | !Context.hasSameType(FD->getParamDecl(0)->getType(), | ||||
7991 | FD->getParamDecl(1)->getType())) { | ||||
7992 | if (!FD->isImplicit()) { | ||||
7993 | Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) | ||||
7994 | << (int)DCK | ||||
7995 | << FD->getParamDecl(0)->getType() | ||||
7996 | << FD->getParamDecl(0)->getSourceRange() | ||||
7997 | << FD->getParamDecl(1)->getType() | ||||
7998 | << FD->getParamDecl(1)->getSourceRange(); | ||||
7999 | } | ||||
8000 | return true; | ||||
8001 | } | ||||
8002 | |||||
8003 | // ... non-static const member ... | ||||
8004 | if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { | ||||
8005 | assert(!MD->isStatic() && "comparison function cannot be a static member")((!MD->isStatic() && "comparison function cannot be a static member" ) ? static_cast<void> (0) : __assert_fail ("!MD->isStatic() && \"comparison function cannot be a static member\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 8005, __PRETTY_FUNCTION__)); | ||||
8006 | if (!MD->isConst()) { | ||||
8007 | SourceLocation InsertLoc; | ||||
8008 | if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) | ||||
8009 | InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); | ||||
8010 | // Don't diagnose an implicit 'operator=='; we will have diagnosed the | ||||
8011 | // corresponding defaulted 'operator<=>' already. | ||||
8012 | if (!MD->isImplicit()) { | ||||
8013 | Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) | ||||
8014 | << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); | ||||
8015 | } | ||||
8016 | |||||
8017 | // Add the 'const' to the type to recover. | ||||
8018 | const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); | ||||
8019 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | ||||
8020 | EPI.TypeQuals.addConst(); | ||||
8021 | MD->setType(Context.getFunctionType(FPT->getReturnType(), | ||||
8022 | FPT->getParamTypes(), EPI)); | ||||
8023 | } | ||||
8024 | } else { | ||||
8025 | // A non-member function declared in a class must be a friend. | ||||
8026 | assert(FD->getFriendObjectKind() && "expected a friend declaration")((FD->getFriendObjectKind() && "expected a friend declaration" ) ? static_cast<void> (0) : __assert_fail ("FD->getFriendObjectKind() && \"expected a friend declaration\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 8026, __PRETTY_FUNCTION__)); | ||||
8027 | } | ||||
8028 | |||||
8029 | // C++2a [class.eq]p1, [class.rel]p1: | ||||
8030 | // A [defaulted comparison other than <=>] shall have a declared return | ||||
8031 | // type bool. | ||||
8032 | if (DCK != DefaultedComparisonKind::ThreeWay && | ||||
8033 | !FD->getDeclaredReturnType()->isDependentType() && | ||||
8034 | !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { | ||||
8035 | Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) | ||||
8036 | << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy | ||||
8037 | << FD->getReturnTypeSourceRange(); | ||||
8038 | return true; | ||||
8039 | } | ||||
8040 | // C++2a [class.spaceship]p2 [P2002R0]: | ||||
8041 | // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, | ||||
8042 | // R shall not contain a placeholder type. | ||||
8043 | if (DCK == DefaultedComparisonKind::ThreeWay && | ||||
8044 | FD->getDeclaredReturnType()->getContainedDeducedType() && | ||||
8045 | !Context.hasSameType(FD->getDeclaredReturnType(), | ||||
8046 | Context.getAutoDeductType())) { | ||||
8047 | Diag(FD->getLocation(), | ||||
8048 | diag::err_defaulted_comparison_deduced_return_type_not_auto) | ||||
8049 | << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy | ||||
8050 | << FD->getReturnTypeSourceRange(); | ||||
8051 | return true; | ||||
8052 | } | ||||
8053 | |||||
8054 | // For a defaulted function in a dependent class, defer all remaining checks | ||||
8055 | // until instantiation. | ||||
8056 | if (RD->isDependentType()) | ||||
8057 | return false; | ||||
8058 | |||||
8059 | // Determine whether the function should be defined as deleted. | ||||
8060 | DefaultedComparisonInfo Info = | ||||
8061 | DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); | ||||
8062 | |||||
8063 | bool First = FD == FD->getCanonicalDecl(); | ||||
8064 | |||||
8065 | // If we want to delete the function, then do so; there's nothing else to | ||||
8066 | // check in that case. | ||||
8067 | if (Info.Deleted) { | ||||
8068 | if (!First) { | ||||
8069 | // C++11 [dcl.fct.def.default]p4: | ||||
8070 | // [For a] user-provided explicitly-defaulted function [...] if such a | ||||
8071 | // function is implicitly defined as deleted, the program is ill-formed. | ||||
8072 | // | ||||
8073 | // This is really just a consequence of the general rule that you can | ||||
8074 | // only delete a function on its first declaration. | ||||
8075 | Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) | ||||
8076 | << FD->isImplicit() << (int)DCK; | ||||
8077 | DefaultedComparisonAnalyzer(*this, RD, FD, DCK, | ||||
8078 | DefaultedComparisonAnalyzer::ExplainDeleted) | ||||
8079 | .visit(); | ||||
8080 | return true; | ||||
8081 | } | ||||
8082 | |||||
8083 | SetDeclDeleted(FD, FD->getLocation()); | ||||
8084 | if (!inTemplateInstantiation() && !FD->isImplicit()) { | ||||
8085 | Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) | ||||
8086 | << (int)DCK; | ||||
8087 | DefaultedComparisonAnalyzer(*this, RD, FD, DCK, | ||||
8088 | DefaultedComparisonAnalyzer::ExplainDeleted) | ||||
8089 | .visit(); | ||||
8090 | } | ||||
8091 | return false; | ||||
8092 | } | ||||
8093 | |||||
8094 | // C++2a [class.spaceship]p2: | ||||
8095 | // The return type is deduced as the common comparison type of R0, R1, ... | ||||
8096 | if (DCK == DefaultedComparisonKind::ThreeWay && | ||||
8097 | FD->getDeclaredReturnType()->isUndeducedAutoType()) { | ||||
8098 | SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); | ||||
8099 | if (RetLoc.isInvalid()) | ||||
8100 | RetLoc = FD->getBeginLoc(); | ||||
8101 | // FIXME: Should we really care whether we have the complete type and the | ||||
8102 | // 'enumerator' constants here? A forward declaration seems sufficient. | ||||
8103 | QualType Cat = CheckComparisonCategoryType( | ||||
8104 | Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); | ||||
8105 | if (Cat.isNull()) | ||||
8106 | return true; | ||||
8107 | Context.adjustDeducedFunctionResultType( | ||||
8108 | FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); | ||||
8109 | } | ||||
8110 | |||||
8111 | // C++2a [dcl.fct.def.default]p3 [P2002R0]: | ||||
8112 | // An explicitly-defaulted function that is not defined as deleted may be | ||||
8113 | // declared constexpr or consteval only if it is constexpr-compatible. | ||||
8114 | // C++2a [class.compare.default]p3 [P2002R0]: | ||||
8115 | // A defaulted comparison function is constexpr-compatible if it satisfies | ||||
8116 | // the requirements for a constexpr function [...] | ||||
8117 | // The only relevant requirements are that the parameter and return types are | ||||
8118 | // literal types. The remaining conditions are checked by the analyzer. | ||||
8119 | if (FD->isConstexpr()) { | ||||
8120 | if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && | ||||
8121 | CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && | ||||
8122 | !Info.Constexpr) { | ||||
8123 | Diag(FD->getBeginLoc(), | ||||
8124 | diag::err_incorrect_defaulted_comparison_constexpr) | ||||
8125 | << FD->isImplicit() << (int)DCK << FD->isConsteval(); | ||||
8126 | DefaultedComparisonAnalyzer(*this, RD, FD, DCK, | ||||
8127 | DefaultedComparisonAnalyzer::ExplainConstexpr) | ||||
8128 | .visit(); | ||||
8129 | } | ||||
8130 | } | ||||
8131 | |||||
8132 | // C++2a [dcl.fct.def.default]p3 [P2002R0]: | ||||
8133 | // If a constexpr-compatible function is explicitly defaulted on its first | ||||
8134 | // declaration, it is implicitly considered to be constexpr. | ||||
8135 | // FIXME: Only applying this to the first declaration seems problematic, as | ||||
8136 | // simple reorderings can affect the meaning of the program. | ||||
8137 | if (First && !FD->isConstexpr() && Info.Constexpr) | ||||
8138 | FD->setConstexprKind(CSK_constexpr); | ||||
8139 | |||||
8140 | // C++2a [except.spec]p3: | ||||
8141 | // If a declaration of a function does not have a noexcept-specifier | ||||
8142 | // [and] is defaulted on its first declaration, [...] the exception | ||||
8143 | // specification is as specified below | ||||
8144 | if (FD->getExceptionSpecType() == EST_None) { | ||||
8145 | auto *FPT = FD->getType()->castAs<FunctionProtoType>(); | ||||
8146 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | ||||
8147 | EPI.ExceptionSpec.Type = EST_Unevaluated; | ||||
8148 | EPI.ExceptionSpec.SourceDecl = FD; | ||||
8149 | FD->setType(Context.getFunctionType(FPT->getReturnType(), | ||||
8150 | FPT->getParamTypes(), EPI)); | ||||
8151 | } | ||||
8152 | |||||
8153 | return false; | ||||
8154 | } | ||||
8155 | |||||
8156 | void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, | ||||
8157 | FunctionDecl *Spaceship) { | ||||
8158 | Sema::CodeSynthesisContext Ctx; | ||||
8159 | Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; | ||||
8160 | Ctx.PointOfInstantiation = Spaceship->getEndLoc(); | ||||
8161 | Ctx.Entity = Spaceship; | ||||
8162 | pushCodeSynthesisContext(Ctx); | ||||
8163 | |||||
8164 | if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) | ||||
8165 | EqualEqual->setImplicit(); | ||||
8166 | |||||
8167 | popCodeSynthesisContext(); | ||||
8168 | } | ||||
8169 | |||||
8170 | void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, | ||||
8171 | DefaultedComparisonKind DCK) { | ||||
8172 | assert(FD->isDefaulted() && !FD->isDeleted() &&((FD->isDefaulted() && !FD->isDeleted() && !FD->doesThisDeclarationHaveABody()) ? static_cast<void > (0) : __assert_fail ("FD->isDefaulted() && !FD->isDeleted() && !FD->doesThisDeclarationHaveABody()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 8173, __PRETTY_FUNCTION__)) | ||||
8173 | !FD->doesThisDeclarationHaveABody())((FD->isDefaulted() && !FD->isDeleted() && !FD->doesThisDeclarationHaveABody()) ? static_cast<void > (0) : __assert_fail ("FD->isDefaulted() && !FD->isDeleted() && !FD->doesThisDeclarationHaveABody()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 8173, __PRETTY_FUNCTION__)); | ||||
8174 | if (FD->willHaveBody() || FD->isInvalidDecl()) | ||||
8175 | return; | ||||
8176 | |||||
8177 | SynthesizedFunctionScope Scope(*this, FD); | ||||
8178 | |||||
8179 | // Add a context note for diagnostics produced after this point. | ||||
8180 | Scope.addContextNote(UseLoc); | ||||
8181 | |||||
8182 | { | ||||
8183 | // Build and set up the function body. | ||||
8184 | CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); | ||||
8185 | SourceLocation BodyLoc = | ||||
8186 | FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); | ||||
8187 | StmtResult Body = | ||||
8188 | DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); | ||||
8189 | if (Body.isInvalid()) { | ||||
8190 | FD->setInvalidDecl(); | ||||
8191 | return; | ||||
8192 | } | ||||
8193 | FD->setBody(Body.get()); | ||||
8194 | FD->markUsed(Context); | ||||
8195 | } | ||||
8196 | |||||
8197 | // The exception specification is needed because we are defining the | ||||
8198 | // function. Note that this will reuse the body we just built. | ||||
8199 | ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); | ||||
8200 | |||||
8201 | if (ASTMutationListener *L = getASTMutationListener()) | ||||
8202 | L->CompletedImplicitDefinition(FD); | ||||
8203 | } | ||||
8204 | |||||
8205 | static Sema::ImplicitExceptionSpecification | ||||
8206 | ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, | ||||
8207 | FunctionDecl *FD, | ||||
8208 | Sema::DefaultedComparisonKind DCK) { | ||||
8209 | ComputingExceptionSpec CES(S, FD, Loc); | ||||
8210 | Sema::ImplicitExceptionSpecification ExceptSpec(S); | ||||
8211 | |||||
8212 | if (FD->isInvalidDecl()) | ||||
8213 | return ExceptSpec; | ||||
8214 | |||||
8215 | // The common case is that we just defined the comparison function. In that | ||||
8216 | // case, just look at whether the body can throw. | ||||
8217 | if (FD->hasBody()) { | ||||
8218 | ExceptSpec.CalledStmt(FD->getBody()); | ||||
8219 | } else { | ||||
8220 | // Otherwise, build a body so we can check it. This should ideally only | ||||
8221 | // happen when we're not actually marking the function referenced. (This is | ||||
8222 | // only really important for efficiency: we don't want to build and throw | ||||
8223 | // away bodies for comparison functions more than we strictly need to.) | ||||
8224 | |||||
8225 | // Pretend to synthesize the function body in an unevaluated context. | ||||
8226 | // Note that we can't actually just go ahead and define the function here: | ||||
8227 | // we are not permitted to mark its callees as referenced. | ||||
8228 | Sema::SynthesizedFunctionScope Scope(S, FD); | ||||
8229 | EnterExpressionEvaluationContext Context( | ||||
8230 | S, Sema::ExpressionEvaluationContext::Unevaluated); | ||||
8231 | |||||
8232 | CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); | ||||
8233 | SourceLocation BodyLoc = | ||||
8234 | FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); | ||||
8235 | StmtResult Body = | ||||
8236 | DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); | ||||
8237 | if (!Body.isInvalid()) | ||||
8238 | ExceptSpec.CalledStmt(Body.get()); | ||||
8239 | |||||
8240 | // FIXME: Can we hold onto this body and just transform it to potentially | ||||
8241 | // evaluated when we're asked to define the function rather than rebuilding | ||||
8242 | // it? Either that, or we should only build the bits of the body that we | ||||
8243 | // need (the expressions, not the statements). | ||||
8244 | } | ||||
8245 | |||||
8246 | return ExceptSpec; | ||||
8247 | } | ||||
8248 | |||||
8249 | void Sema::CheckDelayedMemberExceptionSpecs() { | ||||
8250 | decltype(DelayedOverridingExceptionSpecChecks) Overriding; | ||||
8251 | decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; | ||||
8252 | |||||
8253 | std::swap(Overriding, DelayedOverridingExceptionSpecChecks); | ||||
8254 | std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); | ||||
8255 | |||||
8256 | // Perform any deferred checking of exception specifications for virtual | ||||
8257 | // destructors. | ||||
8258 | for (auto &Check : Overriding) | ||||
8259 | CheckOverridingFunctionExceptionSpec(Check.first, Check.second); | ||||
8260 | |||||
8261 | // Perform any deferred checking of exception specifications for befriended | ||||
8262 | // special members. | ||||
8263 | for (auto &Check : Equivalent) | ||||
8264 | CheckEquivalentExceptionSpec(Check.second, Check.first); | ||||
8265 | } | ||||
8266 | |||||
8267 | namespace { | ||||
8268 | /// CRTP base class for visiting operations performed by a special member | ||||
8269 | /// function (or inherited constructor). | ||||
8270 | template<typename Derived> | ||||
8271 | struct SpecialMemberVisitor { | ||||
8272 | Sema &S; | ||||
8273 | CXXMethodDecl *MD; | ||||
8274 | Sema::CXXSpecialMember CSM; | ||||
8275 | Sema::InheritedConstructorInfo *ICI; | ||||
8276 | |||||
8277 | // Properties of the special member, computed for convenience. | ||||
8278 | bool IsConstructor = false, IsAssignment = false, ConstArg = false; | ||||
8279 | |||||
8280 | SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, | ||||
8281 | Sema::InheritedConstructorInfo *ICI) | ||||
8282 | : S(S), MD(MD), CSM(CSM), ICI(ICI) { | ||||
8283 | switch (CSM) { | ||||
8284 | case Sema::CXXDefaultConstructor: | ||||
8285 | case Sema::CXXCopyConstructor: | ||||
8286 | case Sema::CXXMoveConstructor: | ||||
8287 | IsConstructor = true; | ||||
8288 | break; | ||||
8289 | case Sema::CXXCopyAssignment: | ||||
8290 | case Sema::CXXMoveAssignment: | ||||
8291 | IsAssignment = true; | ||||
8292 | break; | ||||
8293 | case Sema::CXXDestructor: | ||||
8294 | break; | ||||
8295 | case Sema::CXXInvalid: | ||||
8296 | llvm_unreachable("invalid special member kind")::llvm::llvm_unreachable_internal("invalid special member kind" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 8296); | ||||
8297 | } | ||||
8298 | |||||
8299 | if (MD->getNumParams()) { | ||||
8300 | if (const ReferenceType *RT = | ||||
8301 | MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) | ||||
8302 | ConstArg = RT->getPointeeType().isConstQualified(); | ||||
8303 | } | ||||
8304 | } | ||||
8305 | |||||
8306 | Derived &getDerived() { return static_cast<Derived&>(*this); } | ||||
8307 | |||||
8308 | /// Is this a "move" special member? | ||||
8309 | bool isMove() const { | ||||
8310 | return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; | ||||
8311 | } | ||||
8312 | |||||
8313 | /// Look up the corresponding special member in the given class. | ||||
8314 | Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, | ||||
8315 | unsigned Quals, bool IsMutable) { | ||||
8316 | return lookupCallFromSpecialMember(S, Class, CSM, Quals, | ||||
8317 | ConstArg && !IsMutable); | ||||
8318 | } | ||||
8319 | |||||
8320 | /// Look up the constructor for the specified base class to see if it's | ||||
8321 | /// overridden due to this being an inherited constructor. | ||||
8322 | Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { | ||||
8323 | if (!ICI) | ||||
8324 | return {}; | ||||
8325 | assert(CSM == Sema::CXXDefaultConstructor)((CSM == Sema::CXXDefaultConstructor) ? static_cast<void> (0) : __assert_fail ("CSM == Sema::CXXDefaultConstructor", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 8325, __PRETTY_FUNCTION__)); | ||||
8326 | auto *BaseCtor = | ||||
8327 | cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); | ||||
8328 | if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) | ||||
8329 | return MD; | ||||
8330 | return {}; | ||||
8331 | } | ||||
8332 | |||||
8333 | /// A base or member subobject. | ||||
8334 | typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; | ||||
8335 | |||||
8336 | /// Get the location to use for a subobject in diagnostics. | ||||
8337 | static SourceLocation getSubobjectLoc(Subobject Subobj) { | ||||
8338 | // FIXME: For an indirect virtual base, the direct base leading to | ||||
8339 | // the indirect virtual base would be a more useful choice. | ||||
8340 | if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) | ||||
8341 | return B->getBaseTypeLoc(); | ||||
8342 | else | ||||
8343 | return Subobj.get<FieldDecl*>()->getLocation(); | ||||
8344 | } | ||||
8345 | |||||
8346 | enum BasesToVisit { | ||||
8347 | /// Visit all non-virtual (direct) bases. | ||||
8348 | VisitNonVirtualBases, | ||||
8349 | /// Visit all direct bases, virtual or not. | ||||
8350 | VisitDirectBases, | ||||
8351 | /// Visit all non-virtual bases, and all virtual bases if the class | ||||
8352 | /// is not abstract. | ||||
8353 | VisitPotentiallyConstructedBases, | ||||
8354 | /// Visit all direct or virtual bases. | ||||
8355 | VisitAllBases | ||||
8356 | }; | ||||
8357 | |||||
8358 | // Visit the bases and members of the class. | ||||
8359 | bool visit(BasesToVisit Bases) { | ||||
8360 | CXXRecordDecl *RD = MD->getParent(); | ||||
8361 | |||||
8362 | if (Bases == VisitPotentiallyConstructedBases) | ||||
8363 | Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; | ||||
8364 | |||||
8365 | for (auto &B : RD->bases()) | ||||
8366 | if ((Bases == VisitDirectBases || !B.isVirtual()) && | ||||
8367 | getDerived().visitBase(&B)) | ||||
8368 | return true; | ||||
8369 | |||||
8370 | if (Bases == VisitAllBases) | ||||
8371 | for (auto &B : RD->vbases()) | ||||
8372 | if (getDerived().visitBase(&B)) | ||||
8373 | return true; | ||||
8374 | |||||
8375 | for (auto *F : RD->fields()) | ||||
8376 | if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && | ||||
8377 | getDerived().visitField(F)) | ||||
8378 | return true; | ||||
8379 | |||||
8380 | return false; | ||||
8381 | } | ||||
8382 | }; | ||||
8383 | } | ||||
8384 | |||||
8385 | namespace { | ||||
8386 | struct SpecialMemberDeletionInfo | ||||
8387 | : SpecialMemberVisitor<SpecialMemberDeletionInfo> { | ||||
8388 | bool Diagnose; | ||||
8389 | |||||
8390 | SourceLocation Loc; | ||||
8391 | |||||
8392 | bool AllFieldsAreConst; | ||||
8393 | |||||
8394 | SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, | ||||
8395 | Sema::CXXSpecialMember CSM, | ||||
8396 | Sema::InheritedConstructorInfo *ICI, bool Diagnose) | ||||
8397 | : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), | ||||
8398 | Loc(MD->getLocation()), AllFieldsAreConst(true) {} | ||||
8399 | |||||
8400 | bool inUnion() const { return MD->getParent()->isUnion(); } | ||||
8401 | |||||
8402 | Sema::CXXSpecialMember getEffectiveCSM() { | ||||
8403 | return ICI ? Sema::CXXInvalid : CSM; | ||||
8404 | } | ||||
8405 | |||||
8406 | bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); | ||||
8407 | |||||
8408 | bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } | ||||
8409 | bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } | ||||
8410 | |||||
8411 | bool shouldDeleteForBase(CXXBaseSpecifier *Base); | ||||
8412 | bool shouldDeleteForField(FieldDecl *FD); | ||||
8413 | bool shouldDeleteForAllConstMembers(); | ||||
8414 | |||||
8415 | bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, | ||||
8416 | unsigned Quals); | ||||
8417 | bool shouldDeleteForSubobjectCall(Subobject Subobj, | ||||
8418 | Sema::SpecialMemberOverloadResult SMOR, | ||||
8419 | bool IsDtorCallInCtor); | ||||
8420 | |||||
8421 | bool isAccessible(Subobject Subobj, CXXMethodDecl *D); | ||||
8422 | }; | ||||
8423 | } | ||||
8424 | |||||
8425 | /// Is the given special member inaccessible when used on the given | ||||
8426 | /// sub-object. | ||||
8427 | bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, | ||||
8428 | CXXMethodDecl *target) { | ||||
8429 | /// If we're operating on a base class, the object type is the | ||||
8430 | /// type of this special member. | ||||
8431 | QualType objectTy; | ||||
8432 | AccessSpecifier access = target->getAccess(); | ||||
8433 | if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { | ||||
8434 | objectTy = S.Context.getTypeDeclType(MD->getParent()); | ||||
8435 | access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); | ||||
8436 | |||||
8437 | // If we're operating on a field, the object type is the type of the field. | ||||
8438 | } else { | ||||
8439 | objectTy = S.Context.getTypeDeclType(target->getParent()); | ||||
8440 | } | ||||
8441 | |||||
8442 | return S.isMemberAccessibleForDeletion( | ||||
8443 | target->getParent(), DeclAccessPair::make(target, access), objectTy); | ||||
8444 | } | ||||
8445 | |||||
8446 | /// Check whether we should delete a special member due to the implicit | ||||
8447 | /// definition containing a call to a special member of a subobject. | ||||
8448 | bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( | ||||
8449 | Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, | ||||
8450 | bool IsDtorCallInCtor) { | ||||
8451 | CXXMethodDecl *Decl = SMOR.getMethod(); | ||||
8452 | FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); | ||||
8453 | |||||
8454 | int DiagKind = -1; | ||||
8455 | |||||
8456 | if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) | ||||
8457 | DiagKind = !Decl ? 0 : 1; | ||||
8458 | else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) | ||||
8459 | DiagKind = 2; | ||||
8460 | else if (!isAccessible(Subobj, Decl)) | ||||
8461 | DiagKind = 3; | ||||
8462 | else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && | ||||
8463 | !Decl->isTrivial()) { | ||||
8464 | // A member of a union must have a trivial corresponding special member. | ||||
8465 | // As a weird special case, a destructor call from a union's constructor | ||||
8466 | // must be accessible and non-deleted, but need not be trivial. Such a | ||||
8467 | // destructor is never actually called, but is semantically checked as | ||||
8468 | // if it were. | ||||
8469 | DiagKind = 4; | ||||
8470 | } | ||||
8471 | |||||
8472 | if (DiagKind == -1) | ||||
8473 | return false; | ||||
8474 | |||||
8475 | if (Diagnose) { | ||||
8476 | if (Field) { | ||||
8477 | S.Diag(Field->getLocation(), | ||||
8478 | diag::note_deleted_special_member_class_subobject) | ||||
8479 | << getEffectiveCSM() << MD->getParent() << /*IsField*/true | ||||
8480 | << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; | ||||
8481 | } else { | ||||
8482 | CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); | ||||
8483 | S.Diag(Base->getBeginLoc(), | ||||
8484 | diag::note_deleted_special_member_class_subobject) | ||||
8485 | << getEffectiveCSM() << MD->getParent() << /*IsField*/ false | ||||
8486 | << Base->getType() << DiagKind << IsDtorCallInCtor | ||||
8487 | << /*IsObjCPtr*/false; | ||||
8488 | } | ||||
8489 | |||||
8490 | if (DiagKind == 1) | ||||
8491 | S.NoteDeletedFunction(Decl); | ||||
8492 | // FIXME: Explain inaccessibility if DiagKind == 3. | ||||
8493 | } | ||||
8494 | |||||
8495 | return true; | ||||
8496 | } | ||||
8497 | |||||
8498 | /// Check whether we should delete a special member function due to having a | ||||
8499 | /// direct or virtual base class or non-static data member of class type M. | ||||
8500 | bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( | ||||
8501 | CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { | ||||
8502 | FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); | ||||
8503 | bool IsMutable = Field && Field->isMutable(); | ||||
8504 | |||||
8505 | // C++11 [class.ctor]p5: | ||||
8506 | // -- any direct or virtual base class, or non-static data member with no | ||||
8507 | // brace-or-equal-initializer, has class type M (or array thereof) and | ||||
8508 | // either M has no default constructor or overload resolution as applied | ||||
8509 | // to M's default constructor results in an ambiguity or in a function | ||||
8510 | // that is deleted or inaccessible | ||||
8511 | // C++11 [class.copy]p11, C++11 [class.copy]p23: | ||||
8512 | // -- a direct or virtual base class B that cannot be copied/moved because | ||||
8513 | // overload resolution, as applied to B's corresponding special member, | ||||
8514 | // results in an ambiguity or a function that is deleted or inaccessible | ||||
8515 | // from the defaulted special member | ||||
8516 | // C++11 [class.dtor]p5: | ||||
8517 | // -- any direct or virtual base class [...] has a type with a destructor | ||||
8518 | // that is deleted or inaccessible | ||||
8519 | if (!(CSM == Sema::CXXDefaultConstructor && | ||||
8520 | Field && Field->hasInClassInitializer()) && | ||||
8521 | shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), | ||||
8522 | false)) | ||||
8523 | return true; | ||||
8524 | |||||
8525 | // C++11 [class.ctor]p5, C++11 [class.copy]p11: | ||||
8526 | // -- any direct or virtual base class or non-static data member has a | ||||
8527 | // type with a destructor that is deleted or inaccessible | ||||
8528 | if (IsConstructor) { | ||||
8529 | Sema::SpecialMemberOverloadResult SMOR = | ||||
8530 | S.LookupSpecialMember(Class, Sema::CXXDestructor, | ||||
8531 | false, false, false, false, false); | ||||
8532 | if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) | ||||
8533 | return true; | ||||
8534 | } | ||||
8535 | |||||
8536 | return false; | ||||
8537 | } | ||||
8538 | |||||
8539 | bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( | ||||
8540 | FieldDecl *FD, QualType FieldType) { | ||||
8541 | // The defaulted special functions are defined as deleted if this is a variant | ||||
8542 | // member with a non-trivial ownership type, e.g., ObjC __strong or __weak | ||||
8543 | // type under ARC. | ||||
8544 | if (!FieldType.hasNonTrivialObjCLifetime()) | ||||
8545 | return false; | ||||
8546 | |||||
8547 | // Don't make the defaulted default constructor defined as deleted if the | ||||
8548 | // member has an in-class initializer. | ||||
8549 | if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) | ||||
8550 | return false; | ||||
8551 | |||||
8552 | if (Diagnose) { | ||||
8553 | auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); | ||||
8554 | S.Diag(FD->getLocation(), | ||||
8555 | diag::note_deleted_special_member_class_subobject) | ||||
8556 | << getEffectiveCSM() << ParentClass << /*IsField*/true | ||||
8557 | << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; | ||||
8558 | } | ||||
8559 | |||||
8560 | return true; | ||||
8561 | } | ||||
8562 | |||||
8563 | /// Check whether we should delete a special member function due to the class | ||||
8564 | /// having a particular direct or virtual base class. | ||||
8565 | bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { | ||||
8566 | CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); | ||||
8567 | // If program is correct, BaseClass cannot be null, but if it is, the error | ||||
8568 | // must be reported elsewhere. | ||||
8569 | if (!BaseClass) | ||||
8570 | return false; | ||||
8571 | // If we have an inheriting constructor, check whether we're calling an | ||||
8572 | // inherited constructor instead of a default constructor. | ||||
8573 | Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); | ||||
8574 | if (auto *BaseCtor = SMOR.getMethod()) { | ||||
8575 | // Note that we do not check access along this path; other than that, | ||||
8576 | // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); | ||||
8577 | // FIXME: Check that the base has a usable destructor! Sink this into | ||||
8578 | // shouldDeleteForClassSubobject. | ||||
8579 | if (BaseCtor->isDeleted() && Diagnose) { | ||||
8580 | S.Diag(Base->getBeginLoc(), | ||||
8581 | diag::note_deleted_special_member_class_subobject) | ||||
8582 | << getEffectiveCSM() << MD->getParent() << /*IsField*/ false | ||||
8583 | << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false | ||||
8584 | << /*IsObjCPtr*/false; | ||||
8585 | S.NoteDeletedFunction(BaseCtor); | ||||
8586 | } | ||||
8587 | return BaseCtor->isDeleted(); | ||||
8588 | } | ||||
8589 | return shouldDeleteForClassSubobject(BaseClass, Base, 0); | ||||
8590 | } | ||||
8591 | |||||
8592 | /// Check whether we should delete a special member function due to the class | ||||
8593 | /// having a particular non-static data member. | ||||
8594 | bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { | ||||
8595 | QualType FieldType = S.Context.getBaseElementType(FD->getType()); | ||||
8596 | CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); | ||||
8597 | |||||
8598 | if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) | ||||
8599 | return true; | ||||
8600 | |||||
8601 | if (CSM == Sema::CXXDefaultConstructor) { | ||||
8602 | // For a default constructor, all references must be initialized in-class | ||||
8603 | // and, if a union, it must have a non-const member. | ||||
8604 | if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { | ||||
8605 | if (Diagnose) | ||||
8606 | S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) | ||||
8607 | << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; | ||||
8608 | return true; | ||||
8609 | } | ||||
8610 | // C++11 [class.ctor]p5: any non-variant non-static data member of | ||||
8611 | // const-qualified type (or array thereof) with no | ||||
8612 | // brace-or-equal-initializer does not have a user-provided default | ||||
8613 | // constructor. | ||||
8614 | if (!inUnion() && FieldType.isConstQualified() && | ||||
8615 | !FD->hasInClassInitializer() && | ||||
8616 | (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { | ||||
8617 | if (Diagnose) | ||||
8618 | S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) | ||||
8619 | << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; | ||||
8620 | return true; | ||||
8621 | } | ||||
8622 | |||||
8623 | if (inUnion() && !FieldType.isConstQualified()) | ||||
8624 | AllFieldsAreConst = false; | ||||
8625 | } else if (CSM == Sema::CXXCopyConstructor) { | ||||
8626 | // For a copy constructor, data members must not be of rvalue reference | ||||
8627 | // type. | ||||
8628 | if (FieldType->isRValueReferenceType()) { | ||||
8629 | if (Diagnose) | ||||
8630 | S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) | ||||
8631 | << MD->getParent() << FD << FieldType; | ||||
8632 | return true; | ||||
8633 | } | ||||
8634 | } else if (IsAssignment) { | ||||
8635 | // For an assignment operator, data members must not be of reference type. | ||||
8636 | if (FieldType->isReferenceType()) { | ||||
8637 | if (Diagnose) | ||||
8638 | S.Diag(FD->getLocation(), diag::note_deleted_assign_field) | ||||
8639 | << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; | ||||
8640 | return true; | ||||
8641 | } | ||||
8642 | if (!FieldRecord && FieldType.isConstQualified()) { | ||||
8643 | // C++11 [class.copy]p23: | ||||
8644 | // -- a non-static data member of const non-class type (or array thereof) | ||||
8645 | if (Diagnose) | ||||
8646 | S.Diag(FD->getLocation(), diag::note_deleted_assign_field) | ||||
8647 | << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; | ||||
8648 | return true; | ||||
8649 | } | ||||
8650 | } | ||||
8651 | |||||
8652 | if (FieldRecord) { | ||||
8653 | // Some additional restrictions exist on the variant members. | ||||
8654 | if (!inUnion() && FieldRecord->isUnion() && | ||||
8655 | FieldRecord->isAnonymousStructOrUnion()) { | ||||
8656 | bool AllVariantFieldsAreConst = true; | ||||
8657 | |||||
8658 | // FIXME: Handle anonymous unions declared within anonymous unions. | ||||
8659 | for (auto *UI : FieldRecord->fields()) { | ||||
8660 | QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); | ||||
8661 | |||||
8662 | if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) | ||||
8663 | return true; | ||||
8664 | |||||
8665 | if (!UnionFieldType.isConstQualified()) | ||||
8666 | AllVariantFieldsAreConst = false; | ||||
8667 | |||||
8668 | CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); | ||||
8669 | if (UnionFieldRecord && | ||||
8670 | shouldDeleteForClassSubobject(UnionFieldRecord, UI, | ||||
8671 | UnionFieldType.getCVRQualifiers())) | ||||
8672 | return true; | ||||
8673 | } | ||||
8674 | |||||
8675 | // At least one member in each anonymous union must be non-const | ||||
8676 | if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && | ||||
8677 | !FieldRecord->field_empty()) { | ||||
8678 | if (Diagnose) | ||||
8679 | S.Diag(FieldRecord->getLocation(), | ||||
8680 | diag::note_deleted_default_ctor_all_const) | ||||
8681 | << !!ICI << MD->getParent() << /*anonymous union*/1; | ||||
8682 | return true; | ||||
8683 | } | ||||
8684 | |||||
8685 | // Don't check the implicit member of the anonymous union type. | ||||
8686 | // This is technically non-conformant, but sanity demands it. | ||||
8687 | return false; | ||||
8688 | } | ||||
8689 | |||||
8690 | if (shouldDeleteForClassSubobject(FieldRecord, FD, | ||||
8691 | FieldType.getCVRQualifiers())) | ||||
8692 | return true; | ||||
8693 | } | ||||
8694 | |||||
8695 | return false; | ||||
8696 | } | ||||
8697 | |||||
8698 | /// C++11 [class.ctor] p5: | ||||
8699 | /// A defaulted default constructor for a class X is defined as deleted if | ||||
8700 | /// X is a union and all of its variant members are of const-qualified type. | ||||
8701 | bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { | ||||
8702 | // This is a silly definition, because it gives an empty union a deleted | ||||
8703 | // default constructor. Don't do that. | ||||
8704 | if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { | ||||
8705 | bool AnyFields = false; | ||||
8706 | for (auto *F : MD->getParent()->fields()) | ||||
8707 | if ((AnyFields = !F->isUnnamedBitfield())) | ||||
8708 | break; | ||||
8709 | if (!AnyFields) | ||||
8710 | return false; | ||||
8711 | if (Diagnose) | ||||
8712 | S.Diag(MD->getParent()->getLocation(), | ||||
8713 | diag::note_deleted_default_ctor_all_const) | ||||
8714 | << !!ICI << MD->getParent() << /*not anonymous union*/0; | ||||
8715 | return true; | ||||
8716 | } | ||||
8717 | return false; | ||||
8718 | } | ||||
8719 | |||||
8720 | /// Determine whether a defaulted special member function should be defined as | ||||
8721 | /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, | ||||
8722 | /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. | ||||
8723 | bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, | ||||
8724 | InheritedConstructorInfo *ICI, | ||||
8725 | bool Diagnose) { | ||||
8726 | if (MD->isInvalidDecl()) | ||||
8727 | return false; | ||||
8728 | CXXRecordDecl *RD = MD->getParent(); | ||||
8729 | assert(!RD->isDependentType() && "do deletion after instantiation")((!RD->isDependentType() && "do deletion after instantiation" ) ? static_cast<void> (0) : __assert_fail ("!RD->isDependentType() && \"do deletion after instantiation\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 8729, __PRETTY_FUNCTION__)); | ||||
8730 | if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) | ||||
8731 | return false; | ||||
8732 | |||||
8733 | // C++11 [expr.lambda.prim]p19: | ||||
8734 | // The closure type associated with a lambda-expression has a | ||||
8735 | // deleted (8.4.3) default constructor and a deleted copy | ||||
8736 | // assignment operator. | ||||
8737 | // C++2a adds back these operators if the lambda has no lambda-capture. | ||||
8738 | if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && | ||||
8739 | (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { | ||||
8740 | if (Diagnose) | ||||
8741 | Diag(RD->getLocation(), diag::note_lambda_decl); | ||||
8742 | return true; | ||||
8743 | } | ||||
8744 | |||||
8745 | // For an anonymous struct or union, the copy and assignment special members | ||||
8746 | // will never be used, so skip the check. For an anonymous union declared at | ||||
8747 | // namespace scope, the constructor and destructor are used. | ||||
8748 | if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && | ||||
8749 | RD->isAnonymousStructOrUnion()) | ||||
8750 | return false; | ||||
8751 | |||||
8752 | // C++11 [class.copy]p7, p18: | ||||
8753 | // If the class definition declares a move constructor or move assignment | ||||
8754 | // operator, an implicitly declared copy constructor or copy assignment | ||||
8755 | // operator is defined as deleted. | ||||
8756 | if (MD->isImplicit() && | ||||
8757 | (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { | ||||
8758 | CXXMethodDecl *UserDeclaredMove = nullptr; | ||||
8759 | |||||
8760 | // In Microsoft mode up to MSVC 2013, a user-declared move only causes the | ||||
8761 | // deletion of the corresponding copy operation, not both copy operations. | ||||
8762 | // MSVC 2015 has adopted the standards conforming behavior. | ||||
8763 | bool DeletesOnlyMatchingCopy = | ||||
8764 | getLangOpts().MSVCCompat && | ||||
8765 | !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); | ||||
8766 | |||||
8767 | if (RD->hasUserDeclaredMoveConstructor() && | ||||
8768 | (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { | ||||
8769 | if (!Diagnose) return true; | ||||
8770 | |||||
8771 | // Find any user-declared move constructor. | ||||
8772 | for (auto *I : RD->ctors()) { | ||||
8773 | if (I->isMoveConstructor()) { | ||||
8774 | UserDeclaredMove = I; | ||||
8775 | break; | ||||
8776 | } | ||||
8777 | } | ||||
8778 | assert(UserDeclaredMove)((UserDeclaredMove) ? static_cast<void> (0) : __assert_fail ("UserDeclaredMove", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 8778, __PRETTY_FUNCTION__)); | ||||
8779 | } else if (RD->hasUserDeclaredMoveAssignment() && | ||||
8780 | (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { | ||||
8781 | if (!Diagnose) return true; | ||||
8782 | |||||
8783 | // Find any user-declared move assignment operator. | ||||
8784 | for (auto *I : RD->methods()) { | ||||
8785 | if (I->isMoveAssignmentOperator()) { | ||||
8786 | UserDeclaredMove = I; | ||||
8787 | break; | ||||
8788 | } | ||||
8789 | } | ||||
8790 | assert(UserDeclaredMove)((UserDeclaredMove) ? static_cast<void> (0) : __assert_fail ("UserDeclaredMove", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 8790, __PRETTY_FUNCTION__)); | ||||
8791 | } | ||||
8792 | |||||
8793 | if (UserDeclaredMove) { | ||||
8794 | Diag(UserDeclaredMove->getLocation(), | ||||
8795 | diag::note_deleted_copy_user_declared_move) | ||||
8796 | << (CSM == CXXCopyAssignment) << RD | ||||
8797 | << UserDeclaredMove->isMoveAssignmentOperator(); | ||||
8798 | return true; | ||||
8799 | } | ||||
8800 | } | ||||
8801 | |||||
8802 | // Do access control from the special member function | ||||
8803 | ContextRAII MethodContext(*this, MD); | ||||
8804 | |||||
8805 | // C++11 [class.dtor]p5: | ||||
8806 | // -- for a virtual destructor, lookup of the non-array deallocation function | ||||
8807 | // results in an ambiguity or in a function that is deleted or inaccessible | ||||
8808 | if (CSM == CXXDestructor && MD->isVirtual()) { | ||||
8809 | FunctionDecl *OperatorDelete = nullptr; | ||||
8810 | DeclarationName Name = | ||||
8811 | Context.DeclarationNames.getCXXOperatorName(OO_Delete); | ||||
8812 | if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, | ||||
8813 | OperatorDelete, /*Diagnose*/false)) { | ||||
8814 | if (Diagnose) | ||||
8815 | Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); | ||||
8816 | return true; | ||||
8817 | } | ||||
8818 | } | ||||
8819 | |||||
8820 | SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); | ||||
8821 | |||||
8822 | // Per DR1611, do not consider virtual bases of constructors of abstract | ||||
8823 | // classes, since we are not going to construct them. | ||||
8824 | // Per DR1658, do not consider virtual bases of destructors of abstract | ||||
8825 | // classes either. | ||||
8826 | // Per DR2180, for assignment operators we only assign (and thus only | ||||
8827 | // consider) direct bases. | ||||
8828 | if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases | ||||
8829 | : SMI.VisitPotentiallyConstructedBases)) | ||||
8830 | return true; | ||||
8831 | |||||
8832 | if (SMI.shouldDeleteForAllConstMembers()) | ||||
8833 | return true; | ||||
8834 | |||||
8835 | if (getLangOpts().CUDA) { | ||||
8836 | // We should delete the special member in CUDA mode if target inference | ||||
8837 | // failed. | ||||
8838 | // For inherited constructors (non-null ICI), CSM may be passed so that MD | ||||
8839 | // is treated as certain special member, which may not reflect what special | ||||
8840 | // member MD really is. However inferCUDATargetForImplicitSpecialMember | ||||
8841 | // expects CSM to match MD, therefore recalculate CSM. | ||||
8842 | assert(ICI || CSM == getSpecialMember(MD))((ICI || CSM == getSpecialMember(MD)) ? static_cast<void> (0) : __assert_fail ("ICI || CSM == getSpecialMember(MD)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 8842, __PRETTY_FUNCTION__)); | ||||
8843 | auto RealCSM = CSM; | ||||
8844 | if (ICI) | ||||
8845 | RealCSM = getSpecialMember(MD); | ||||
8846 | |||||
8847 | return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, | ||||
8848 | SMI.ConstArg, Diagnose); | ||||
8849 | } | ||||
8850 | |||||
8851 | return false; | ||||
8852 | } | ||||
8853 | |||||
8854 | void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { | ||||
8855 | DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); | ||||
8856 | assert(DFK && "not a defaultable function")((DFK && "not a defaultable function") ? static_cast< void> (0) : __assert_fail ("DFK && \"not a defaultable function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 8856, __PRETTY_FUNCTION__)); | ||||
8857 | assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted")((FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted") ? static_cast<void> (0) : __assert_fail ("FD->isDefaulted() && FD->isDeleted() && \"not defaulted and deleted\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 8857, __PRETTY_FUNCTION__)); | ||||
8858 | |||||
8859 | if (DFK.isSpecialMember()) { | ||||
8860 | ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), | ||||
8861 | nullptr, /*Diagnose=*/true); | ||||
8862 | } else { | ||||
8863 | DefaultedComparisonAnalyzer( | ||||
8864 | *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, | ||||
8865 | DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) | ||||
8866 | .visit(); | ||||
8867 | } | ||||
8868 | } | ||||
8869 | |||||
8870 | /// Perform lookup for a special member of the specified kind, and determine | ||||
8871 | /// whether it is trivial. If the triviality can be determined without the | ||||
8872 | /// lookup, skip it. This is intended for use when determining whether a | ||||
8873 | /// special member of a containing object is trivial, and thus does not ever | ||||
8874 | /// perform overload resolution for default constructors. | ||||
8875 | /// | ||||
8876 | /// If \p Selected is not \c NULL, \c *Selected will be filled in with the | ||||
8877 | /// member that was most likely to be intended to be trivial, if any. | ||||
8878 | /// | ||||
8879 | /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to | ||||
8880 | /// determine whether the special member is trivial. | ||||
8881 | static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, | ||||
8882 | Sema::CXXSpecialMember CSM, unsigned Quals, | ||||
8883 | bool ConstRHS, | ||||
8884 | Sema::TrivialABIHandling TAH, | ||||
8885 | CXXMethodDecl **Selected) { | ||||
8886 | if (Selected) | ||||
8887 | *Selected = nullptr; | ||||
8888 | |||||
8889 | switch (CSM) { | ||||
8890 | case Sema::CXXInvalid: | ||||
8891 | llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 8891); | ||||
8892 | |||||
8893 | case Sema::CXXDefaultConstructor: | ||||
8894 | // C++11 [class.ctor]p5: | ||||
8895 | // A default constructor is trivial if: | ||||
8896 | // - all the [direct subobjects] have trivial default constructors | ||||
8897 | // | ||||
8898 | // Note, no overload resolution is performed in this case. | ||||
8899 | if (RD->hasTrivialDefaultConstructor()) | ||||
8900 | return true; | ||||
8901 | |||||
8902 | if (Selected) { | ||||
8903 | // If there's a default constructor which could have been trivial, dig it | ||||
8904 | // out. Otherwise, if there's any user-provided default constructor, point | ||||
8905 | // to that as an example of why there's not a trivial one. | ||||
8906 | CXXConstructorDecl *DefCtor = nullptr; | ||||
8907 | if (RD->needsImplicitDefaultConstructor()) | ||||
8908 | S.DeclareImplicitDefaultConstructor(RD); | ||||
8909 | for (auto *CI : RD->ctors()) { | ||||
8910 | if (!CI->isDefaultConstructor()) | ||||
8911 | continue; | ||||
8912 | DefCtor = CI; | ||||
8913 | if (!DefCtor->isUserProvided()) | ||||
8914 | break; | ||||
8915 | } | ||||
8916 | |||||
8917 | *Selected = DefCtor; | ||||
8918 | } | ||||
8919 | |||||
8920 | return false; | ||||
8921 | |||||
8922 | case Sema::CXXDestructor: | ||||
8923 | // C++11 [class.dtor]p5: | ||||
8924 | // A destructor is trivial if: | ||||
8925 | // - all the direct [subobjects] have trivial destructors | ||||
8926 | if (RD->hasTrivialDestructor() || | ||||
8927 | (TAH == Sema::TAH_ConsiderTrivialABI && | ||||
8928 | RD->hasTrivialDestructorForCall())) | ||||
8929 | return true; | ||||
8930 | |||||
8931 | if (Selected) { | ||||
8932 | if (RD->needsImplicitDestructor()) | ||||
8933 | S.DeclareImplicitDestructor(RD); | ||||
8934 | *Selected = RD->getDestructor(); | ||||
8935 | } | ||||
8936 | |||||
8937 | return false; | ||||
8938 | |||||
8939 | case Sema::CXXCopyConstructor: | ||||
8940 | // C++11 [class.copy]p12: | ||||
8941 | // A copy constructor is trivial if: | ||||
8942 | // - the constructor selected to copy each direct [subobject] is trivial | ||||
8943 | if (RD->hasTrivialCopyConstructor() || | ||||
8944 | (TAH == Sema::TAH_ConsiderTrivialABI && | ||||
8945 | RD->hasTrivialCopyConstructorForCall())) { | ||||
8946 | if (Quals == Qualifiers::Const) | ||||
8947 | // We must either select the trivial copy constructor or reach an | ||||
8948 | // ambiguity; no need to actually perform overload resolution. | ||||
8949 | return true; | ||||
8950 | } else if (!Selected) { | ||||
8951 | return false; | ||||
8952 | } | ||||
8953 | // In C++98, we are not supposed to perform overload resolution here, but we | ||||
8954 | // treat that as a language defect, as suggested on cxx-abi-dev, to treat | ||||
8955 | // cases like B as having a non-trivial copy constructor: | ||||
8956 | // struct A { template<typename T> A(T&); }; | ||||
8957 | // struct B { mutable A a; }; | ||||
8958 | goto NeedOverloadResolution; | ||||
8959 | |||||
8960 | case Sema::CXXCopyAssignment: | ||||
8961 | // C++11 [class.copy]p25: | ||||
8962 | // A copy assignment operator is trivial if: | ||||
8963 | // - the assignment operator selected to copy each direct [subobject] is | ||||
8964 | // trivial | ||||
8965 | if (RD->hasTrivialCopyAssignment()) { | ||||
8966 | if (Quals == Qualifiers::Const) | ||||
8967 | return true; | ||||
8968 | } else if (!Selected) { | ||||
8969 | return false; | ||||
8970 | } | ||||
8971 | // In C++98, we are not supposed to perform overload resolution here, but we | ||||
8972 | // treat that as a language defect. | ||||
8973 | goto NeedOverloadResolution; | ||||
8974 | |||||
8975 | case Sema::CXXMoveConstructor: | ||||
8976 | case Sema::CXXMoveAssignment: | ||||
8977 | NeedOverloadResolution: | ||||
8978 | Sema::SpecialMemberOverloadResult SMOR = | ||||
8979 | lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); | ||||
8980 | |||||
8981 | // The standard doesn't describe how to behave if the lookup is ambiguous. | ||||
8982 | // We treat it as not making the member non-trivial, just like the standard | ||||
8983 | // mandates for the default constructor. This should rarely matter, because | ||||
8984 | // the member will also be deleted. | ||||
8985 | if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) | ||||
8986 | return true; | ||||
8987 | |||||
8988 | if (!SMOR.getMethod()) { | ||||
8989 | assert(SMOR.getKind() ==((SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted ) ? static_cast<void> (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 8990, __PRETTY_FUNCTION__)) | ||||
8990 | Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)((SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted ) ? static_cast<void> (0) : __assert_fail ("SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 8990, __PRETTY_FUNCTION__)); | ||||
8991 | return false; | ||||
8992 | } | ||||
8993 | |||||
8994 | // We deliberately don't check if we found a deleted special member. We're | ||||
8995 | // not supposed to! | ||||
8996 | if (Selected) | ||||
8997 | *Selected = SMOR.getMethod(); | ||||
8998 | |||||
8999 | if (TAH == Sema::TAH_ConsiderTrivialABI && | ||||
9000 | (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) | ||||
9001 | return SMOR.getMethod()->isTrivialForCall(); | ||||
9002 | return SMOR.getMethod()->isTrivial(); | ||||
9003 | } | ||||
9004 | |||||
9005 | llvm_unreachable("unknown special method kind")::llvm::llvm_unreachable_internal("unknown special method kind" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 9005); | ||||
9006 | } | ||||
9007 | |||||
9008 | static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { | ||||
9009 | for (auto *CI : RD->ctors()) | ||||
9010 | if (!CI->isImplicit()) | ||||
9011 | return CI; | ||||
9012 | |||||
9013 | // Look for constructor templates. | ||||
9014 | typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; | ||||
9015 | for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { | ||||
9016 | if (CXXConstructorDecl *CD = | ||||
9017 | dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) | ||||
9018 | return CD; | ||||
9019 | } | ||||
9020 | |||||
9021 | return nullptr; | ||||
9022 | } | ||||
9023 | |||||
9024 | /// The kind of subobject we are checking for triviality. The values of this | ||||
9025 | /// enumeration are used in diagnostics. | ||||
9026 | enum TrivialSubobjectKind { | ||||
9027 | /// The subobject is a base class. | ||||
9028 | TSK_BaseClass, | ||||
9029 | /// The subobject is a non-static data member. | ||||
9030 | TSK_Field, | ||||
9031 | /// The object is actually the complete object. | ||||
9032 | TSK_CompleteObject | ||||
9033 | }; | ||||
9034 | |||||
9035 | /// Check whether the special member selected for a given type would be trivial. | ||||
9036 | static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, | ||||
9037 | QualType SubType, bool ConstRHS, | ||||
9038 | Sema::CXXSpecialMember CSM, | ||||
9039 | TrivialSubobjectKind Kind, | ||||
9040 | Sema::TrivialABIHandling TAH, bool Diagnose) { | ||||
9041 | CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); | ||||
9042 | if (!SubRD) | ||||
9043 | return true; | ||||
9044 | |||||
9045 | CXXMethodDecl *Selected; | ||||
9046 | if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), | ||||
9047 | ConstRHS, TAH, Diagnose ? &Selected : nullptr)) | ||||
9048 | return true; | ||||
9049 | |||||
9050 | if (Diagnose) { | ||||
9051 | if (ConstRHS) | ||||
9052 | SubType.addConst(); | ||||
9053 | |||||
9054 | if (!Selected && CSM == Sema::CXXDefaultConstructor) { | ||||
9055 | S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) | ||||
9056 | << Kind << SubType.getUnqualifiedType(); | ||||
9057 | if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) | ||||
9058 | S.Diag(CD->getLocation(), diag::note_user_declared_ctor); | ||||
9059 | } else if (!Selected) | ||||
9060 | S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) | ||||
9061 | << Kind << SubType.getUnqualifiedType() << CSM << SubType; | ||||
9062 | else if (Selected->isUserProvided()) { | ||||
9063 | if (Kind == TSK_CompleteObject) | ||||
9064 | S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) | ||||
9065 | << Kind << SubType.getUnqualifiedType() << CSM; | ||||
9066 | else { | ||||
9067 | S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) | ||||
9068 | << Kind << SubType.getUnqualifiedType() << CSM; | ||||
9069 | S.Diag(Selected->getLocation(), diag::note_declared_at); | ||||
9070 | } | ||||
9071 | } else { | ||||
9072 | if (Kind != TSK_CompleteObject) | ||||
9073 | S.Diag(SubobjLoc, diag::note_nontrivial_subobject) | ||||
9074 | << Kind << SubType.getUnqualifiedType() << CSM; | ||||
9075 | |||||
9076 | // Explain why the defaulted or deleted special member isn't trivial. | ||||
9077 | S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, | ||||
9078 | Diagnose); | ||||
9079 | } | ||||
9080 | } | ||||
9081 | |||||
9082 | return false; | ||||
9083 | } | ||||
9084 | |||||
9085 | /// Check whether the members of a class type allow a special member to be | ||||
9086 | /// trivial. | ||||
9087 | static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, | ||||
9088 | Sema::CXXSpecialMember CSM, | ||||
9089 | bool ConstArg, | ||||
9090 | Sema::TrivialABIHandling TAH, | ||||
9091 | bool Diagnose) { | ||||
9092 | for (const auto *FI : RD->fields()) { | ||||
9093 | if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) | ||||
9094 | continue; | ||||
9095 | |||||
9096 | QualType FieldType = S.Context.getBaseElementType(FI->getType()); | ||||
9097 | |||||
9098 | // Pretend anonymous struct or union members are members of this class. | ||||
9099 | if (FI->isAnonymousStructOrUnion()) { | ||||
9100 | if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), | ||||
9101 | CSM, ConstArg, TAH, Diagnose)) | ||||
9102 | return false; | ||||
9103 | continue; | ||||
9104 | } | ||||
9105 | |||||
9106 | // C++11 [class.ctor]p5: | ||||
9107 | // A default constructor is trivial if [...] | ||||
9108 | // -- no non-static data member of its class has a | ||||
9109 | // brace-or-equal-initializer | ||||
9110 | if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { | ||||
9111 | if (Diagnose) | ||||
9112 | S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; | ||||
9113 | return false; | ||||
9114 | } | ||||
9115 | |||||
9116 | // Objective C ARC 4.3.5: | ||||
9117 | // [...] nontrivally ownership-qualified types are [...] not trivially | ||||
9118 | // default constructible, copy constructible, move constructible, copy | ||||
9119 | // assignable, move assignable, or destructible [...] | ||||
9120 | if (FieldType.hasNonTrivialObjCLifetime()) { | ||||
9121 | if (Diagnose) | ||||
9122 | S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) | ||||
9123 | << RD << FieldType.getObjCLifetime(); | ||||
9124 | return false; | ||||
9125 | } | ||||
9126 | |||||
9127 | bool ConstRHS = ConstArg && !FI->isMutable(); | ||||
9128 | if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, | ||||
9129 | CSM, TSK_Field, TAH, Diagnose)) | ||||
9130 | return false; | ||||
9131 | } | ||||
9132 | |||||
9133 | return true; | ||||
9134 | } | ||||
9135 | |||||
9136 | /// Diagnose why the specified class does not have a trivial special member of | ||||
9137 | /// the given kind. | ||||
9138 | void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { | ||||
9139 | QualType Ty = Context.getRecordType(RD); | ||||
9140 | |||||
9141 | bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); | ||||
9142 | checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, | ||||
9143 | TSK_CompleteObject, TAH_IgnoreTrivialABI, | ||||
9144 | /*Diagnose*/true); | ||||
9145 | } | ||||
9146 | |||||
9147 | /// Determine whether a defaulted or deleted special member function is trivial, | ||||
9148 | /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, | ||||
9149 | /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. | ||||
9150 | bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, | ||||
9151 | TrivialABIHandling TAH, bool Diagnose) { | ||||
9152 | assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough")((!MD->isUserProvided() && CSM != CXXInvalid && "not special enough") ? static_cast<void> (0) : __assert_fail ("!MD->isUserProvided() && CSM != CXXInvalid && \"not special enough\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 9152, __PRETTY_FUNCTION__)); | ||||
9153 | |||||
9154 | CXXRecordDecl *RD = MD->getParent(); | ||||
9155 | |||||
9156 | bool ConstArg = false; | ||||
9157 | |||||
9158 | // C++11 [class.copy]p12, p25: [DR1593] | ||||
9159 | // A [special member] is trivial if [...] its parameter-type-list is | ||||
9160 | // equivalent to the parameter-type-list of an implicit declaration [...] | ||||
9161 | switch (CSM) { | ||||
9162 | case CXXDefaultConstructor: | ||||
9163 | case CXXDestructor: | ||||
9164 | // Trivial default constructors and destructors cannot have parameters. | ||||
9165 | break; | ||||
9166 | |||||
9167 | case CXXCopyConstructor: | ||||
9168 | case CXXCopyAssignment: { | ||||
9169 | // Trivial copy operations always have const, non-volatile parameter types. | ||||
9170 | ConstArg = true; | ||||
9171 | const ParmVarDecl *Param0 = MD->getParamDecl(0); | ||||
9172 | const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); | ||||
9173 | if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { | ||||
9174 | if (Diagnose) | ||||
9175 | Diag(Param0->getLocation(), diag::note_nontrivial_param_type) | ||||
9176 | << Param0->getSourceRange() << Param0->getType() | ||||
9177 | << Context.getLValueReferenceType( | ||||
9178 | Context.getRecordType(RD).withConst()); | ||||
9179 | return false; | ||||
9180 | } | ||||
9181 | break; | ||||
9182 | } | ||||
9183 | |||||
9184 | case CXXMoveConstructor: | ||||
9185 | case CXXMoveAssignment: { | ||||
9186 | // Trivial move operations always have non-cv-qualified parameters. | ||||
9187 | const ParmVarDecl *Param0 = MD->getParamDecl(0); | ||||
9188 | const RValueReferenceType *RT = | ||||
9189 | Param0->getType()->getAs<RValueReferenceType>(); | ||||
9190 | if (!RT || RT->getPointeeType().getCVRQualifiers()) { | ||||
9191 | if (Diagnose) | ||||
9192 | Diag(Param0->getLocation(), diag::note_nontrivial_param_type) | ||||
9193 | << Param0->getSourceRange() << Param0->getType() | ||||
9194 | << Context.getRValueReferenceType(Context.getRecordType(RD)); | ||||
9195 | return false; | ||||
9196 | } | ||||
9197 | break; | ||||
9198 | } | ||||
9199 | |||||
9200 | case CXXInvalid: | ||||
9201 | llvm_unreachable("not a special member")::llvm::llvm_unreachable_internal("not a special member", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 9201); | ||||
9202 | } | ||||
9203 | |||||
9204 | if (MD->getMinRequiredArguments() < MD->getNumParams()) { | ||||
9205 | if (Diagnose) | ||||
9206 | Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), | ||||
9207 | diag::note_nontrivial_default_arg) | ||||
9208 | << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); | ||||
9209 | return false; | ||||
9210 | } | ||||
9211 | if (MD->isVariadic()) { | ||||
9212 | if (Diagnose) | ||||
9213 | Diag(MD->getLocation(), diag::note_nontrivial_variadic); | ||||
9214 | return false; | ||||
9215 | } | ||||
9216 | |||||
9217 | // C++11 [class.ctor]p5, C++11 [class.dtor]p5: | ||||
9218 | // A copy/move [constructor or assignment operator] is trivial if | ||||
9219 | // -- the [member] selected to copy/move each direct base class subobject | ||||
9220 | // is trivial | ||||
9221 | // | ||||
9222 | // C++11 [class.copy]p12, C++11 [class.copy]p25: | ||||
9223 | // A [default constructor or destructor] is trivial if | ||||
9224 | // -- all the direct base classes have trivial [default constructors or | ||||
9225 | // destructors] | ||||
9226 | for (const auto &BI : RD->bases()) | ||||
9227 | if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), | ||||
9228 | ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) | ||||
9229 | return false; | ||||
9230 | |||||
9231 | // C++11 [class.ctor]p5, C++11 [class.dtor]p5: | ||||
9232 | // A copy/move [constructor or assignment operator] for a class X is | ||||
9233 | // trivial if | ||||
9234 | // -- for each non-static data member of X that is of class type (or array | ||||
9235 | // thereof), the constructor selected to copy/move that member is | ||||
9236 | // trivial | ||||
9237 | // | ||||
9238 | // C++11 [class.copy]p12, C++11 [class.copy]p25: | ||||
9239 | // A [default constructor or destructor] is trivial if | ||||
9240 | // -- for all of the non-static data members of its class that are of class | ||||
9241 | // type (or array thereof), each such class has a trivial [default | ||||
9242 | // constructor or destructor] | ||||
9243 | if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) | ||||
9244 | return false; | ||||
9245 | |||||
9246 | // C++11 [class.dtor]p5: | ||||
9247 | // A destructor is trivial if [...] | ||||
9248 | // -- the destructor is not virtual | ||||
9249 | if (CSM == CXXDestructor && MD->isVirtual()) { | ||||
9250 | if (Diagnose) | ||||
9251 | Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; | ||||
9252 | return false; | ||||
9253 | } | ||||
9254 | |||||
9255 | // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: | ||||
9256 | // A [special member] for class X is trivial if [...] | ||||
9257 | // -- class X has no virtual functions and no virtual base classes | ||||
9258 | if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { | ||||
9259 | if (!Diagnose) | ||||
9260 | return false; | ||||
9261 | |||||
9262 | if (RD->getNumVBases()) { | ||||
9263 | // Check for virtual bases. We already know that the corresponding | ||||
9264 | // member in all bases is trivial, so vbases must all be direct. | ||||
9265 | CXXBaseSpecifier &BS = *RD->vbases_begin(); | ||||
9266 | assert(BS.isVirtual())((BS.isVirtual()) ? static_cast<void> (0) : __assert_fail ("BS.isVirtual()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 9266, __PRETTY_FUNCTION__)); | ||||
9267 | Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; | ||||
9268 | return false; | ||||
9269 | } | ||||
9270 | |||||
9271 | // Must have a virtual method. | ||||
9272 | for (const auto *MI : RD->methods()) { | ||||
9273 | if (MI->isVirtual()) { | ||||
9274 | SourceLocation MLoc = MI->getBeginLoc(); | ||||
9275 | Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; | ||||
9276 | return false; | ||||
9277 | } | ||||
9278 | } | ||||
9279 | |||||
9280 | llvm_unreachable("dynamic class with no vbases and no virtual functions")::llvm::llvm_unreachable_internal("dynamic class with no vbases and no virtual functions" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 9280); | ||||
9281 | } | ||||
9282 | |||||
9283 | // Looks like it's trivial! | ||||
9284 | return true; | ||||
9285 | } | ||||
9286 | |||||
9287 | namespace { | ||||
9288 | struct FindHiddenVirtualMethod { | ||||
9289 | Sema *S; | ||||
9290 | CXXMethodDecl *Method; | ||||
9291 | llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; | ||||
9292 | SmallVector<CXXMethodDecl *, 8> OverloadedMethods; | ||||
9293 | |||||
9294 | private: | ||||
9295 | /// Check whether any most overridden method from MD in Methods | ||||
9296 | static bool CheckMostOverridenMethods( | ||||
9297 | const CXXMethodDecl *MD, | ||||
9298 | const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { | ||||
9299 | if (MD->size_overridden_methods() == 0) | ||||
9300 | return Methods.count(MD->getCanonicalDecl()); | ||||
9301 | for (const CXXMethodDecl *O : MD->overridden_methods()) | ||||
9302 | if (CheckMostOverridenMethods(O, Methods)) | ||||
9303 | return true; | ||||
9304 | return false; | ||||
9305 | } | ||||
9306 | |||||
9307 | public: | ||||
9308 | /// Member lookup function that determines whether a given C++ | ||||
9309 | /// method overloads virtual methods in a base class without overriding any, | ||||
9310 | /// to be used with CXXRecordDecl::lookupInBases(). | ||||
9311 | bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { | ||||
9312 | RecordDecl *BaseRecord = | ||||
9313 | Specifier->getType()->castAs<RecordType>()->getDecl(); | ||||
9314 | |||||
9315 | DeclarationName Name = Method->getDeclName(); | ||||
9316 | assert(Name.getNameKind() == DeclarationName::Identifier)((Name.getNameKind() == DeclarationName::Identifier) ? static_cast <void> (0) : __assert_fail ("Name.getNameKind() == DeclarationName::Identifier" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 9316, __PRETTY_FUNCTION__)); | ||||
9317 | |||||
9318 | bool foundSameNameMethod = false; | ||||
9319 | SmallVector<CXXMethodDecl *, 8> overloadedMethods; | ||||
9320 | for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); | ||||
9321 | Path.Decls = Path.Decls.slice(1)) { | ||||
9322 | NamedDecl *D = Path.Decls.front(); | ||||
9323 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { | ||||
9324 | MD = MD->getCanonicalDecl(); | ||||
9325 | foundSameNameMethod = true; | ||||
9326 | // Interested only in hidden virtual methods. | ||||
9327 | if (!MD->isVirtual()) | ||||
9328 | continue; | ||||
9329 | // If the method we are checking overrides a method from its base | ||||
9330 | // don't warn about the other overloaded methods. Clang deviates from | ||||
9331 | // GCC by only diagnosing overloads of inherited virtual functions that | ||||
9332 | // do not override any other virtual functions in the base. GCC's | ||||
9333 | // -Woverloaded-virtual diagnoses any derived function hiding a virtual | ||||
9334 | // function from a base class. These cases may be better served by a | ||||
9335 | // warning (not specific to virtual functions) on call sites when the | ||||
9336 | // call would select a different function from the base class, were it | ||||
9337 | // visible. | ||||
9338 | // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. | ||||
9339 | if (!S->IsOverload(Method, MD, false)) | ||||
9340 | return true; | ||||
9341 | // Collect the overload only if its hidden. | ||||
9342 | if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) | ||||
9343 | overloadedMethods.push_back(MD); | ||||
9344 | } | ||||
9345 | } | ||||
9346 | |||||
9347 | if (foundSameNameMethod) | ||||
9348 | OverloadedMethods.append(overloadedMethods.begin(), | ||||
9349 | overloadedMethods.end()); | ||||
9350 | return foundSameNameMethod; | ||||
9351 | } | ||||
9352 | }; | ||||
9353 | } // end anonymous namespace | ||||
9354 | |||||
9355 | /// Add the most overriden methods from MD to Methods | ||||
9356 | static void AddMostOverridenMethods(const CXXMethodDecl *MD, | ||||
9357 | llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { | ||||
9358 | if (MD->size_overridden_methods() == 0) | ||||
9359 | Methods.insert(MD->getCanonicalDecl()); | ||||
9360 | else | ||||
9361 | for (const CXXMethodDecl *O : MD->overridden_methods()) | ||||
9362 | AddMostOverridenMethods(O, Methods); | ||||
9363 | } | ||||
9364 | |||||
9365 | /// Check if a method overloads virtual methods in a base class without | ||||
9366 | /// overriding any. | ||||
9367 | void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, | ||||
9368 | SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { | ||||
9369 | if (!MD->getDeclName().isIdentifier()) | ||||
9370 | return; | ||||
9371 | |||||
9372 | CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. | ||||
9373 | /*bool RecordPaths=*/false, | ||||
9374 | /*bool DetectVirtual=*/false); | ||||
9375 | FindHiddenVirtualMethod FHVM; | ||||
9376 | FHVM.Method = MD; | ||||
9377 | FHVM.S = this; | ||||
9378 | |||||
9379 | // Keep the base methods that were overridden or introduced in the subclass | ||||
9380 | // by 'using' in a set. A base method not in this set is hidden. | ||||
9381 | CXXRecordDecl *DC = MD->getParent(); | ||||
9382 | DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); | ||||
9383 | for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { | ||||
9384 | NamedDecl *ND = *I; | ||||
9385 | if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) | ||||
9386 | ND = shad->getTargetDecl(); | ||||
9387 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) | ||||
9388 | AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); | ||||
9389 | } | ||||
9390 | |||||
9391 | if (DC->lookupInBases(FHVM, Paths)) | ||||
9392 | OverloadedMethods = FHVM.OverloadedMethods; | ||||
9393 | } | ||||
9394 | |||||
9395 | void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, | ||||
9396 | SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { | ||||
9397 | for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { | ||||
9398 | CXXMethodDecl *overloadedMD = OverloadedMethods[i]; | ||||
9399 | PartialDiagnostic PD = PDiag( | ||||
9400 | diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; | ||||
9401 | HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); | ||||
9402 | Diag(overloadedMD->getLocation(), PD); | ||||
9403 | } | ||||
9404 | } | ||||
9405 | |||||
9406 | /// Diagnose methods which overload virtual methods in a base class | ||||
9407 | /// without overriding any. | ||||
9408 | void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { | ||||
9409 | if (MD->isInvalidDecl()) | ||||
9410 | return; | ||||
9411 | |||||
9412 | if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) | ||||
9413 | return; | ||||
9414 | |||||
9415 | SmallVector<CXXMethodDecl *, 8> OverloadedMethods; | ||||
9416 | FindHiddenVirtualMethods(MD, OverloadedMethods); | ||||
9417 | if (!OverloadedMethods.empty()) { | ||||
9418 | Diag(MD->getLocation(), diag::warn_overloaded_virtual) | ||||
9419 | << MD << (OverloadedMethods.size() > 1); | ||||
9420 | |||||
9421 | NoteHiddenVirtualMethods(MD, OverloadedMethods); | ||||
9422 | } | ||||
9423 | } | ||||
9424 | |||||
9425 | void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { | ||||
9426 | auto PrintDiagAndRemoveAttr = [&]() { | ||||
9427 | // No diagnostics if this is a template instantiation. | ||||
9428 | if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) | ||||
9429 | Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), | ||||
9430 | diag::ext_cannot_use_trivial_abi) << &RD; | ||||
9431 | RD.dropAttr<TrivialABIAttr>(); | ||||
9432 | }; | ||||
9433 | |||||
9434 | // Ill-formed if the struct has virtual functions. | ||||
9435 | if (RD.isPolymorphic()) { | ||||
9436 | PrintDiagAndRemoveAttr(); | ||||
9437 | return; | ||||
9438 | } | ||||
9439 | |||||
9440 | for (const auto &B : RD.bases()) { | ||||
9441 | // Ill-formed if the base class is non-trivial for the purpose of calls or a | ||||
9442 | // virtual base. | ||||
9443 | if ((!B.getType()->isDependentType() && | ||||
9444 | !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || | ||||
9445 | B.isVirtual()) { | ||||
9446 | PrintDiagAndRemoveAttr(); | ||||
9447 | return; | ||||
9448 | } | ||||
9449 | } | ||||
9450 | |||||
9451 | for (const auto *FD : RD.fields()) { | ||||
9452 | // Ill-formed if the field is an ObjectiveC pointer or of a type that is | ||||
9453 | // non-trivial for the purpose of calls. | ||||
9454 | QualType FT = FD->getType(); | ||||
9455 | if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { | ||||
9456 | PrintDiagAndRemoveAttr(); | ||||
9457 | return; | ||||
9458 | } | ||||
9459 | |||||
9460 | if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) | ||||
9461 | if (!RT->isDependentType() && | ||||
9462 | !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { | ||||
9463 | PrintDiagAndRemoveAttr(); | ||||
9464 | return; | ||||
9465 | } | ||||
9466 | } | ||||
9467 | } | ||||
9468 | |||||
9469 | void Sema::ActOnFinishCXXMemberSpecification( | ||||
9470 | Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, | ||||
9471 | SourceLocation RBrac, const ParsedAttributesView &AttrList) { | ||||
9472 | if (!TagDecl) | ||||
9473 | return; | ||||
9474 | |||||
9475 | AdjustDeclIfTemplate(TagDecl); | ||||
9476 | |||||
9477 | for (const ParsedAttr &AL : AttrList) { | ||||
9478 | if (AL.getKind() != ParsedAttr::AT_Visibility) | ||||
9479 | continue; | ||||
9480 | AL.setInvalid(); | ||||
9481 | Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; | ||||
9482 | } | ||||
9483 | |||||
9484 | ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( | ||||
9485 | // strict aliasing violation! | ||||
9486 | reinterpret_cast<Decl**>(FieldCollector->getCurFields()), | ||||
9487 | FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); | ||||
9488 | |||||
9489 | CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); | ||||
9490 | } | ||||
9491 | |||||
9492 | /// Find the equality comparison functions that should be implicitly declared | ||||
9493 | /// in a given class definition, per C++2a [class.compare.default]p3. | ||||
9494 | static void findImplicitlyDeclaredEqualityComparisons( | ||||
9495 | ASTContext &Ctx, CXXRecordDecl *RD, | ||||
9496 | llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { | ||||
9497 | DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); | ||||
9498 | if (!RD->lookup(EqEq).empty()) | ||||
9499 | // Member operator== explicitly declared: no implicit operator==s. | ||||
9500 | return; | ||||
9501 | |||||
9502 | // Traverse friends looking for an '==' or a '<=>'. | ||||
9503 | for (FriendDecl *Friend : RD->friends()) { | ||||
9504 | FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); | ||||
9505 | if (!FD) continue; | ||||
9506 | |||||
9507 | if (FD->getOverloadedOperator() == OO_EqualEqual) { | ||||
9508 | // Friend operator== explicitly declared: no implicit operator==s. | ||||
9509 | Spaceships.clear(); | ||||
9510 | return; | ||||
9511 | } | ||||
9512 | |||||
9513 | if (FD->getOverloadedOperator() == OO_Spaceship && | ||||
9514 | FD->isExplicitlyDefaulted()) | ||||
9515 | Spaceships.push_back(FD); | ||||
9516 | } | ||||
9517 | |||||
9518 | // Look for members named 'operator<=>'. | ||||
9519 | DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); | ||||
9520 | for (NamedDecl *ND : RD->lookup(Cmp)) { | ||||
9521 | // Note that we could find a non-function here (either a function template | ||||
9522 | // or a using-declaration). Neither case results in an implicit | ||||
9523 | // 'operator=='. | ||||
9524 | if (auto *FD = dyn_cast<FunctionDecl>(ND)) | ||||
9525 | if (FD->isExplicitlyDefaulted()) | ||||
9526 | Spaceships.push_back(FD); | ||||
9527 | } | ||||
9528 | } | ||||
9529 | |||||
9530 | /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared | ||||
9531 | /// special functions, such as the default constructor, copy | ||||
9532 | /// constructor, or destructor, to the given C++ class (C++ | ||||
9533 | /// [special]p1). This routine can only be executed just before the | ||||
9534 | /// definition of the class is complete. | ||||
9535 | void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { | ||||
9536 | if (ClassDecl->needsImplicitDefaultConstructor()) { | ||||
9537 | ++getASTContext().NumImplicitDefaultConstructors; | ||||
9538 | |||||
9539 | if (ClassDecl->hasInheritedConstructor()) | ||||
9540 | DeclareImplicitDefaultConstructor(ClassDecl); | ||||
9541 | } | ||||
9542 | |||||
9543 | if (ClassDecl->needsImplicitCopyConstructor()) { | ||||
9544 | ++getASTContext().NumImplicitCopyConstructors; | ||||
9545 | |||||
9546 | // If the properties or semantics of the copy constructor couldn't be | ||||
9547 | // determined while the class was being declared, force a declaration | ||||
9548 | // of it now. | ||||
9549 | if (ClassDecl->needsOverloadResolutionForCopyConstructor() || | ||||
9550 | ClassDecl->hasInheritedConstructor()) | ||||
9551 | DeclareImplicitCopyConstructor(ClassDecl); | ||||
9552 | // For the MS ABI we need to know whether the copy ctor is deleted. A | ||||
9553 | // prerequisite for deleting the implicit copy ctor is that the class has a | ||||
9554 | // move ctor or move assignment that is either user-declared or whose | ||||
9555 | // semantics are inherited from a subobject. FIXME: We should provide a more | ||||
9556 | // direct way for CodeGen to ask whether the constructor was deleted. | ||||
9557 | else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && | ||||
9558 | (ClassDecl->hasUserDeclaredMoveConstructor() || | ||||
9559 | ClassDecl->needsOverloadResolutionForMoveConstructor() || | ||||
9560 | ClassDecl->hasUserDeclaredMoveAssignment() || | ||||
9561 | ClassDecl->needsOverloadResolutionForMoveAssignment())) | ||||
9562 | DeclareImplicitCopyConstructor(ClassDecl); | ||||
9563 | } | ||||
9564 | |||||
9565 | if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { | ||||
9566 | ++getASTContext().NumImplicitMoveConstructors; | ||||
9567 | |||||
9568 | if (ClassDecl->needsOverloadResolutionForMoveConstructor() || | ||||
9569 | ClassDecl->hasInheritedConstructor()) | ||||
9570 | DeclareImplicitMoveConstructor(ClassDecl); | ||||
9571 | } | ||||
9572 | |||||
9573 | if (ClassDecl->needsImplicitCopyAssignment()) { | ||||
9574 | ++getASTContext().NumImplicitCopyAssignmentOperators; | ||||
9575 | |||||
9576 | // If we have a dynamic class, then the copy assignment operator may be | ||||
9577 | // virtual, so we have to declare it immediately. This ensures that, e.g., | ||||
9578 | // it shows up in the right place in the vtable and that we diagnose | ||||
9579 | // problems with the implicit exception specification. | ||||
9580 | if (ClassDecl->isDynamicClass() || | ||||
9581 | ClassDecl->needsOverloadResolutionForCopyAssignment() || | ||||
9582 | ClassDecl->hasInheritedAssignment()) | ||||
9583 | DeclareImplicitCopyAssignment(ClassDecl); | ||||
9584 | } | ||||
9585 | |||||
9586 | if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { | ||||
9587 | ++getASTContext().NumImplicitMoveAssignmentOperators; | ||||
9588 | |||||
9589 | // Likewise for the move assignment operator. | ||||
9590 | if (ClassDecl->isDynamicClass() || | ||||
9591 | ClassDecl->needsOverloadResolutionForMoveAssignment() || | ||||
9592 | ClassDecl->hasInheritedAssignment()) | ||||
9593 | DeclareImplicitMoveAssignment(ClassDecl); | ||||
9594 | } | ||||
9595 | |||||
9596 | if (ClassDecl->needsImplicitDestructor()) { | ||||
9597 | ++getASTContext().NumImplicitDestructors; | ||||
9598 | |||||
9599 | // If we have a dynamic class, then the destructor may be virtual, so we | ||||
9600 | // have to declare the destructor immediately. This ensures that, e.g., it | ||||
9601 | // shows up in the right place in the vtable and that we diagnose problems | ||||
9602 | // with the implicit exception specification. | ||||
9603 | if (ClassDecl->isDynamicClass() || | ||||
9604 | ClassDecl->needsOverloadResolutionForDestructor()) | ||||
9605 | DeclareImplicitDestructor(ClassDecl); | ||||
9606 | } | ||||
9607 | |||||
9608 | // C++2a [class.compare.default]p3: | ||||
9609 | // If the member-specification does not explicitly declare any member or | ||||
9610 | // friend named operator==, an == operator function is declared implicitly | ||||
9611 | // for each defaulted three-way comparison operator function defined in the | ||||
9612 | // member-specification | ||||
9613 | // FIXME: Consider doing this lazily. | ||||
9614 | if (getLangOpts().CPlusPlus2a) { | ||||
9615 | llvm::SmallVector<FunctionDecl*, 4> DefaultedSpaceships; | ||||
9616 | findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, | ||||
9617 | DefaultedSpaceships); | ||||
9618 | for (auto *FD : DefaultedSpaceships) | ||||
9619 | DeclareImplicitEqualityComparison(ClassDecl, FD); | ||||
9620 | } | ||||
9621 | } | ||||
9622 | |||||
9623 | unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { | ||||
9624 | if (!D) | ||||
9625 | return 0; | ||||
9626 | |||||
9627 | // The order of template parameters is not important here. All names | ||||
9628 | // get added to the same scope. | ||||
9629 | SmallVector<TemplateParameterList *, 4> ParameterLists; | ||||
9630 | |||||
9631 | if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) | ||||
9632 | D = TD->getTemplatedDecl(); | ||||
9633 | |||||
9634 | if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) | ||||
9635 | ParameterLists.push_back(PSD->getTemplateParameters()); | ||||
9636 | |||||
9637 | if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { | ||||
9638 | for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) | ||||
9639 | ParameterLists.push_back(DD->getTemplateParameterList(i)); | ||||
9640 | |||||
9641 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||
9642 | if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) | ||||
9643 | ParameterLists.push_back(FTD->getTemplateParameters()); | ||||
9644 | } | ||||
9645 | } | ||||
9646 | |||||
9647 | if (TagDecl *TD = dyn_cast<TagDecl>(D)) { | ||||
9648 | for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) | ||||
9649 | ParameterLists.push_back(TD->getTemplateParameterList(i)); | ||||
9650 | |||||
9651 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { | ||||
9652 | if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) | ||||
9653 | ParameterLists.push_back(CTD->getTemplateParameters()); | ||||
9654 | } | ||||
9655 | } | ||||
9656 | |||||
9657 | unsigned Count = 0; | ||||
9658 | for (TemplateParameterList *Params : ParameterLists) { | ||||
9659 | if (Params->size() > 0) | ||||
9660 | // Ignore explicit specializations; they don't contribute to the template | ||||
9661 | // depth. | ||||
9662 | ++Count; | ||||
9663 | for (NamedDecl *Param : *Params) { | ||||
9664 | if (Param->getDeclName()) { | ||||
9665 | S->AddDecl(Param); | ||||
9666 | IdResolver.AddDecl(Param); | ||||
9667 | } | ||||
9668 | } | ||||
9669 | } | ||||
9670 | |||||
9671 | return Count; | ||||
9672 | } | ||||
9673 | |||||
9674 | void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { | ||||
9675 | if (!RecordD) return; | ||||
9676 | AdjustDeclIfTemplate(RecordD); | ||||
9677 | CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); | ||||
9678 | PushDeclContext(S, Record); | ||||
9679 | } | ||||
9680 | |||||
9681 | void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { | ||||
9682 | if (!RecordD) return; | ||||
9683 | PopDeclContext(); | ||||
9684 | } | ||||
9685 | |||||
9686 | /// This is used to implement the constant expression evaluation part of the | ||||
9687 | /// attribute enable_if extension. There is nothing in standard C++ which would | ||||
9688 | /// require reentering parameters. | ||||
9689 | void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { | ||||
9690 | if (!Param) | ||||
9691 | return; | ||||
9692 | |||||
9693 | S->AddDecl(Param); | ||||
9694 | if (Param->getDeclName()) | ||||
9695 | IdResolver.AddDecl(Param); | ||||
9696 | } | ||||
9697 | |||||
9698 | /// ActOnStartDelayedCXXMethodDeclaration - We have completed | ||||
9699 | /// parsing a top-level (non-nested) C++ class, and we are now | ||||
9700 | /// parsing those parts of the given Method declaration that could | ||||
9701 | /// not be parsed earlier (C++ [class.mem]p2), such as default | ||||
9702 | /// arguments. This action should enter the scope of the given | ||||
9703 | /// Method declaration as if we had just parsed the qualified method | ||||
9704 | /// name. However, it should not bring the parameters into scope; | ||||
9705 | /// that will be performed by ActOnDelayedCXXMethodParameter. | ||||
9706 | void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { | ||||
9707 | } | ||||
9708 | |||||
9709 | /// ActOnDelayedCXXMethodParameter - We've already started a delayed | ||||
9710 | /// C++ method declaration. We're (re-)introducing the given | ||||
9711 | /// function parameter into scope for use in parsing later parts of | ||||
9712 | /// the method declaration. For example, we could see an | ||||
9713 | /// ActOnParamDefaultArgument event for this parameter. | ||||
9714 | void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { | ||||
9715 | if (!ParamD) | ||||
9716 | return; | ||||
9717 | |||||
9718 | ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); | ||||
9719 | |||||
9720 | // If this parameter has an unparsed default argument, clear it out | ||||
9721 | // to make way for the parsed default argument. | ||||
9722 | if (Param->hasUnparsedDefaultArg()) | ||||
9723 | Param->setDefaultArg(nullptr); | ||||
9724 | |||||
9725 | S->AddDecl(Param); | ||||
9726 | if (Param->getDeclName()) | ||||
9727 | IdResolver.AddDecl(Param); | ||||
9728 | } | ||||
9729 | |||||
9730 | /// ActOnFinishDelayedCXXMethodDeclaration - We have finished | ||||
9731 | /// processing the delayed method declaration for Method. The method | ||||
9732 | /// declaration is now considered finished. There may be a separate | ||||
9733 | /// ActOnStartOfFunctionDef action later (not necessarily | ||||
9734 | /// immediately!) for this method, if it was also defined inside the | ||||
9735 | /// class body. | ||||
9736 | void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { | ||||
9737 | if (!MethodD) | ||||
9738 | return; | ||||
9739 | |||||
9740 | AdjustDeclIfTemplate(MethodD); | ||||
9741 | |||||
9742 | FunctionDecl *Method = cast<FunctionDecl>(MethodD); | ||||
9743 | |||||
9744 | // Now that we have our default arguments, check the constructor | ||||
9745 | // again. It could produce additional diagnostics or affect whether | ||||
9746 | // the class has implicitly-declared destructors, among other | ||||
9747 | // things. | ||||
9748 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) | ||||
9749 | CheckConstructor(Constructor); | ||||
9750 | |||||
9751 | // Check the default arguments, which we may have added. | ||||
9752 | if (!Method->isInvalidDecl()) | ||||
9753 | CheckCXXDefaultArguments(Method); | ||||
9754 | } | ||||
9755 | |||||
9756 | // Emit the given diagnostic for each non-address-space qualifier. | ||||
9757 | // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. | ||||
9758 | static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { | ||||
9759 | const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | ||||
9760 | if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { | ||||
9761 | bool DiagOccured = false; | ||||
9762 | FTI.MethodQualifiers->forEachQualifier( | ||||
9763 | [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, | ||||
9764 | SourceLocation SL) { | ||||
9765 | // This diagnostic should be emitted on any qualifier except an addr | ||||
9766 | // space qualifier. However, forEachQualifier currently doesn't visit | ||||
9767 | // addr space qualifiers, so there's no way to write this condition | ||||
9768 | // right now; we just diagnose on everything. | ||||
9769 | S.Diag(SL, DiagID) << QualName << SourceRange(SL); | ||||
9770 | DiagOccured = true; | ||||
9771 | }); | ||||
9772 | if (DiagOccured) | ||||
9773 | D.setInvalidType(); | ||||
9774 | } | ||||
9775 | } | ||||
9776 | |||||
9777 | /// CheckConstructorDeclarator - Called by ActOnDeclarator to check | ||||
9778 | /// the well-formedness of the constructor declarator @p D with type @p | ||||
9779 | /// R. If there are any errors in the declarator, this routine will | ||||
9780 | /// emit diagnostics and set the invalid bit to true. In any case, the type | ||||
9781 | /// will be updated to reflect a well-formed type for the constructor and | ||||
9782 | /// returned. | ||||
9783 | QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, | ||||
9784 | StorageClass &SC) { | ||||
9785 | bool isVirtual = D.getDeclSpec().isVirtualSpecified(); | ||||
9786 | |||||
9787 | // C++ [class.ctor]p3: | ||||
9788 | // A constructor shall not be virtual (10.3) or static (9.4). A | ||||
9789 | // constructor can be invoked for a const, volatile or const | ||||
9790 | // volatile object. A constructor shall not be declared const, | ||||
9791 | // volatile, or const volatile (9.3.2). | ||||
9792 | if (isVirtual) { | ||||
9793 | if (!D.isInvalidType()) | ||||
9794 | Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) | ||||
9795 | << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) | ||||
9796 | << SourceRange(D.getIdentifierLoc()); | ||||
9797 | D.setInvalidType(); | ||||
9798 | } | ||||
9799 | if (SC == SC_Static) { | ||||
9800 | if (!D.isInvalidType()) | ||||
9801 | Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) | ||||
9802 | << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) | ||||
9803 | << SourceRange(D.getIdentifierLoc()); | ||||
9804 | D.setInvalidType(); | ||||
9805 | SC = SC_None; | ||||
9806 | } | ||||
9807 | |||||
9808 | if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { | ||||
9809 | diagnoseIgnoredQualifiers( | ||||
9810 | diag::err_constructor_return_type, TypeQuals, SourceLocation(), | ||||
9811 | D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), | ||||
9812 | D.getDeclSpec().getRestrictSpecLoc(), | ||||
9813 | D.getDeclSpec().getAtomicSpecLoc()); | ||||
9814 | D.setInvalidType(); | ||||
9815 | } | ||||
9816 | |||||
9817 | checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); | ||||
9818 | |||||
9819 | // C++0x [class.ctor]p4: | ||||
9820 | // A constructor shall not be declared with a ref-qualifier. | ||||
9821 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | ||||
9822 | if (FTI.hasRefQualifier()) { | ||||
9823 | Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) | ||||
9824 | << FTI.RefQualifierIsLValueRef | ||||
9825 | << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); | ||||
9826 | D.setInvalidType(); | ||||
9827 | } | ||||
9828 | |||||
9829 | // Rebuild the function type "R" without any type qualifiers (in | ||||
9830 | // case any of the errors above fired) and with "void" as the | ||||
9831 | // return type, since constructors don't have return types. | ||||
9832 | const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); | ||||
9833 | if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) | ||||
9834 | return R; | ||||
9835 | |||||
9836 | FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); | ||||
9837 | EPI.TypeQuals = Qualifiers(); | ||||
9838 | EPI.RefQualifier = RQ_None; | ||||
9839 | |||||
9840 | return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); | ||||
9841 | } | ||||
9842 | |||||
9843 | /// CheckConstructor - Checks a fully-formed constructor for | ||||
9844 | /// well-formedness, issuing any diagnostics required. Returns true if | ||||
9845 | /// the constructor declarator is invalid. | ||||
9846 | void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { | ||||
9847 | CXXRecordDecl *ClassDecl | ||||
9848 | = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); | ||||
9849 | if (!ClassDecl) | ||||
9850 | return Constructor->setInvalidDecl(); | ||||
9851 | |||||
9852 | // C++ [class.copy]p3: | ||||
9853 | // A declaration of a constructor for a class X is ill-formed if | ||||
9854 | // its first parameter is of type (optionally cv-qualified) X and | ||||
9855 | // either there are no other parameters or else all other | ||||
9856 | // parameters have default arguments. | ||||
9857 | if (!Constructor->isInvalidDecl() && | ||||
9858 | ((Constructor->getNumParams() == 1) || | ||||
9859 | (Constructor->getNumParams() > 1 && | ||||
9860 | Constructor->getParamDecl(1)->hasDefaultArg())) && | ||||
9861 | Constructor->getTemplateSpecializationKind() | ||||
9862 | != TSK_ImplicitInstantiation) { | ||||
9863 | QualType ParamType = Constructor->getParamDecl(0)->getType(); | ||||
9864 | QualType ClassTy = Context.getTagDeclType(ClassDecl); | ||||
9865 | if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { | ||||
9866 | SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); | ||||
9867 | const char *ConstRef | ||||
9868 | = Constructor->getParamDecl(0)->getIdentifier() ? "const &" | ||||
9869 | : " const &"; | ||||
9870 | Diag(ParamLoc, diag::err_constructor_byvalue_arg) | ||||
9871 | << FixItHint::CreateInsertion(ParamLoc, ConstRef); | ||||
9872 | |||||
9873 | // FIXME: Rather that making the constructor invalid, we should endeavor | ||||
9874 | // to fix the type. | ||||
9875 | Constructor->setInvalidDecl(); | ||||
9876 | } | ||||
9877 | } | ||||
9878 | } | ||||
9879 | |||||
9880 | /// CheckDestructor - Checks a fully-formed destructor definition for | ||||
9881 | /// well-formedness, issuing any diagnostics required. Returns true | ||||
9882 | /// on error. | ||||
9883 | bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { | ||||
9884 | CXXRecordDecl *RD = Destructor->getParent(); | ||||
9885 | |||||
9886 | if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { | ||||
9887 | SourceLocation Loc; | ||||
9888 | |||||
9889 | if (!Destructor->isImplicit()) | ||||
9890 | Loc = Destructor->getLocation(); | ||||
9891 | else | ||||
9892 | Loc = RD->getLocation(); | ||||
9893 | |||||
9894 | // If we have a virtual destructor, look up the deallocation function | ||||
9895 | if (FunctionDecl *OperatorDelete = | ||||
9896 | FindDeallocationFunctionForDestructor(Loc, RD)) { | ||||
9897 | Expr *ThisArg = nullptr; | ||||
9898 | |||||
9899 | // If the notional 'delete this' expression requires a non-trivial | ||||
9900 | // conversion from 'this' to the type of a destroying operator delete's | ||||
9901 | // first parameter, perform that conversion now. | ||||
9902 | if (OperatorDelete->isDestroyingOperatorDelete()) { | ||||
9903 | QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); | ||||
9904 | if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { | ||||
9905 | // C++ [class.dtor]p13: | ||||
9906 | // ... as if for the expression 'delete this' appearing in a | ||||
9907 | // non-virtual destructor of the destructor's class. | ||||
9908 | ContextRAII SwitchContext(*this, Destructor); | ||||
9909 | ExprResult This = | ||||
9910 | ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); | ||||
9911 | assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?")((!This.isInvalid() && "couldn't form 'this' expr in dtor?" ) ? static_cast<void> (0) : __assert_fail ("!This.isInvalid() && \"couldn't form 'this' expr in dtor?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 9911, __PRETTY_FUNCTION__)); | ||||
9912 | This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); | ||||
9913 | if (This.isInvalid()) { | ||||
9914 | // FIXME: Register this as a context note so that it comes out | ||||
9915 | // in the right order. | ||||
9916 | Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); | ||||
9917 | return true; | ||||
9918 | } | ||||
9919 | ThisArg = This.get(); | ||||
9920 | } | ||||
9921 | } | ||||
9922 | |||||
9923 | DiagnoseUseOfDecl(OperatorDelete, Loc); | ||||
9924 | MarkFunctionReferenced(Loc, OperatorDelete); | ||||
9925 | Destructor->setOperatorDelete(OperatorDelete, ThisArg); | ||||
9926 | } | ||||
9927 | } | ||||
9928 | |||||
9929 | return false; | ||||
9930 | } | ||||
9931 | |||||
9932 | /// CheckDestructorDeclarator - Called by ActOnDeclarator to check | ||||
9933 | /// the well-formednes of the destructor declarator @p D with type @p | ||||
9934 | /// R. If there are any errors in the declarator, this routine will | ||||
9935 | /// emit diagnostics and set the declarator to invalid. Even if this happens, | ||||
9936 | /// will be updated to reflect a well-formed type for the destructor and | ||||
9937 | /// returned. | ||||
9938 | QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, | ||||
9939 | StorageClass& SC) { | ||||
9940 | // C++ [class.dtor]p1: | ||||
9941 | // [...] A typedef-name that names a class is a class-name | ||||
9942 | // (7.1.3); however, a typedef-name that names a class shall not | ||||
9943 | // be used as the identifier in the declarator for a destructor | ||||
9944 | // declaration. | ||||
9945 | QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); | ||||
9946 | if (const TypedefType *TT
| ||||
| |||||
9947 | Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) | ||||
9948 | << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); | ||||
9949 | else if (const TemplateSpecializationType *TST
| ||||
9950 | DeclaratorType->getAs<TemplateSpecializationType>()) | ||||
9951 | if (TST->isTypeAlias()) | ||||
9952 | Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) | ||||
9953 | << DeclaratorType << 1; | ||||
9954 | |||||
9955 | // C++ [class.dtor]p2: | ||||
9956 | // A destructor is used to destroy objects of its class type. A | ||||
9957 | // destructor takes no parameters, and no return type can be | ||||
9958 | // specified for it (not even void). The address of a destructor | ||||
9959 | // shall not be taken. A destructor shall not be static. A | ||||
9960 | // destructor can be invoked for a const, volatile or const | ||||
9961 | // volatile object. A destructor shall not be declared const, | ||||
9962 | // volatile or const volatile (9.3.2). | ||||
9963 | if (SC == SC_Static) { | ||||
9964 | if (!D.isInvalidType()) | ||||
9965 | Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) | ||||
9966 | << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) | ||||
9967 | << SourceRange(D.getIdentifierLoc()) | ||||
9968 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||
9969 | |||||
9970 | SC = SC_None; | ||||
9971 | } | ||||
9972 | if (!D.isInvalidType()) { | ||||
9973 | // Destructors don't have return types, but the parser will | ||||
9974 | // happily parse something like: | ||||
9975 | // | ||||
9976 | // class X { | ||||
9977 | // float ~X(); | ||||
9978 | // }; | ||||
9979 | // | ||||
9980 | // The return type will be eliminated later. | ||||
9981 | if (D.getDeclSpec().hasTypeSpecifier()) | ||||
9982 | Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) | ||||
9983 | << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) | ||||
9984 | << SourceRange(D.getIdentifierLoc()); | ||||
9985 | else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { | ||||
9986 | diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, | ||||
9987 | SourceLocation(), | ||||
9988 | D.getDeclSpec().getConstSpecLoc(), | ||||
9989 | D.getDeclSpec().getVolatileSpecLoc(), | ||||
9990 | D.getDeclSpec().getRestrictSpecLoc(), | ||||
9991 | D.getDeclSpec().getAtomicSpecLoc()); | ||||
9992 | D.setInvalidType(); | ||||
9993 | } | ||||
9994 | } | ||||
9995 | |||||
9996 | checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); | ||||
9997 | |||||
9998 | // C++0x [class.dtor]p2: | ||||
9999 | // A destructor shall not be declared with a ref-qualifier. | ||||
10000 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | ||||
10001 | if (FTI.hasRefQualifier()) { | ||||
10002 | Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) | ||||
10003 | << FTI.RefQualifierIsLValueRef | ||||
10004 | << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); | ||||
10005 | D.setInvalidType(); | ||||
10006 | } | ||||
10007 | |||||
10008 | // Make sure we don't have any parameters. | ||||
10009 | if (FTIHasNonVoidParameters(FTI)) { | ||||
10010 | Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); | ||||
10011 | |||||
10012 | // Delete the parameters. | ||||
10013 | FTI.freeParams(); | ||||
10014 | D.setInvalidType(); | ||||
10015 | } | ||||
10016 | |||||
10017 | // Make sure the destructor isn't variadic. | ||||
10018 | if (FTI.isVariadic) { | ||||
10019 | Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); | ||||
10020 | D.setInvalidType(); | ||||
10021 | } | ||||
10022 | |||||
10023 | // Rebuild the function type "R" without any type qualifiers or | ||||
10024 | // parameters (in case any of the errors above fired) and with | ||||
10025 | // "void" as the return type, since destructors don't have return | ||||
10026 | // types. | ||||
10027 | if (!D.isInvalidType()) | ||||
10028 | return R; | ||||
10029 | |||||
10030 | const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); | ||||
10031 | FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); | ||||
| |||||
10032 | EPI.Variadic = false; | ||||
10033 | EPI.TypeQuals = Qualifiers(); | ||||
10034 | EPI.RefQualifier = RQ_None; | ||||
10035 | return Context.getFunctionType(Context.VoidTy, None, EPI); | ||||
10036 | } | ||||
10037 | |||||
10038 | static void extendLeft(SourceRange &R, SourceRange Before) { | ||||
10039 | if (Before.isInvalid()) | ||||
10040 | return; | ||||
10041 | R.setBegin(Before.getBegin()); | ||||
10042 | if (R.getEnd().isInvalid()) | ||||
10043 | R.setEnd(Before.getEnd()); | ||||
10044 | } | ||||
10045 | |||||
10046 | static void extendRight(SourceRange &R, SourceRange After) { | ||||
10047 | if (After.isInvalid()) | ||||
10048 | return; | ||||
10049 | if (R.getBegin().isInvalid()) | ||||
10050 | R.setBegin(After.getBegin()); | ||||
10051 | R.setEnd(After.getEnd()); | ||||
10052 | } | ||||
10053 | |||||
10054 | /// CheckConversionDeclarator - Called by ActOnDeclarator to check the | ||||
10055 | /// well-formednes of the conversion function declarator @p D with | ||||
10056 | /// type @p R. If there are any errors in the declarator, this routine | ||||
10057 | /// will emit diagnostics and return true. Otherwise, it will return | ||||
10058 | /// false. Either way, the type @p R will be updated to reflect a | ||||
10059 | /// well-formed type for the conversion operator. | ||||
10060 | void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, | ||||
10061 | StorageClass& SC) { | ||||
10062 | // C++ [class.conv.fct]p1: | ||||
10063 | // Neither parameter types nor return type can be specified. The | ||||
10064 | // type of a conversion function (8.3.5) is "function taking no | ||||
10065 | // parameter returning conversion-type-id." | ||||
10066 | if (SC == SC_Static) { | ||||
10067 | if (!D.isInvalidType()) | ||||
10068 | Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) | ||||
10069 | << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) | ||||
10070 | << D.getName().getSourceRange(); | ||||
10071 | D.setInvalidType(); | ||||
10072 | SC = SC_None; | ||||
10073 | } | ||||
10074 | |||||
10075 | TypeSourceInfo *ConvTSI = nullptr; | ||||
10076 | QualType ConvType = | ||||
10077 | GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); | ||||
10078 | |||||
10079 | const DeclSpec &DS = D.getDeclSpec(); | ||||
10080 | if (DS.hasTypeSpecifier() && !D.isInvalidType()) { | ||||
10081 | // Conversion functions don't have return types, but the parser will | ||||
10082 | // happily parse something like: | ||||
10083 | // | ||||
10084 | // class X { | ||||
10085 | // float operator bool(); | ||||
10086 | // }; | ||||
10087 | // | ||||
10088 | // The return type will be changed later anyway. | ||||
10089 | Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) | ||||
10090 | << SourceRange(DS.getTypeSpecTypeLoc()) | ||||
10091 | << SourceRange(D.getIdentifierLoc()); | ||||
10092 | D.setInvalidType(); | ||||
10093 | } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { | ||||
10094 | // It's also plausible that the user writes type qualifiers in the wrong | ||||
10095 | // place, such as: | ||||
10096 | // struct S { const operator int(); }; | ||||
10097 | // FIXME: we could provide a fixit to move the qualifiers onto the | ||||
10098 | // conversion type. | ||||
10099 | Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) | ||||
10100 | << SourceRange(D.getIdentifierLoc()) << 0; | ||||
10101 | D.setInvalidType(); | ||||
10102 | } | ||||
10103 | |||||
10104 | const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); | ||||
10105 | |||||
10106 | // Make sure we don't have any parameters. | ||||
10107 | if (Proto->getNumParams() > 0) { | ||||
10108 | Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); | ||||
10109 | |||||
10110 | // Delete the parameters. | ||||
10111 | D.getFunctionTypeInfo().freeParams(); | ||||
10112 | D.setInvalidType(); | ||||
10113 | } else if (Proto->isVariadic()) { | ||||
10114 | Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); | ||||
10115 | D.setInvalidType(); | ||||
10116 | } | ||||
10117 | |||||
10118 | // Diagnose "&operator bool()" and other such nonsense. This | ||||
10119 | // is actually a gcc extension which we don't support. | ||||
10120 | if (Proto->getReturnType() != ConvType) { | ||||
10121 | bool NeedsTypedef = false; | ||||
10122 | SourceRange Before, After; | ||||
10123 | |||||
10124 | // Walk the chunks and extract information on them for our diagnostic. | ||||
10125 | bool PastFunctionChunk = false; | ||||
10126 | for (auto &Chunk : D.type_objects()) { | ||||
10127 | switch (Chunk.Kind) { | ||||
10128 | case DeclaratorChunk::Function: | ||||
10129 | if (!PastFunctionChunk) { | ||||
10130 | if (Chunk.Fun.HasTrailingReturnType) { | ||||
10131 | TypeSourceInfo *TRT = nullptr; | ||||
10132 | GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); | ||||
10133 | if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); | ||||
10134 | } | ||||
10135 | PastFunctionChunk = true; | ||||
10136 | break; | ||||
10137 | } | ||||
10138 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
10139 | case DeclaratorChunk::Array: | ||||
10140 | NeedsTypedef = true; | ||||
10141 | extendRight(After, Chunk.getSourceRange()); | ||||
10142 | break; | ||||
10143 | |||||
10144 | case DeclaratorChunk::Pointer: | ||||
10145 | case DeclaratorChunk::BlockPointer: | ||||
10146 | case DeclaratorChunk::Reference: | ||||
10147 | case DeclaratorChunk::MemberPointer: | ||||
10148 | case DeclaratorChunk::Pipe: | ||||
10149 | extendLeft(Before, Chunk.getSourceRange()); | ||||
10150 | break; | ||||
10151 | |||||
10152 | case DeclaratorChunk::Paren: | ||||
10153 | extendLeft(Before, Chunk.Loc); | ||||
10154 | extendRight(After, Chunk.EndLoc); | ||||
10155 | break; | ||||
10156 | } | ||||
10157 | } | ||||
10158 | |||||
10159 | SourceLocation Loc = Before.isValid() ? Before.getBegin() : | ||||
10160 | After.isValid() ? After.getBegin() : | ||||
10161 | D.getIdentifierLoc(); | ||||
10162 | auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); | ||||
10163 | DB << Before << After; | ||||
10164 | |||||
10165 | if (!NeedsTypedef) { | ||||
10166 | DB << /*don't need a typedef*/0; | ||||
10167 | |||||
10168 | // If we can provide a correct fix-it hint, do so. | ||||
10169 | if (After.isInvalid() && ConvTSI) { | ||||
10170 | SourceLocation InsertLoc = | ||||
10171 | getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); | ||||
10172 | DB << FixItHint::CreateInsertion(InsertLoc, " ") | ||||
10173 | << FixItHint::CreateInsertionFromRange( | ||||
10174 | InsertLoc, CharSourceRange::getTokenRange(Before)) | ||||
10175 | << FixItHint::CreateRemoval(Before); | ||||
10176 | } | ||||
10177 | } else if (!Proto->getReturnType()->isDependentType()) { | ||||
10178 | DB << /*typedef*/1 << Proto->getReturnType(); | ||||
10179 | } else if (getLangOpts().CPlusPlus11) { | ||||
10180 | DB << /*alias template*/2 << Proto->getReturnType(); | ||||
10181 | } else { | ||||
10182 | DB << /*might not be fixable*/3; | ||||
10183 | } | ||||
10184 | |||||
10185 | // Recover by incorporating the other type chunks into the result type. | ||||
10186 | // Note, this does *not* change the name of the function. This is compatible | ||||
10187 | // with the GCC extension: | ||||
10188 | // struct S { &operator int(); } s; | ||||
10189 | // int &r = s.operator int(); // ok in GCC | ||||
10190 | // S::operator int&() {} // error in GCC, function name is 'operator int'. | ||||
10191 | ConvType = Proto->getReturnType(); | ||||
10192 | } | ||||
10193 | |||||
10194 | // C++ [class.conv.fct]p4: | ||||
10195 | // The conversion-type-id shall not represent a function type nor | ||||
10196 | // an array type. | ||||
10197 | if (ConvType->isArrayType()) { | ||||
10198 | Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); | ||||
10199 | ConvType = Context.getPointerType(ConvType); | ||||
10200 | D.setInvalidType(); | ||||
10201 | } else if (ConvType->isFunctionType()) { | ||||
10202 | Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); | ||||
10203 | ConvType = Context.getPointerType(ConvType); | ||||
10204 | D.setInvalidType(); | ||||
10205 | } | ||||
10206 | |||||
10207 | // Rebuild the function type "R" without any parameters (in case any | ||||
10208 | // of the errors above fired) and with the conversion type as the | ||||
10209 | // return type. | ||||
10210 | if (D.isInvalidType()) | ||||
10211 | R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); | ||||
10212 | |||||
10213 | // C++0x explicit conversion operators. | ||||
10214 | if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a) | ||||
10215 | Diag(DS.getExplicitSpecLoc(), | ||||
10216 | getLangOpts().CPlusPlus11 | ||||
10217 | ? diag::warn_cxx98_compat_explicit_conversion_functions | ||||
10218 | : diag::ext_explicit_conversion_functions) | ||||
10219 | << SourceRange(DS.getExplicitSpecRange()); | ||||
10220 | } | ||||
10221 | |||||
10222 | /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete | ||||
10223 | /// the declaration of the given C++ conversion function. This routine | ||||
10224 | /// is responsible for recording the conversion function in the C++ | ||||
10225 | /// class, if possible. | ||||
10226 | Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { | ||||
10227 | assert(Conversion && "Expected to receive a conversion function declaration")((Conversion && "Expected to receive a conversion function declaration" ) ? static_cast<void> (0) : __assert_fail ("Conversion && \"Expected to receive a conversion function declaration\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 10227, __PRETTY_FUNCTION__)); | ||||
10228 | |||||
10229 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); | ||||
10230 | |||||
10231 | // Make sure we aren't redeclaring the conversion function. | ||||
10232 | QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); | ||||
10233 | |||||
10234 | // C++ [class.conv.fct]p1: | ||||
10235 | // [...] A conversion function is never used to convert a | ||||
10236 | // (possibly cv-qualified) object to the (possibly cv-qualified) | ||||
10237 | // same object type (or a reference to it), to a (possibly | ||||
10238 | // cv-qualified) base class of that type (or a reference to it), | ||||
10239 | // or to (possibly cv-qualified) void. | ||||
10240 | // FIXME: Suppress this warning if the conversion function ends up being a | ||||
10241 | // virtual function that overrides a virtual function in a base class. | ||||
10242 | QualType ClassType | ||||
10243 | = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); | ||||
10244 | if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) | ||||
10245 | ConvType = ConvTypeRef->getPointeeType(); | ||||
10246 | if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && | ||||
10247 | Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) | ||||
10248 | /* Suppress diagnostics for instantiations. */; | ||||
10249 | else if (ConvType->isRecordType()) { | ||||
10250 | ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); | ||||
10251 | if (ConvType == ClassType) | ||||
10252 | Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) | ||||
10253 | << ClassType; | ||||
10254 | else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) | ||||
10255 | Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) | ||||
10256 | << ClassType << ConvType; | ||||
10257 | } else if (ConvType->isVoidType()) { | ||||
10258 | Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) | ||||
10259 | << ClassType << ConvType; | ||||
10260 | } | ||||
10261 | |||||
10262 | if (FunctionTemplateDecl *ConversionTemplate | ||||
10263 | = Conversion->getDescribedFunctionTemplate()) | ||||
10264 | return ConversionTemplate; | ||||
10265 | |||||
10266 | return Conversion; | ||||
10267 | } | ||||
10268 | |||||
10269 | namespace { | ||||
10270 | /// Utility class to accumulate and print a diagnostic listing the invalid | ||||
10271 | /// specifier(s) on a declaration. | ||||
10272 | struct BadSpecifierDiagnoser { | ||||
10273 | BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) | ||||
10274 | : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} | ||||
10275 | ~BadSpecifierDiagnoser() { | ||||
10276 | Diagnostic << Specifiers; | ||||
10277 | } | ||||
10278 | |||||
10279 | template<typename T> void check(SourceLocation SpecLoc, T Spec) { | ||||
10280 | return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); | ||||
10281 | } | ||||
10282 | void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { | ||||
10283 | return check(SpecLoc, | ||||
10284 | DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); | ||||
10285 | } | ||||
10286 | void check(SourceLocation SpecLoc, const char *Spec) { | ||||
10287 | if (SpecLoc.isInvalid()) return; | ||||
10288 | Diagnostic << SourceRange(SpecLoc, SpecLoc); | ||||
10289 | if (!Specifiers.empty()) Specifiers += " "; | ||||
10290 | Specifiers += Spec; | ||||
10291 | } | ||||
10292 | |||||
10293 | Sema &S; | ||||
10294 | Sema::SemaDiagnosticBuilder Diagnostic; | ||||
10295 | std::string Specifiers; | ||||
10296 | }; | ||||
10297 | } | ||||
10298 | |||||
10299 | /// Check the validity of a declarator that we parsed for a deduction-guide. | ||||
10300 | /// These aren't actually declarators in the grammar, so we need to check that | ||||
10301 | /// the user didn't specify any pieces that are not part of the deduction-guide | ||||
10302 | /// grammar. | ||||
10303 | void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, | ||||
10304 | StorageClass &SC) { | ||||
10305 | TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); | ||||
10306 | TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); | ||||
10307 | assert(GuidedTemplateDecl && "missing template decl for deduction guide")((GuidedTemplateDecl && "missing template decl for deduction guide" ) ? static_cast<void> (0) : __assert_fail ("GuidedTemplateDecl && \"missing template decl for deduction guide\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 10307, __PRETTY_FUNCTION__)); | ||||
10308 | |||||
10309 | // C++ [temp.deduct.guide]p3: | ||||
10310 | // A deduction-gide shall be declared in the same scope as the | ||||
10311 | // corresponding class template. | ||||
10312 | if (!CurContext->getRedeclContext()->Equals( | ||||
10313 | GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { | ||||
10314 | Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) | ||||
10315 | << GuidedTemplateDecl; | ||||
10316 | Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); | ||||
10317 | } | ||||
10318 | |||||
10319 | auto &DS = D.getMutableDeclSpec(); | ||||
10320 | // We leave 'friend' and 'virtual' to be rejected in the normal way. | ||||
10321 | if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || | ||||
10322 | DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || | ||||
10323 | DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { | ||||
10324 | BadSpecifierDiagnoser Diagnoser( | ||||
10325 | *this, D.getIdentifierLoc(), | ||||
10326 | diag::err_deduction_guide_invalid_specifier); | ||||
10327 | |||||
10328 | Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); | ||||
10329 | DS.ClearStorageClassSpecs(); | ||||
10330 | SC = SC_None; | ||||
10331 | |||||
10332 | // 'explicit' is permitted. | ||||
10333 | Diagnoser.check(DS.getInlineSpecLoc(), "inline"); | ||||
10334 | Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); | ||||
10335 | Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); | ||||
10336 | DS.ClearConstexprSpec(); | ||||
10337 | |||||
10338 | Diagnoser.check(DS.getConstSpecLoc(), "const"); | ||||
10339 | Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); | ||||
10340 | Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); | ||||
10341 | Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); | ||||
10342 | Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); | ||||
10343 | DS.ClearTypeQualifiers(); | ||||
10344 | |||||
10345 | Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); | ||||
10346 | Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); | ||||
10347 | Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); | ||||
10348 | Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); | ||||
10349 | DS.ClearTypeSpecType(); | ||||
10350 | } | ||||
10351 | |||||
10352 | if (D.isInvalidType()) | ||||
10353 | return; | ||||
10354 | |||||
10355 | // Check the declarator is simple enough. | ||||
10356 | bool FoundFunction = false; | ||||
10357 | for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { | ||||
10358 | if (Chunk.Kind == DeclaratorChunk::Paren) | ||||
10359 | continue; | ||||
10360 | if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { | ||||
10361 | Diag(D.getDeclSpec().getBeginLoc(), | ||||
10362 | diag::err_deduction_guide_with_complex_decl) | ||||
10363 | << D.getSourceRange(); | ||||
10364 | break; | ||||
10365 | } | ||||
10366 | if (!Chunk.Fun.hasTrailingReturnType()) { | ||||
10367 | Diag(D.getName().getBeginLoc(), | ||||
10368 | diag::err_deduction_guide_no_trailing_return_type); | ||||
10369 | break; | ||||
10370 | } | ||||
10371 | |||||
10372 | // Check that the return type is written as a specialization of | ||||
10373 | // the template specified as the deduction-guide's name. | ||||
10374 | ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); | ||||
10375 | TypeSourceInfo *TSI = nullptr; | ||||
10376 | QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); | ||||
10377 | assert(TSI && "deduction guide has valid type but invalid return type?")((TSI && "deduction guide has valid type but invalid return type?" ) ? static_cast<void> (0) : __assert_fail ("TSI && \"deduction guide has valid type but invalid return type?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 10377, __PRETTY_FUNCTION__)); | ||||
10378 | bool AcceptableReturnType = false; | ||||
10379 | bool MightInstantiateToSpecialization = false; | ||||
10380 | if (auto RetTST = | ||||
10381 | TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { | ||||
10382 | TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); | ||||
10383 | bool TemplateMatches = | ||||
10384 | Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); | ||||
10385 | if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) | ||||
10386 | AcceptableReturnType = true; | ||||
10387 | else { | ||||
10388 | // This could still instantiate to the right type, unless we know it | ||||
10389 | // names the wrong class template. | ||||
10390 | auto *TD = SpecifiedName.getAsTemplateDecl(); | ||||
10391 | MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && | ||||
10392 | !TemplateMatches); | ||||
10393 | } | ||||
10394 | } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { | ||||
10395 | MightInstantiateToSpecialization = true; | ||||
10396 | } | ||||
10397 | |||||
10398 | if (!AcceptableReturnType) { | ||||
10399 | Diag(TSI->getTypeLoc().getBeginLoc(), | ||||
10400 | diag::err_deduction_guide_bad_trailing_return_type) | ||||
10401 | << GuidedTemplate << TSI->getType() | ||||
10402 | << MightInstantiateToSpecialization | ||||
10403 | << TSI->getTypeLoc().getSourceRange(); | ||||
10404 | } | ||||
10405 | |||||
10406 | // Keep going to check that we don't have any inner declarator pieces (we | ||||
10407 | // could still have a function returning a pointer to a function). | ||||
10408 | FoundFunction = true; | ||||
10409 | } | ||||
10410 | |||||
10411 | if (D.isFunctionDefinition()) | ||||
10412 | Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); | ||||
10413 | } | ||||
10414 | |||||
10415 | //===----------------------------------------------------------------------===// | ||||
10416 | // Namespace Handling | ||||
10417 | //===----------------------------------------------------------------------===// | ||||
10418 | |||||
10419 | /// Diagnose a mismatch in 'inline' qualifiers when a namespace is | ||||
10420 | /// reopened. | ||||
10421 | static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, | ||||
10422 | SourceLocation Loc, | ||||
10423 | IdentifierInfo *II, bool *IsInline, | ||||
10424 | NamespaceDecl *PrevNS) { | ||||
10425 | assert(*IsInline != PrevNS->isInline())((*IsInline != PrevNS->isInline()) ? static_cast<void> (0) : __assert_fail ("*IsInline != PrevNS->isInline()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 10425, __PRETTY_FUNCTION__)); | ||||
10426 | |||||
10427 | // HACK: Work around a bug in libstdc++4.6's <atomic>, where | ||||
10428 | // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as | ||||
10429 | // inline namespaces, with the intention of bringing names into namespace std. | ||||
10430 | // | ||||
10431 | // We support this just well enough to get that case working; this is not | ||||
10432 | // sufficient to support reopening namespaces as inline in general. | ||||
10433 | if (*IsInline && II && II->getName().startswith("__atomic") && | ||||
10434 | S.getSourceManager().isInSystemHeader(Loc)) { | ||||
10435 | // Mark all prior declarations of the namespace as inline. | ||||
10436 | for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; | ||||
10437 | NS = NS->getPreviousDecl()) | ||||
10438 | NS->setInline(*IsInline); | ||||
10439 | // Patch up the lookup table for the containing namespace. This isn't really | ||||
10440 | // correct, but it's good enough for this particular case. | ||||
10441 | for (auto *I : PrevNS->decls()) | ||||
10442 | if (auto *ND = dyn_cast<NamedDecl>(I)) | ||||
10443 | PrevNS->getParent()->makeDeclVisibleInContext(ND); | ||||
10444 | return; | ||||
10445 | } | ||||
10446 | |||||
10447 | if (PrevNS->isInline()) | ||||
10448 | // The user probably just forgot the 'inline', so suggest that it | ||||
10449 | // be added back. | ||||
10450 | S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) | ||||
10451 | << FixItHint::CreateInsertion(KeywordLoc, "inline "); | ||||
10452 | else | ||||
10453 | S.Diag(Loc, diag::err_inline_namespace_mismatch); | ||||
10454 | |||||
10455 | S.Diag(PrevNS->getLocation(), diag::note_previous_definition); | ||||
10456 | *IsInline = PrevNS->isInline(); | ||||
10457 | } | ||||
10458 | |||||
10459 | /// ActOnStartNamespaceDef - This is called at the start of a namespace | ||||
10460 | /// definition. | ||||
10461 | Decl *Sema::ActOnStartNamespaceDef( | ||||
10462 | Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, | ||||
10463 | SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, | ||||
10464 | const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { | ||||
10465 | SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; | ||||
10466 | // For anonymous namespace, take the location of the left brace. | ||||
10467 | SourceLocation Loc = II ? IdentLoc : LBrace; | ||||
10468 | bool IsInline = InlineLoc.isValid(); | ||||
10469 | bool IsInvalid = false; | ||||
10470 | bool IsStd = false; | ||||
10471 | bool AddToKnown = false; | ||||
10472 | Scope *DeclRegionScope = NamespcScope->getParent(); | ||||
10473 | |||||
10474 | NamespaceDecl *PrevNS = nullptr; | ||||
10475 | if (II) { | ||||
10476 | // C++ [namespace.def]p2: | ||||
10477 | // The identifier in an original-namespace-definition shall not | ||||
10478 | // have been previously defined in the declarative region in | ||||
10479 | // which the original-namespace-definition appears. The | ||||
10480 | // identifier in an original-namespace-definition is the name of | ||||
10481 | // the namespace. Subsequently in that declarative region, it is | ||||
10482 | // treated as an original-namespace-name. | ||||
10483 | // | ||||
10484 | // Since namespace names are unique in their scope, and we don't | ||||
10485 | // look through using directives, just look for any ordinary names | ||||
10486 | // as if by qualified name lookup. | ||||
10487 | LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, | ||||
10488 | ForExternalRedeclaration); | ||||
10489 | LookupQualifiedName(R, CurContext->getRedeclContext()); | ||||
10490 | NamedDecl *PrevDecl = | ||||
10491 | R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; | ||||
10492 | PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); | ||||
10493 | |||||
10494 | if (PrevNS) { | ||||
10495 | // This is an extended namespace definition. | ||||
10496 | if (IsInline != PrevNS->isInline()) | ||||
10497 | DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, | ||||
10498 | &IsInline, PrevNS); | ||||
10499 | } else if (PrevDecl) { | ||||
10500 | // This is an invalid name redefinition. | ||||
10501 | Diag(Loc, diag::err_redefinition_different_kind) | ||||
10502 | << II; | ||||
10503 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); | ||||
10504 | IsInvalid = true; | ||||
10505 | // Continue on to push Namespc as current DeclContext and return it. | ||||
10506 | } else if (II->isStr("std") && | ||||
10507 | CurContext->getRedeclContext()->isTranslationUnit()) { | ||||
10508 | // This is the first "real" definition of the namespace "std", so update | ||||
10509 | // our cache of the "std" namespace to point at this definition. | ||||
10510 | PrevNS = getStdNamespace(); | ||||
10511 | IsStd = true; | ||||
10512 | AddToKnown = !IsInline; | ||||
10513 | } else { | ||||
10514 | // We've seen this namespace for the first time. | ||||
10515 | AddToKnown = !IsInline; | ||||
10516 | } | ||||
10517 | } else { | ||||
10518 | // Anonymous namespaces. | ||||
10519 | |||||
10520 | // Determine whether the parent already has an anonymous namespace. | ||||
10521 | DeclContext *Parent = CurContext->getRedeclContext(); | ||||
10522 | if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { | ||||
10523 | PrevNS = TU->getAnonymousNamespace(); | ||||
10524 | } else { | ||||
10525 | NamespaceDecl *ND = cast<NamespaceDecl>(Parent); | ||||
10526 | PrevNS = ND->getAnonymousNamespace(); | ||||
10527 | } | ||||
10528 | |||||
10529 | if (PrevNS && IsInline != PrevNS->isInline()) | ||||
10530 | DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, | ||||
10531 | &IsInline, PrevNS); | ||||
10532 | } | ||||
10533 | |||||
10534 | NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, | ||||
10535 | StartLoc, Loc, II, PrevNS); | ||||
10536 | if (IsInvalid) | ||||
10537 | Namespc->setInvalidDecl(); | ||||
10538 | |||||
10539 | ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); | ||||
10540 | AddPragmaAttributes(DeclRegionScope, Namespc); | ||||
10541 | |||||
10542 | // FIXME: Should we be merging attributes? | ||||
10543 | if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) | ||||
10544 | PushNamespaceVisibilityAttr(Attr, Loc); | ||||
10545 | |||||
10546 | if (IsStd) | ||||
10547 | StdNamespace = Namespc; | ||||
10548 | if (AddToKnown) | ||||
10549 | KnownNamespaces[Namespc] = false; | ||||
10550 | |||||
10551 | if (II) { | ||||
10552 | PushOnScopeChains(Namespc, DeclRegionScope); | ||||
10553 | } else { | ||||
10554 | // Link the anonymous namespace into its parent. | ||||
10555 | DeclContext *Parent = CurContext->getRedeclContext(); | ||||
10556 | if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { | ||||
10557 | TU->setAnonymousNamespace(Namespc); | ||||
10558 | } else { | ||||
10559 | cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); | ||||
10560 | } | ||||
10561 | |||||
10562 | CurContext->addDecl(Namespc); | ||||
10563 | |||||
10564 | // C++ [namespace.unnamed]p1. An unnamed-namespace-definition | ||||
10565 | // behaves as if it were replaced by | ||||
10566 | // namespace unique { /* empty body */ } | ||||
10567 | // using namespace unique; | ||||
10568 | // namespace unique { namespace-body } | ||||
10569 | // where all occurrences of 'unique' in a translation unit are | ||||
10570 | // replaced by the same identifier and this identifier differs | ||||
10571 | // from all other identifiers in the entire program. | ||||
10572 | |||||
10573 | // We just create the namespace with an empty name and then add an | ||||
10574 | // implicit using declaration, just like the standard suggests. | ||||
10575 | // | ||||
10576 | // CodeGen enforces the "universally unique" aspect by giving all | ||||
10577 | // declarations semantically contained within an anonymous | ||||
10578 | // namespace internal linkage. | ||||
10579 | |||||
10580 | if (!PrevNS) { | ||||
10581 | UD = UsingDirectiveDecl::Create(Context, Parent, | ||||
10582 | /* 'using' */ LBrace, | ||||
10583 | /* 'namespace' */ SourceLocation(), | ||||
10584 | /* qualifier */ NestedNameSpecifierLoc(), | ||||
10585 | /* identifier */ SourceLocation(), | ||||
10586 | Namespc, | ||||
10587 | /* Ancestor */ Parent); | ||||
10588 | UD->setImplicit(); | ||||
10589 | Parent->addDecl(UD); | ||||
10590 | } | ||||
10591 | } | ||||
10592 | |||||
10593 | ActOnDocumentableDecl(Namespc); | ||||
10594 | |||||
10595 | // Although we could have an invalid decl (i.e. the namespace name is a | ||||
10596 | // redefinition), push it as current DeclContext and try to continue parsing. | ||||
10597 | // FIXME: We should be able to push Namespc here, so that the each DeclContext | ||||
10598 | // for the namespace has the declarations that showed up in that particular | ||||
10599 | // namespace definition. | ||||
10600 | PushDeclContext(NamespcScope, Namespc); | ||||
10601 | return Namespc; | ||||
10602 | } | ||||
10603 | |||||
10604 | /// getNamespaceDecl - Returns the namespace a decl represents. If the decl | ||||
10605 | /// is a namespace alias, returns the namespace it points to. | ||||
10606 | static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { | ||||
10607 | if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) | ||||
10608 | return AD->getNamespace(); | ||||
10609 | return dyn_cast_or_null<NamespaceDecl>(D); | ||||
10610 | } | ||||
10611 | |||||
10612 | /// ActOnFinishNamespaceDef - This callback is called after a namespace is | ||||
10613 | /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. | ||||
10614 | void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { | ||||
10615 | NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); | ||||
10616 | assert(Namespc && "Invalid parameter, expected NamespaceDecl")((Namespc && "Invalid parameter, expected NamespaceDecl" ) ? static_cast<void> (0) : __assert_fail ("Namespc && \"Invalid parameter, expected NamespaceDecl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 10616, __PRETTY_FUNCTION__)); | ||||
10617 | Namespc->setRBraceLoc(RBrace); | ||||
10618 | PopDeclContext(); | ||||
10619 | if (Namespc->hasAttr<VisibilityAttr>()) | ||||
10620 | PopPragmaVisibility(true, RBrace); | ||||
10621 | // If this namespace contains an export-declaration, export it now. | ||||
10622 | if (DeferredExportedNamespaces.erase(Namespc)) | ||||
10623 | Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); | ||||
10624 | } | ||||
10625 | |||||
10626 | CXXRecordDecl *Sema::getStdBadAlloc() const { | ||||
10627 | return cast_or_null<CXXRecordDecl>( | ||||
10628 | StdBadAlloc.get(Context.getExternalSource())); | ||||
10629 | } | ||||
10630 | |||||
10631 | EnumDecl *Sema::getStdAlignValT() const { | ||||
10632 | return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); | ||||
10633 | } | ||||
10634 | |||||
10635 | NamespaceDecl *Sema::getStdNamespace() const { | ||||
10636 | return cast_or_null<NamespaceDecl>( | ||||
10637 | StdNamespace.get(Context.getExternalSource())); | ||||
10638 | } | ||||
10639 | |||||
10640 | NamespaceDecl *Sema::lookupStdExperimentalNamespace() { | ||||
10641 | if (!StdExperimentalNamespaceCache) { | ||||
10642 | if (auto Std = getStdNamespace()) { | ||||
10643 | LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), | ||||
10644 | SourceLocation(), LookupNamespaceName); | ||||
10645 | if (!LookupQualifiedName(Result, Std) || | ||||
10646 | !(StdExperimentalNamespaceCache = | ||||
10647 | Result.getAsSingle<NamespaceDecl>())) | ||||
10648 | Result.suppressDiagnostics(); | ||||
10649 | } | ||||
10650 | } | ||||
10651 | return StdExperimentalNamespaceCache; | ||||
10652 | } | ||||
10653 | |||||
10654 | namespace { | ||||
10655 | |||||
10656 | enum UnsupportedSTLSelect { | ||||
10657 | USS_InvalidMember, | ||||
10658 | USS_MissingMember, | ||||
10659 | USS_NonTrivial, | ||||
10660 | USS_Other | ||||
10661 | }; | ||||
10662 | |||||
10663 | struct InvalidSTLDiagnoser { | ||||
10664 | Sema &S; | ||||
10665 | SourceLocation Loc; | ||||
10666 | QualType TyForDiags; | ||||
10667 | |||||
10668 | QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", | ||||
10669 | const VarDecl *VD = nullptr) { | ||||
10670 | { | ||||
10671 | auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) | ||||
10672 | << TyForDiags << ((int)Sel); | ||||
10673 | if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { | ||||
10674 | assert(!Name.empty())((!Name.empty()) ? static_cast<void> (0) : __assert_fail ("!Name.empty()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 10674, __PRETTY_FUNCTION__)); | ||||
10675 | D << Name; | ||||
10676 | } | ||||
10677 | } | ||||
10678 | if (Sel == USS_InvalidMember) { | ||||
10679 | S.Diag(VD->getLocation(), diag::note_var_declared_here) | ||||
10680 | << VD << VD->getSourceRange(); | ||||
10681 | } | ||||
10682 | return QualType(); | ||||
10683 | } | ||||
10684 | }; | ||||
10685 | } // namespace | ||||
10686 | |||||
10687 | QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, | ||||
10688 | SourceLocation Loc, | ||||
10689 | ComparisonCategoryUsage Usage) { | ||||
10690 | assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "Looking for comparison category type outside of C++." ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for comparison category type outside of C++.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 10691, __PRETTY_FUNCTION__)) | ||||
10691 | "Looking for comparison category type outside of C++.")((getLangOpts().CPlusPlus && "Looking for comparison category type outside of C++." ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for comparison category type outside of C++.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 10691, __PRETTY_FUNCTION__)); | ||||
10692 | |||||
10693 | // Use an elaborated type for diagnostics which has a name containing the | ||||
10694 | // prepended 'std' namespace but not any inline namespace names. | ||||
10695 | auto TyForDiags = [&](ComparisonCategoryInfo *Info) { | ||||
10696 | auto *NNS = | ||||
10697 | NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); | ||||
10698 | return Context.getElaboratedType(ETK_None, NNS, Info->getType()); | ||||
10699 | }; | ||||
10700 | |||||
10701 | // Check if we've already successfully checked the comparison category type | ||||
10702 | // before. If so, skip checking it again. | ||||
10703 | ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); | ||||
10704 | if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { | ||||
10705 | // The only thing we need to check is that the type has a reachable | ||||
10706 | // definition in the current context. | ||||
10707 | if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) | ||||
10708 | return QualType(); | ||||
10709 | |||||
10710 | return Info->getType(); | ||||
10711 | } | ||||
10712 | |||||
10713 | // If lookup failed | ||||
10714 | if (!Info) { | ||||
10715 | std::string NameForDiags = "std::"; | ||||
10716 | NameForDiags += ComparisonCategories::getCategoryString(Kind); | ||||
10717 | Diag(Loc, diag::err_implied_comparison_category_type_not_found) | ||||
10718 | << NameForDiags << (int)Usage; | ||||
10719 | return QualType(); | ||||
10720 | } | ||||
10721 | |||||
10722 | assert(Info->Kind == Kind)((Info->Kind == Kind) ? static_cast<void> (0) : __assert_fail ("Info->Kind == Kind", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 10722, __PRETTY_FUNCTION__)); | ||||
10723 | assert(Info->Record)((Info->Record) ? static_cast<void> (0) : __assert_fail ("Info->Record", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 10723, __PRETTY_FUNCTION__)); | ||||
10724 | |||||
10725 | // Update the Record decl in case we encountered a forward declaration on our | ||||
10726 | // first pass. FIXME: This is a bit of a hack. | ||||
10727 | if (Info->Record->hasDefinition()) | ||||
10728 | Info->Record = Info->Record->getDefinition(); | ||||
10729 | |||||
10730 | if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) | ||||
10731 | return QualType(); | ||||
10732 | |||||
10733 | InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; | ||||
10734 | |||||
10735 | if (!Info->Record->isTriviallyCopyable()) | ||||
10736 | return UnsupportedSTLError(USS_NonTrivial); | ||||
10737 | |||||
10738 | for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { | ||||
10739 | CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); | ||||
10740 | // Tolerate empty base classes. | ||||
10741 | if (Base->isEmpty()) | ||||
10742 | continue; | ||||
10743 | // Reject STL implementations which have at least one non-empty base. | ||||
10744 | return UnsupportedSTLError(); | ||||
10745 | } | ||||
10746 | |||||
10747 | // Check that the STL has implemented the types using a single integer field. | ||||
10748 | // This expectation allows better codegen for builtin operators. We require: | ||||
10749 | // (1) The class has exactly one field. | ||||
10750 | // (2) The field is an integral or enumeration type. | ||||
10751 | auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); | ||||
10752 | if (std::distance(FIt, FEnd) != 1 || | ||||
10753 | !FIt->getType()->isIntegralOrEnumerationType()) { | ||||
10754 | return UnsupportedSTLError(); | ||||
10755 | } | ||||
10756 | |||||
10757 | // Build each of the require values and store them in Info. | ||||
10758 | for (ComparisonCategoryResult CCR : | ||||
10759 | ComparisonCategories::getPossibleResultsForType(Kind)) { | ||||
10760 | StringRef MemName = ComparisonCategories::getResultString(CCR); | ||||
10761 | ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); | ||||
10762 | |||||
10763 | if (!ValInfo) | ||||
10764 | return UnsupportedSTLError(USS_MissingMember, MemName); | ||||
10765 | |||||
10766 | VarDecl *VD = ValInfo->VD; | ||||
10767 | assert(VD && "should not be null!")((VD && "should not be null!") ? static_cast<void> (0) : __assert_fail ("VD && \"should not be null!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 10767, __PRETTY_FUNCTION__)); | ||||
10768 | |||||
10769 | // Attempt to diagnose reasons why the STL definition of this type | ||||
10770 | // might be foobar, including it failing to be a constant expression. | ||||
10771 | // TODO Handle more ways the lookup or result can be invalid. | ||||
10772 | if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || | ||||
10773 | !VD->checkInitIsICE()) | ||||
10774 | return UnsupportedSTLError(USS_InvalidMember, MemName, VD); | ||||
10775 | |||||
10776 | // Attempt to evaluate the var decl as a constant expression and extract | ||||
10777 | // the value of its first field as a ICE. If this fails, the STL | ||||
10778 | // implementation is not supported. | ||||
10779 | if (!ValInfo->hasValidIntValue()) | ||||
10780 | return UnsupportedSTLError(); | ||||
10781 | |||||
10782 | MarkVariableReferenced(Loc, VD); | ||||
10783 | } | ||||
10784 | |||||
10785 | // We've successfully built the required types and expressions. Update | ||||
10786 | // the cache and return the newly cached value. | ||||
10787 | FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; | ||||
10788 | return Info->getType(); | ||||
10789 | } | ||||
10790 | |||||
10791 | /// Retrieve the special "std" namespace, which may require us to | ||||
10792 | /// implicitly define the namespace. | ||||
10793 | NamespaceDecl *Sema::getOrCreateStdNamespace() { | ||||
10794 | if (!StdNamespace) { | ||||
10795 | // The "std" namespace has not yet been defined, so build one implicitly. | ||||
10796 | StdNamespace = NamespaceDecl::Create(Context, | ||||
10797 | Context.getTranslationUnitDecl(), | ||||
10798 | /*Inline=*/false, | ||||
10799 | SourceLocation(), SourceLocation(), | ||||
10800 | &PP.getIdentifierTable().get("std"), | ||||
10801 | /*PrevDecl=*/nullptr); | ||||
10802 | getStdNamespace()->setImplicit(true); | ||||
10803 | } | ||||
10804 | |||||
10805 | return getStdNamespace(); | ||||
10806 | } | ||||
10807 | |||||
10808 | bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { | ||||
10809 | assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "Looking for std::initializer_list outside of C++." ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for std::initializer_list outside of C++.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 10810, __PRETTY_FUNCTION__)) | ||||
10810 | "Looking for std::initializer_list outside of C++.")((getLangOpts().CPlusPlus && "Looking for std::initializer_list outside of C++." ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Looking for std::initializer_list outside of C++.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 10810, __PRETTY_FUNCTION__)); | ||||
10811 | |||||
10812 | // We're looking for implicit instantiations of | ||||
10813 | // template <typename E> class std::initializer_list. | ||||
10814 | |||||
10815 | if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. | ||||
10816 | return false; | ||||
10817 | |||||
10818 | ClassTemplateDecl *Template = nullptr; | ||||
10819 | const TemplateArgument *Arguments = nullptr; | ||||
10820 | |||||
10821 | if (const RecordType *RT = Ty->getAs<RecordType>()) { | ||||
10822 | |||||
10823 | ClassTemplateSpecializationDecl *Specialization = | ||||
10824 | dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); | ||||
10825 | if (!Specialization) | ||||
10826 | return false; | ||||
10827 | |||||
10828 | Template = Specialization->getSpecializedTemplate(); | ||||
10829 | Arguments = Specialization->getTemplateArgs().data(); | ||||
10830 | } else if (const TemplateSpecializationType *TST = | ||||
10831 | Ty->getAs<TemplateSpecializationType>()) { | ||||
10832 | Template = dyn_cast_or_null<ClassTemplateDecl>( | ||||
10833 | TST->getTemplateName().getAsTemplateDecl()); | ||||
10834 | Arguments = TST->getArgs(); | ||||
10835 | } | ||||
10836 | if (!Template) | ||||
10837 | return false; | ||||
10838 | |||||
10839 | if (!StdInitializerList) { | ||||
10840 | // Haven't recognized std::initializer_list yet, maybe this is it. | ||||
10841 | CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); | ||||
10842 | if (TemplateClass->getIdentifier() != | ||||
10843 | &PP.getIdentifierTable().get("initializer_list") || | ||||
10844 | !getStdNamespace()->InEnclosingNamespaceSetOf( | ||||
10845 | TemplateClass->getDeclContext())) | ||||
10846 | return false; | ||||
10847 | // This is a template called std::initializer_list, but is it the right | ||||
10848 | // template? | ||||
10849 | TemplateParameterList *Params = Template->getTemplateParameters(); | ||||
10850 | if (Params->getMinRequiredArguments() != 1) | ||||
10851 | return false; | ||||
10852 | if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) | ||||
10853 | return false; | ||||
10854 | |||||
10855 | // It's the right template. | ||||
10856 | StdInitializerList = Template; | ||||
10857 | } | ||||
10858 | |||||
10859 | if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) | ||||
10860 | return false; | ||||
10861 | |||||
10862 | // This is an instance of std::initializer_list. Find the argument type. | ||||
10863 | if (Element) | ||||
10864 | *Element = Arguments[0].getAsType(); | ||||
10865 | return true; | ||||
10866 | } | ||||
10867 | |||||
10868 | static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ | ||||
10869 | NamespaceDecl *Std = S.getStdNamespace(); | ||||
10870 | if (!Std) { | ||||
10871 | S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); | ||||
10872 | return nullptr; | ||||
10873 | } | ||||
10874 | |||||
10875 | LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), | ||||
10876 | Loc, Sema::LookupOrdinaryName); | ||||
10877 | if (!S.LookupQualifiedName(Result, Std)) { | ||||
10878 | S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); | ||||
10879 | return nullptr; | ||||
10880 | } | ||||
10881 | ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); | ||||
10882 | if (!Template) { | ||||
10883 | Result.suppressDiagnostics(); | ||||
10884 | // We found something weird. Complain about the first thing we found. | ||||
10885 | NamedDecl *Found = *Result.begin(); | ||||
10886 | S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); | ||||
10887 | return nullptr; | ||||
10888 | } | ||||
10889 | |||||
10890 | // We found some template called std::initializer_list. Now verify that it's | ||||
10891 | // correct. | ||||
10892 | TemplateParameterList *Params = Template->getTemplateParameters(); | ||||
10893 | if (Params->getMinRequiredArguments() != 1 || | ||||
10894 | !isa<TemplateTypeParmDecl>(Params->getParam(0))) { | ||||
10895 | S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); | ||||
10896 | return nullptr; | ||||
10897 | } | ||||
10898 | |||||
10899 | return Template; | ||||
10900 | } | ||||
10901 | |||||
10902 | QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { | ||||
10903 | if (!StdInitializerList) { | ||||
10904 | StdInitializerList = LookupStdInitializerList(*this, Loc); | ||||
10905 | if (!StdInitializerList) | ||||
10906 | return QualType(); | ||||
10907 | } | ||||
10908 | |||||
10909 | TemplateArgumentListInfo Args(Loc, Loc); | ||||
10910 | Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), | ||||
10911 | Context.getTrivialTypeSourceInfo(Element, | ||||
10912 | Loc))); | ||||
10913 | return Context.getCanonicalType( | ||||
10914 | CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); | ||||
10915 | } | ||||
10916 | |||||
10917 | bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { | ||||
10918 | // C++ [dcl.init.list]p2: | ||||
10919 | // A constructor is an initializer-list constructor if its first parameter | ||||
10920 | // is of type std::initializer_list<E> or reference to possibly cv-qualified | ||||
10921 | // std::initializer_list<E> for some type E, and either there are no other | ||||
10922 | // parameters or else all other parameters have default arguments. | ||||
10923 | if (Ctor->getNumParams() < 1 || | ||||
10924 | (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) | ||||
10925 | return false; | ||||
10926 | |||||
10927 | QualType ArgType = Ctor->getParamDecl(0)->getType(); | ||||
10928 | if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) | ||||
10929 | ArgType = RT->getPointeeType().getUnqualifiedType(); | ||||
10930 | |||||
10931 | return isStdInitializerList(ArgType, nullptr); | ||||
10932 | } | ||||
10933 | |||||
10934 | /// Determine whether a using statement is in a context where it will be | ||||
10935 | /// apply in all contexts. | ||||
10936 | static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { | ||||
10937 | switch (CurContext->getDeclKind()) { | ||||
10938 | case Decl::TranslationUnit: | ||||
10939 | return true; | ||||
10940 | case Decl::LinkageSpec: | ||||
10941 | return IsUsingDirectiveInToplevelContext(CurContext->getParent()); | ||||
10942 | default: | ||||
10943 | return false; | ||||
10944 | } | ||||
10945 | } | ||||
10946 | |||||
10947 | namespace { | ||||
10948 | |||||
10949 | // Callback to only accept typo corrections that are namespaces. | ||||
10950 | class NamespaceValidatorCCC final : public CorrectionCandidateCallback { | ||||
10951 | public: | ||||
10952 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||
10953 | if (NamedDecl *ND = candidate.getCorrectionDecl()) | ||||
10954 | return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); | ||||
10955 | return false; | ||||
10956 | } | ||||
10957 | |||||
10958 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||
10959 | return std::make_unique<NamespaceValidatorCCC>(*this); | ||||
10960 | } | ||||
10961 | }; | ||||
10962 | |||||
10963 | } | ||||
10964 | |||||
10965 | static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, | ||||
10966 | CXXScopeSpec &SS, | ||||
10967 | SourceLocation IdentLoc, | ||||
10968 | IdentifierInfo *Ident) { | ||||
10969 | R.clear(); | ||||
10970 | NamespaceValidatorCCC CCC{}; | ||||
10971 | if (TypoCorrection Corrected = | ||||
10972 | S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, | ||||
10973 | Sema::CTK_ErrorRecovery)) { | ||||
10974 | if (DeclContext *DC = S.computeDeclContext(SS, false)) { | ||||
10975 | std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); | ||||
10976 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | ||||
10977 | Ident->getName().equals(CorrectedStr); | ||||
10978 | S.diagnoseTypo(Corrected, | ||||
10979 | S.PDiag(diag::err_using_directive_member_suggest) | ||||
10980 | << Ident << DC << DroppedSpecifier << SS.getRange(), | ||||
10981 | S.PDiag(diag::note_namespace_defined_here)); | ||||
10982 | } else { | ||||
10983 | S.diagnoseTypo(Corrected, | ||||
10984 | S.PDiag(diag::err_using_directive_suggest) << Ident, | ||||
10985 | S.PDiag(diag::note_namespace_defined_here)); | ||||
10986 | } | ||||
10987 | R.addDecl(Corrected.getFoundDecl()); | ||||
10988 | return true; | ||||
10989 | } | ||||
10990 | return false; | ||||
10991 | } | ||||
10992 | |||||
10993 | Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, | ||||
10994 | SourceLocation NamespcLoc, CXXScopeSpec &SS, | ||||
10995 | SourceLocation IdentLoc, | ||||
10996 | IdentifierInfo *NamespcName, | ||||
10997 | const ParsedAttributesView &AttrList) { | ||||
10998 | assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")((!SS.isInvalid() && "Invalid CXXScopeSpec.") ? static_cast <void> (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 10998, __PRETTY_FUNCTION__)); | ||||
10999 | assert(NamespcName && "Invalid NamespcName.")((NamespcName && "Invalid NamespcName.") ? static_cast <void> (0) : __assert_fail ("NamespcName && \"Invalid NamespcName.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 10999, __PRETTY_FUNCTION__)); | ||||
11000 | assert(IdentLoc.isValid() && "Invalid NamespceName location.")((IdentLoc.isValid() && "Invalid NamespceName location." ) ? static_cast<void> (0) : __assert_fail ("IdentLoc.isValid() && \"Invalid NamespceName location.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 11000, __PRETTY_FUNCTION__)); | ||||
11001 | |||||
11002 | // This can only happen along a recovery path. | ||||
11003 | while (S->isTemplateParamScope()) | ||||
11004 | S = S->getParent(); | ||||
11005 | assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")((S->getFlags() & Scope::DeclScope && "Invalid Scope." ) ? static_cast<void> (0) : __assert_fail ("S->getFlags() & Scope::DeclScope && \"Invalid Scope.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 11005, __PRETTY_FUNCTION__)); | ||||
11006 | |||||
11007 | UsingDirectiveDecl *UDir = nullptr; | ||||
11008 | NestedNameSpecifier *Qualifier = nullptr; | ||||
11009 | if (SS.isSet()) | ||||
11010 | Qualifier = SS.getScopeRep(); | ||||
11011 | |||||
11012 | // Lookup namespace name. | ||||
11013 | LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); | ||||
11014 | LookupParsedName(R, S, &SS); | ||||
11015 | if (R.isAmbiguous()) | ||||
11016 | return nullptr; | ||||
11017 | |||||
11018 | if (R.empty()) { | ||||
11019 | R.clear(); | ||||
11020 | // Allow "using namespace std;" or "using namespace ::std;" even if | ||||
11021 | // "std" hasn't been defined yet, for GCC compatibility. | ||||
11022 | if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && | ||||
11023 | NamespcName->isStr("std")) { | ||||
11024 | Diag(IdentLoc, diag::ext_using_undefined_std); | ||||
11025 | R.addDecl(getOrCreateStdNamespace()); | ||||
11026 | R.resolveKind(); | ||||
11027 | } | ||||
11028 | // Otherwise, attempt typo correction. | ||||
11029 | else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); | ||||
11030 | } | ||||
11031 | |||||
11032 | if (!R.empty()) { | ||||
11033 | NamedDecl *Named = R.getRepresentativeDecl(); | ||||
11034 | NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); | ||||
11035 | assert(NS && "expected namespace decl")((NS && "expected namespace decl") ? static_cast<void > (0) : __assert_fail ("NS && \"expected namespace decl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 11035, __PRETTY_FUNCTION__)); | ||||
11036 | |||||
11037 | // The use of a nested name specifier may trigger deprecation warnings. | ||||
11038 | DiagnoseUseOfDecl(Named, IdentLoc); | ||||
11039 | |||||
11040 | // C++ [namespace.udir]p1: | ||||
11041 | // A using-directive specifies that the names in the nominated | ||||
11042 | // namespace can be used in the scope in which the | ||||
11043 | // using-directive appears after the using-directive. During | ||||
11044 | // unqualified name lookup (3.4.1), the names appear as if they | ||||
11045 | // were declared in the nearest enclosing namespace which | ||||
11046 | // contains both the using-directive and the nominated | ||||
11047 | // namespace. [Note: in this context, "contains" means "contains | ||||
11048 | // directly or indirectly". ] | ||||
11049 | |||||
11050 | // Find enclosing context containing both using-directive and | ||||
11051 | // nominated namespace. | ||||
11052 | DeclContext *CommonAncestor = NS; | ||||
11053 | while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) | ||||
11054 | CommonAncestor = CommonAncestor->getParent(); | ||||
11055 | |||||
11056 | UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, | ||||
11057 | SS.getWithLocInContext(Context), | ||||
11058 | IdentLoc, Named, CommonAncestor); | ||||
11059 | |||||
11060 | if (IsUsingDirectiveInToplevelContext(CurContext) && | ||||
11061 | !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { | ||||
11062 | Diag(IdentLoc, diag::warn_using_directive_in_header); | ||||
11063 | } | ||||
11064 | |||||
11065 | PushUsingDirective(S, UDir); | ||||
11066 | } else { | ||||
11067 | Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); | ||||
11068 | } | ||||
11069 | |||||
11070 | if (UDir) | ||||
11071 | ProcessDeclAttributeList(S, UDir, AttrList); | ||||
11072 | |||||
11073 | return UDir; | ||||
11074 | } | ||||
11075 | |||||
11076 | void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { | ||||
11077 | // If the scope has an associated entity and the using directive is at | ||||
11078 | // namespace or translation unit scope, add the UsingDirectiveDecl into | ||||
11079 | // its lookup structure so qualified name lookup can find it. | ||||
11080 | DeclContext *Ctx = S->getEntity(); | ||||
11081 | if (Ctx && !Ctx->isFunctionOrMethod()) | ||||
11082 | Ctx->addDecl(UDir); | ||||
11083 | else | ||||
11084 | // Otherwise, it is at block scope. The using-directives will affect lookup | ||||
11085 | // only to the end of the scope. | ||||
11086 | S->PushUsingDirective(UDir); | ||||
11087 | } | ||||
11088 | |||||
11089 | Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, | ||||
11090 | SourceLocation UsingLoc, | ||||
11091 | SourceLocation TypenameLoc, CXXScopeSpec &SS, | ||||
11092 | UnqualifiedId &Name, | ||||
11093 | SourceLocation EllipsisLoc, | ||||
11094 | const ParsedAttributesView &AttrList) { | ||||
11095 | assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")((S->getFlags() & Scope::DeclScope && "Invalid Scope." ) ? static_cast<void> (0) : __assert_fail ("S->getFlags() & Scope::DeclScope && \"Invalid Scope.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 11095, __PRETTY_FUNCTION__)); | ||||
11096 | |||||
11097 | if (SS.isEmpty()) { | ||||
11098 | Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); | ||||
11099 | return nullptr; | ||||
11100 | } | ||||
11101 | |||||
11102 | switch (Name.getKind()) { | ||||
11103 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | ||||
11104 | case UnqualifiedIdKind::IK_Identifier: | ||||
11105 | case UnqualifiedIdKind::IK_OperatorFunctionId: | ||||
11106 | case UnqualifiedIdKind::IK_LiteralOperatorId: | ||||
11107 | case UnqualifiedIdKind::IK_ConversionFunctionId: | ||||
11108 | break; | ||||
11109 | |||||
11110 | case UnqualifiedIdKind::IK_ConstructorName: | ||||
11111 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | ||||
11112 | // C++11 inheriting constructors. | ||||
11113 | Diag(Name.getBeginLoc(), | ||||
11114 | getLangOpts().CPlusPlus11 | ||||
11115 | ? diag::warn_cxx98_compat_using_decl_constructor | ||||
11116 | : diag::err_using_decl_constructor) | ||||
11117 | << SS.getRange(); | ||||
11118 | |||||
11119 | if (getLangOpts().CPlusPlus11) break; | ||||
11120 | |||||
11121 | return nullptr; | ||||
11122 | |||||
11123 | case UnqualifiedIdKind::IK_DestructorName: | ||||
11124 | Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); | ||||
11125 | return nullptr; | ||||
11126 | |||||
11127 | case UnqualifiedIdKind::IK_TemplateId: | ||||
11128 | Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) | ||||
11129 | << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); | ||||
11130 | return nullptr; | ||||
11131 | |||||
11132 | case UnqualifiedIdKind::IK_DeductionGuideName: | ||||
11133 | llvm_unreachable("cannot parse qualified deduction guide name")::llvm::llvm_unreachable_internal("cannot parse qualified deduction guide name" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 11133); | ||||
11134 | } | ||||
11135 | |||||
11136 | DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); | ||||
11137 | DeclarationName TargetName = TargetNameInfo.getName(); | ||||
11138 | if (!TargetName) | ||||
11139 | return nullptr; | ||||
11140 | |||||
11141 | // Warn about access declarations. | ||||
11142 | if (UsingLoc.isInvalid()) { | ||||
11143 | Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 | ||||
11144 | ? diag::err_access_decl | ||||
11145 | : diag::warn_access_decl_deprecated) | ||||
11146 | << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); | ||||
11147 | } | ||||
11148 | |||||
11149 | if (EllipsisLoc.isInvalid()) { | ||||
11150 | if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || | ||||
11151 | DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) | ||||
11152 | return nullptr; | ||||
11153 | } else { | ||||
11154 | if (!SS.getScopeRep()->containsUnexpandedParameterPack() && | ||||
11155 | !TargetNameInfo.containsUnexpandedParameterPack()) { | ||||
11156 | Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) | ||||
11157 | << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); | ||||
11158 | EllipsisLoc = SourceLocation(); | ||||
11159 | } | ||||
11160 | } | ||||
11161 | |||||
11162 | NamedDecl *UD = | ||||
11163 | BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, | ||||
11164 | SS, TargetNameInfo, EllipsisLoc, AttrList, | ||||
11165 | /*IsInstantiation*/false); | ||||
11166 | if (UD) | ||||
11167 | PushOnScopeChains(UD, S, /*AddToContext*/ false); | ||||
11168 | |||||
11169 | return UD; | ||||
11170 | } | ||||
11171 | |||||
11172 | /// Determine whether a using declaration considers the given | ||||
11173 | /// declarations as "equivalent", e.g., if they are redeclarations of | ||||
11174 | /// the same entity or are both typedefs of the same type. | ||||
11175 | static bool | ||||
11176 | IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { | ||||
11177 | if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) | ||||
11178 | return true; | ||||
11179 | |||||
11180 | if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) | ||||
11181 | if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) | ||||
11182 | return Context.hasSameType(TD1->getUnderlyingType(), | ||||
11183 | TD2->getUnderlyingType()); | ||||
11184 | |||||
11185 | return false; | ||||
11186 | } | ||||
11187 | |||||
11188 | |||||
11189 | /// Determines whether to create a using shadow decl for a particular | ||||
11190 | /// decl, given the set of decls existing prior to this using lookup. | ||||
11191 | bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, | ||||
11192 | const LookupResult &Previous, | ||||
11193 | UsingShadowDecl *&PrevShadow) { | ||||
11194 | // Diagnose finding a decl which is not from a base class of the | ||||
11195 | // current class. We do this now because there are cases where this | ||||
11196 | // function will silently decide not to build a shadow decl, which | ||||
11197 | // will pre-empt further diagnostics. | ||||
11198 | // | ||||
11199 | // We don't need to do this in C++11 because we do the check once on | ||||
11200 | // the qualifier. | ||||
11201 | // | ||||
11202 | // FIXME: diagnose the following if we care enough: | ||||
11203 | // struct A { int foo; }; | ||||
11204 | // struct B : A { using A::foo; }; | ||||
11205 | // template <class T> struct C : A {}; | ||||
11206 | // template <class T> struct D : C<T> { using B::foo; } // <--- | ||||
11207 | // This is invalid (during instantiation) in C++03 because B::foo | ||||
11208 | // resolves to the using decl in B, which is not a base class of D<T>. | ||||
11209 | // We can't diagnose it immediately because C<T> is an unknown | ||||
11210 | // specialization. The UsingShadowDecl in D<T> then points directly | ||||
11211 | // to A::foo, which will look well-formed when we instantiate. | ||||
11212 | // The right solution is to not collapse the shadow-decl chain. | ||||
11213 | if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { | ||||
11214 | DeclContext *OrigDC = Orig->getDeclContext(); | ||||
11215 | |||||
11216 | // Handle enums and anonymous structs. | ||||
11217 | if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); | ||||
11218 | CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); | ||||
11219 | while (OrigRec->isAnonymousStructOrUnion()) | ||||
11220 | OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); | ||||
11221 | |||||
11222 | if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { | ||||
11223 | if (OrigDC == CurContext) { | ||||
11224 | Diag(Using->getLocation(), | ||||
11225 | diag::err_using_decl_nested_name_specifier_is_current_class) | ||||
11226 | << Using->getQualifierLoc().getSourceRange(); | ||||
11227 | Diag(Orig->getLocation(), diag::note_using_decl_target); | ||||
11228 | Using->setInvalidDecl(); | ||||
11229 | return true; | ||||
11230 | } | ||||
11231 | |||||
11232 | Diag(Using->getQualifierLoc().getBeginLoc(), | ||||
11233 | diag::err_using_decl_nested_name_specifier_is_not_base_class) | ||||
11234 | << Using->getQualifier() | ||||
11235 | << cast<CXXRecordDecl>(CurContext) | ||||
11236 | << Using->getQualifierLoc().getSourceRange(); | ||||
11237 | Diag(Orig->getLocation(), diag::note_using_decl_target); | ||||
11238 | Using->setInvalidDecl(); | ||||
11239 | return true; | ||||
11240 | } | ||||
11241 | } | ||||
11242 | |||||
11243 | if (Previous.empty()) return false; | ||||
11244 | |||||
11245 | NamedDecl *Target = Orig; | ||||
11246 | if (isa<UsingShadowDecl>(Target)) | ||||
11247 | Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); | ||||
11248 | |||||
11249 | // If the target happens to be one of the previous declarations, we | ||||
11250 | // don't have a conflict. | ||||
11251 | // | ||||
11252 | // FIXME: but we might be increasing its access, in which case we | ||||
11253 | // should redeclare it. | ||||
11254 | NamedDecl *NonTag = nullptr, *Tag = nullptr; | ||||
11255 | bool FoundEquivalentDecl = false; | ||||
11256 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | ||||
11257 | I != E; ++I) { | ||||
11258 | NamedDecl *D = (*I)->getUnderlyingDecl(); | ||||
11259 | // We can have UsingDecls in our Previous results because we use the same | ||||
11260 | // LookupResult for checking whether the UsingDecl itself is a valid | ||||
11261 | // redeclaration. | ||||
11262 | if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) | ||||
11263 | continue; | ||||
11264 | |||||
11265 | if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { | ||||
11266 | // C++ [class.mem]p19: | ||||
11267 | // If T is the name of a class, then [every named member other than | ||||
11268 | // a non-static data member] shall have a name different from T | ||||
11269 | if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && | ||||
11270 | !isa<IndirectFieldDecl>(Target) && | ||||
11271 | !isa<UnresolvedUsingValueDecl>(Target) && | ||||
11272 | DiagnoseClassNameShadow( | ||||
11273 | CurContext, | ||||
11274 | DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) | ||||
11275 | return true; | ||||
11276 | } | ||||
11277 | |||||
11278 | if (IsEquivalentForUsingDecl(Context, D, Target)) { | ||||
11279 | if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) | ||||
11280 | PrevShadow = Shadow; | ||||
11281 | FoundEquivalentDecl = true; | ||||
11282 | } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { | ||||
11283 | // We don't conflict with an existing using shadow decl of an equivalent | ||||
11284 | // declaration, but we're not a redeclaration of it. | ||||
11285 | FoundEquivalentDecl = true; | ||||
11286 | } | ||||
11287 | |||||
11288 | if (isVisible(D)) | ||||
11289 | (isa<TagDecl>(D) ? Tag : NonTag) = D; | ||||
11290 | } | ||||
11291 | |||||
11292 | if (FoundEquivalentDecl) | ||||
11293 | return false; | ||||
11294 | |||||
11295 | if (FunctionDecl *FD = Target->getAsFunction()) { | ||||
11296 | NamedDecl *OldDecl = nullptr; | ||||
11297 | switch (CheckOverload(nullptr, FD, Previous, OldDecl, | ||||
11298 | /*IsForUsingDecl*/ true)) { | ||||
11299 | case Ovl_Overload: | ||||
11300 | return false; | ||||
11301 | |||||
11302 | case Ovl_NonFunction: | ||||
11303 | Diag(Using->getLocation(), diag::err_using_decl_conflict); | ||||
11304 | break; | ||||
11305 | |||||
11306 | // We found a decl with the exact signature. | ||||
11307 | case Ovl_Match: | ||||
11308 | // If we're in a record, we want to hide the target, so we | ||||
11309 | // return true (without a diagnostic) to tell the caller not to | ||||
11310 | // build a shadow decl. | ||||
11311 | if (CurContext->isRecord()) | ||||
11312 | return true; | ||||
11313 | |||||
11314 | // If we're not in a record, this is an error. | ||||
11315 | Diag(Using->getLocation(), diag::err_using_decl_conflict); | ||||
11316 | break; | ||||
11317 | } | ||||
11318 | |||||
11319 | Diag(Target->getLocation(), diag::note_using_decl_target); | ||||
11320 | Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); | ||||
11321 | Using->setInvalidDecl(); | ||||
11322 | return true; | ||||
11323 | } | ||||
11324 | |||||
11325 | // Target is not a function. | ||||
11326 | |||||
11327 | if (isa<TagDecl>(Target)) { | ||||
11328 | // No conflict between a tag and a non-tag. | ||||
11329 | if (!Tag) return false; | ||||
11330 | |||||
11331 | Diag(Using->getLocation(), diag::err_using_decl_conflict); | ||||
11332 | Diag(Target->getLocation(), diag::note_using_decl_target); | ||||
11333 | Diag(Tag->getLocation(), diag::note_using_decl_conflict); | ||||
11334 | Using->setInvalidDecl(); | ||||
11335 | return true; | ||||
11336 | } | ||||
11337 | |||||
11338 | // No conflict between a tag and a non-tag. | ||||
11339 | if (!NonTag) return false; | ||||
11340 | |||||
11341 | Diag(Using->getLocation(), diag::err_using_decl_conflict); | ||||
11342 | Diag(Target->getLocation(), diag::note_using_decl_target); | ||||
11343 | Diag(NonTag->getLocation(), diag::note_using_decl_conflict); | ||||
11344 | Using->setInvalidDecl(); | ||||
11345 | return true; | ||||
11346 | } | ||||
11347 | |||||
11348 | /// Determine whether a direct base class is a virtual base class. | ||||
11349 | static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { | ||||
11350 | if (!Derived->getNumVBases()) | ||||
11351 | return false; | ||||
11352 | for (auto &B : Derived->bases()) | ||||
11353 | if (B.getType()->getAsCXXRecordDecl() == Base) | ||||
11354 | return B.isVirtual(); | ||||
11355 | llvm_unreachable("not a direct base class")::llvm::llvm_unreachable_internal("not a direct base class", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 11355); | ||||
11356 | } | ||||
11357 | |||||
11358 | /// Builds a shadow declaration corresponding to a 'using' declaration. | ||||
11359 | UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, | ||||
11360 | UsingDecl *UD, | ||||
11361 | NamedDecl *Orig, | ||||
11362 | UsingShadowDecl *PrevDecl) { | ||||
11363 | // If we resolved to another shadow declaration, just coalesce them. | ||||
11364 | NamedDecl *Target = Orig; | ||||
11365 | if (isa<UsingShadowDecl>(Target)) { | ||||
11366 | Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); | ||||
11367 | assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration")((!isa<UsingShadowDecl>(Target) && "nested shadow declaration" ) ? static_cast<void> (0) : __assert_fail ("!isa<UsingShadowDecl>(Target) && \"nested shadow declaration\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 11367, __PRETTY_FUNCTION__)); | ||||
11368 | } | ||||
11369 | |||||
11370 | NamedDecl *NonTemplateTarget = Target; | ||||
11371 | if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) | ||||
11372 | NonTemplateTarget = TargetTD->getTemplatedDecl(); | ||||
11373 | |||||
11374 | UsingShadowDecl *Shadow; | ||||
11375 | if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { | ||||
11376 | bool IsVirtualBase = | ||||
11377 | isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), | ||||
11378 | UD->getQualifier()->getAsRecordDecl()); | ||||
11379 | Shadow = ConstructorUsingShadowDecl::Create( | ||||
11380 | Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); | ||||
11381 | } else { | ||||
11382 | Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, | ||||
11383 | Target); | ||||
11384 | } | ||||
11385 | UD->addShadowDecl(Shadow); | ||||
11386 | |||||
11387 | Shadow->setAccess(UD->getAccess()); | ||||
11388 | if (Orig->isInvalidDecl() || UD->isInvalidDecl()) | ||||
11389 | Shadow->setInvalidDecl(); | ||||
11390 | |||||
11391 | Shadow->setPreviousDecl(PrevDecl); | ||||
11392 | |||||
11393 | if (S) | ||||
11394 | PushOnScopeChains(Shadow, S); | ||||
11395 | else | ||||
11396 | CurContext->addDecl(Shadow); | ||||
11397 | |||||
11398 | |||||
11399 | return Shadow; | ||||
11400 | } | ||||
11401 | |||||
11402 | /// Hides a using shadow declaration. This is required by the current | ||||
11403 | /// using-decl implementation when a resolvable using declaration in a | ||||
11404 | /// class is followed by a declaration which would hide or override | ||||
11405 | /// one or more of the using decl's targets; for example: | ||||
11406 | /// | ||||
11407 | /// struct Base { void foo(int); }; | ||||
11408 | /// struct Derived : Base { | ||||
11409 | /// using Base::foo; | ||||
11410 | /// void foo(int); | ||||
11411 | /// }; | ||||
11412 | /// | ||||
11413 | /// The governing language is C++03 [namespace.udecl]p12: | ||||
11414 | /// | ||||
11415 | /// When a using-declaration brings names from a base class into a | ||||
11416 | /// derived class scope, member functions in the derived class | ||||
11417 | /// override and/or hide member functions with the same name and | ||||
11418 | /// parameter types in a base class (rather than conflicting). | ||||
11419 | /// | ||||
11420 | /// There are two ways to implement this: | ||||
11421 | /// (1) optimistically create shadow decls when they're not hidden | ||||
11422 | /// by existing declarations, or | ||||
11423 | /// (2) don't create any shadow decls (or at least don't make them | ||||
11424 | /// visible) until we've fully parsed/instantiated the class. | ||||
11425 | /// The problem with (1) is that we might have to retroactively remove | ||||
11426 | /// a shadow decl, which requires several O(n) operations because the | ||||
11427 | /// decl structures are (very reasonably) not designed for removal. | ||||
11428 | /// (2) avoids this but is very fiddly and phase-dependent. | ||||
11429 | void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { | ||||
11430 | if (Shadow->getDeclName().getNameKind() == | ||||
11431 | DeclarationName::CXXConversionFunctionName) | ||||
11432 | cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); | ||||
11433 | |||||
11434 | // Remove it from the DeclContext... | ||||
11435 | Shadow->getDeclContext()->removeDecl(Shadow); | ||||
11436 | |||||
11437 | // ...and the scope, if applicable... | ||||
11438 | if (S) { | ||||
11439 | S->RemoveDecl(Shadow); | ||||
11440 | IdResolver.RemoveDecl(Shadow); | ||||
11441 | } | ||||
11442 | |||||
11443 | // ...and the using decl. | ||||
11444 | Shadow->getUsingDecl()->removeShadowDecl(Shadow); | ||||
11445 | |||||
11446 | // TODO: complain somehow if Shadow was used. It shouldn't | ||||
11447 | // be possible for this to happen, because...? | ||||
11448 | } | ||||
11449 | |||||
11450 | /// Find the base specifier for a base class with the given type. | ||||
11451 | static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, | ||||
11452 | QualType DesiredBase, | ||||
11453 | bool &AnyDependentBases) { | ||||
11454 | // Check whether the named type is a direct base class. | ||||
11455 | CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() | ||||
11456 | .getUnqualifiedType(); | ||||
11457 | for (auto &Base : Derived->bases()) { | ||||
11458 | CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); | ||||
11459 | if (CanonicalDesiredBase == BaseType) | ||||
11460 | return &Base; | ||||
11461 | if (BaseType->isDependentType()) | ||||
11462 | AnyDependentBases = true; | ||||
11463 | } | ||||
11464 | return nullptr; | ||||
11465 | } | ||||
11466 | |||||
11467 | namespace { | ||||
11468 | class UsingValidatorCCC final : public CorrectionCandidateCallback { | ||||
11469 | public: | ||||
11470 | UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, | ||||
11471 | NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) | ||||
11472 | : HasTypenameKeyword(HasTypenameKeyword), | ||||
11473 | IsInstantiation(IsInstantiation), OldNNS(NNS), | ||||
11474 | RequireMemberOf(RequireMemberOf) {} | ||||
11475 | |||||
11476 | bool ValidateCandidate(const TypoCorrection &Candidate) override { | ||||
11477 | NamedDecl *ND = Candidate.getCorrectionDecl(); | ||||
11478 | |||||
11479 | // Keywords are not valid here. | ||||
11480 | if (!ND || isa<NamespaceDecl>(ND)) | ||||
11481 | return false; | ||||
11482 | |||||
11483 | // Completely unqualified names are invalid for a 'using' declaration. | ||||
11484 | if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) | ||||
11485 | return false; | ||||
11486 | |||||
11487 | // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would | ||||
11488 | // reject. | ||||
11489 | |||||
11490 | if (RequireMemberOf) { | ||||
11491 | auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); | ||||
11492 | if (FoundRecord && FoundRecord->isInjectedClassName()) { | ||||
11493 | // No-one ever wants a using-declaration to name an injected-class-name | ||||
11494 | // of a base class, unless they're declaring an inheriting constructor. | ||||
11495 | ASTContext &Ctx = ND->getASTContext(); | ||||
11496 | if (!Ctx.getLangOpts().CPlusPlus11) | ||||
11497 | return false; | ||||
11498 | QualType FoundType = Ctx.getRecordType(FoundRecord); | ||||
11499 | |||||
11500 | // Check that the injected-class-name is named as a member of its own | ||||
11501 | // type; we don't want to suggest 'using Derived::Base;', since that | ||||
11502 | // means something else. | ||||
11503 | NestedNameSpecifier *Specifier = | ||||
11504 | Candidate.WillReplaceSpecifier() | ||||
11505 | ? Candidate.getCorrectionSpecifier() | ||||
11506 | : OldNNS; | ||||
11507 | if (!Specifier->getAsType() || | ||||
11508 | !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) | ||||
11509 | return false; | ||||
11510 | |||||
11511 | // Check that this inheriting constructor declaration actually names a | ||||
11512 | // direct base class of the current class. | ||||
11513 | bool AnyDependentBases = false; | ||||
11514 | if (!findDirectBaseWithType(RequireMemberOf, | ||||
11515 | Ctx.getRecordType(FoundRecord), | ||||
11516 | AnyDependentBases) && | ||||
11517 | !AnyDependentBases) | ||||
11518 | return false; | ||||
11519 | } else { | ||||
11520 | auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); | ||||
11521 | if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) | ||||
11522 | return false; | ||||
11523 | |||||
11524 | // FIXME: Check that the base class member is accessible? | ||||
11525 | } | ||||
11526 | } else { | ||||
11527 | auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); | ||||
11528 | if (FoundRecord && FoundRecord->isInjectedClassName()) | ||||
11529 | return false; | ||||
11530 | } | ||||
11531 | |||||
11532 | if (isa<TypeDecl>(ND)) | ||||
11533 | return HasTypenameKeyword || !IsInstantiation; | ||||
11534 | |||||
11535 | return !HasTypenameKeyword; | ||||
11536 | } | ||||
11537 | |||||
11538 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||
11539 | return std::make_unique<UsingValidatorCCC>(*this); | ||||
11540 | } | ||||
11541 | |||||
11542 | private: | ||||
11543 | bool HasTypenameKeyword; | ||||
11544 | bool IsInstantiation; | ||||
11545 | NestedNameSpecifier *OldNNS; | ||||
11546 | CXXRecordDecl *RequireMemberOf; | ||||
11547 | }; | ||||
11548 | } // end anonymous namespace | ||||
11549 | |||||
11550 | /// Builds a using declaration. | ||||
11551 | /// | ||||
11552 | /// \param IsInstantiation - Whether this call arises from an | ||||
11553 | /// instantiation of an unresolved using declaration. We treat | ||||
11554 | /// the lookup differently for these declarations. | ||||
11555 | NamedDecl *Sema::BuildUsingDeclaration( | ||||
11556 | Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, | ||||
11557 | bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, | ||||
11558 | DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, | ||||
11559 | const ParsedAttributesView &AttrList, bool IsInstantiation) { | ||||
11560 | assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")((!SS.isInvalid() && "Invalid CXXScopeSpec.") ? static_cast <void> (0) : __assert_fail ("!SS.isInvalid() && \"Invalid CXXScopeSpec.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 11560, __PRETTY_FUNCTION__)); | ||||
11561 | SourceLocation IdentLoc = NameInfo.getLoc(); | ||||
11562 | assert(IdentLoc.isValid() && "Invalid TargetName location.")((IdentLoc.isValid() && "Invalid TargetName location." ) ? static_cast<void> (0) : __assert_fail ("IdentLoc.isValid() && \"Invalid TargetName location.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 11562, __PRETTY_FUNCTION__)); | ||||
11563 | |||||
11564 | // FIXME: We ignore attributes for now. | ||||
11565 | |||||
11566 | // For an inheriting constructor declaration, the name of the using | ||||
11567 | // declaration is the name of a constructor in this class, not in the | ||||
11568 | // base class. | ||||
11569 | DeclarationNameInfo UsingName = NameInfo; | ||||
11570 | if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) | ||||
11571 | if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) | ||||
11572 | UsingName.setName(Context.DeclarationNames.getCXXConstructorName( | ||||
11573 | Context.getCanonicalType(Context.getRecordType(RD)))); | ||||
11574 | |||||
11575 | // Do the redeclaration lookup in the current scope. | ||||
11576 | LookupResult Previous(*this, UsingName, LookupUsingDeclName, | ||||
11577 | ForVisibleRedeclaration); | ||||
11578 | Previous.setHideTags(false); | ||||
11579 | if (S) { | ||||
11580 | LookupName(Previous, S); | ||||
11581 | |||||
11582 | // It is really dumb that we have to do this. | ||||
11583 | LookupResult::Filter F = Previous.makeFilter(); | ||||
11584 | while (F.hasNext()) { | ||||
11585 | NamedDecl *D = F.next(); | ||||
11586 | if (!isDeclInScope(D, CurContext, S)) | ||||
11587 | F.erase(); | ||||
11588 | // If we found a local extern declaration that's not ordinarily visible, | ||||
11589 | // and this declaration is being added to a non-block scope, ignore it. | ||||
11590 | // We're only checking for scope conflicts here, not also for violations | ||||
11591 | // of the linkage rules. | ||||
11592 | else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && | ||||
11593 | !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) | ||||
11594 | F.erase(); | ||||
11595 | } | ||||
11596 | F.done(); | ||||
11597 | } else { | ||||
11598 | assert(IsInstantiation && "no scope in non-instantiation")((IsInstantiation && "no scope in non-instantiation") ? static_cast<void> (0) : __assert_fail ("IsInstantiation && \"no scope in non-instantiation\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 11598, __PRETTY_FUNCTION__)); | ||||
11599 | if (CurContext->isRecord()) | ||||
11600 | LookupQualifiedName(Previous, CurContext); | ||||
11601 | else { | ||||
11602 | // No redeclaration check is needed here; in non-member contexts we | ||||
11603 | // diagnosed all possible conflicts with other using-declarations when | ||||
11604 | // building the template: | ||||
11605 | // | ||||
11606 | // For a dependent non-type using declaration, the only valid case is | ||||
11607 | // if we instantiate to a single enumerator. We check for conflicts | ||||
11608 | // between shadow declarations we introduce, and we check in the template | ||||
11609 | // definition for conflicts between a non-type using declaration and any | ||||
11610 | // other declaration, which together covers all cases. | ||||
11611 | // | ||||
11612 | // A dependent typename using declaration will never successfully | ||||
11613 | // instantiate, since it will always name a class member, so we reject | ||||
11614 | // that in the template definition. | ||||
11615 | } | ||||
11616 | } | ||||
11617 | |||||
11618 | // Check for invalid redeclarations. | ||||
11619 | if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, | ||||
11620 | SS, IdentLoc, Previous)) | ||||
11621 | return nullptr; | ||||
11622 | |||||
11623 | // Check for bad qualifiers. | ||||
11624 | if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, | ||||
11625 | IdentLoc)) | ||||
11626 | return nullptr; | ||||
11627 | |||||
11628 | DeclContext *LookupContext = computeDeclContext(SS); | ||||
11629 | NamedDecl *D; | ||||
11630 | NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); | ||||
11631 | if (!LookupContext || EllipsisLoc.isValid()) { | ||||
11632 | if (HasTypenameKeyword) { | ||||
11633 | // FIXME: not all declaration name kinds are legal here | ||||
11634 | D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, | ||||
11635 | UsingLoc, TypenameLoc, | ||||
11636 | QualifierLoc, | ||||
11637 | IdentLoc, NameInfo.getName(), | ||||
11638 | EllipsisLoc); | ||||
11639 | } else { | ||||
11640 | D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, | ||||
11641 | QualifierLoc, NameInfo, EllipsisLoc); | ||||
11642 | } | ||||
11643 | D->setAccess(AS); | ||||
11644 | CurContext->addDecl(D); | ||||
11645 | return D; | ||||
11646 | } | ||||
11647 | |||||
11648 | auto Build = [&](bool Invalid) { | ||||
11649 | UsingDecl *UD = | ||||
11650 | UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, | ||||
11651 | UsingName, HasTypenameKeyword); | ||||
11652 | UD->setAccess(AS); | ||||
11653 | CurContext->addDecl(UD); | ||||
11654 | UD->setInvalidDecl(Invalid); | ||||
11655 | return UD; | ||||
11656 | }; | ||||
11657 | auto BuildInvalid = [&]{ return Build(true); }; | ||||
11658 | auto BuildValid = [&]{ return Build(false); }; | ||||
11659 | |||||
11660 | if (RequireCompleteDeclContext(SS, LookupContext)) | ||||
11661 | return BuildInvalid(); | ||||
11662 | |||||
11663 | // Look up the target name. | ||||
11664 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | ||||
11665 | |||||
11666 | // Unlike most lookups, we don't always want to hide tag | ||||
11667 | // declarations: tag names are visible through the using declaration | ||||
11668 | // even if hidden by ordinary names, *except* in a dependent context | ||||
11669 | // where it's important for the sanity of two-phase lookup. | ||||
11670 | if (!IsInstantiation) | ||||
11671 | R.setHideTags(false); | ||||
11672 | |||||
11673 | // For the purposes of this lookup, we have a base object type | ||||
11674 | // equal to that of the current context. | ||||
11675 | if (CurContext->isRecord()) { | ||||
11676 | R.setBaseObjectType( | ||||
11677 | Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); | ||||
11678 | } | ||||
11679 | |||||
11680 | LookupQualifiedName(R, LookupContext); | ||||
11681 | |||||
11682 | // Try to correct typos if possible. If constructor name lookup finds no | ||||
11683 | // results, that means the named class has no explicit constructors, and we | ||||
11684 | // suppressed declaring implicit ones (probably because it's dependent or | ||||
11685 | // invalid). | ||||
11686 | if (R.empty() && | ||||
11687 | NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { | ||||
11688 | // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes | ||||
11689 | // it will believe that glibc provides a ::gets in cases where it does not, | ||||
11690 | // and will try to pull it into namespace std with a using-declaration. | ||||
11691 | // Just ignore the using-declaration in that case. | ||||
11692 | auto *II = NameInfo.getName().getAsIdentifierInfo(); | ||||
11693 | if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && | ||||
11694 | CurContext->isStdNamespace() && | ||||
11695 | isa<TranslationUnitDecl>(LookupContext) && | ||||
11696 | getSourceManager().isInSystemHeader(UsingLoc)) | ||||
11697 | return nullptr; | ||||
11698 | UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), | ||||
11699 | dyn_cast<CXXRecordDecl>(CurContext)); | ||||
11700 | if (TypoCorrection Corrected = | ||||
11701 | CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, | ||||
11702 | CTK_ErrorRecovery)) { | ||||
11703 | // We reject candidates where DroppedSpecifier == true, hence the | ||||
11704 | // literal '0' below. | ||||
11705 | diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) | ||||
11706 | << NameInfo.getName() << LookupContext << 0 | ||||
11707 | << SS.getRange()); | ||||
11708 | |||||
11709 | // If we picked a correction with no attached Decl we can't do anything | ||||
11710 | // useful with it, bail out. | ||||
11711 | NamedDecl *ND = Corrected.getCorrectionDecl(); | ||||
11712 | if (!ND) | ||||
11713 | return BuildInvalid(); | ||||
11714 | |||||
11715 | // If we corrected to an inheriting constructor, handle it as one. | ||||
11716 | auto *RD = dyn_cast<CXXRecordDecl>(ND); | ||||
11717 | if (RD && RD->isInjectedClassName()) { | ||||
11718 | // The parent of the injected class name is the class itself. | ||||
11719 | RD = cast<CXXRecordDecl>(RD->getParent()); | ||||
11720 | |||||
11721 | // Fix up the information we'll use to build the using declaration. | ||||
11722 | if (Corrected.WillReplaceSpecifier()) { | ||||
11723 | NestedNameSpecifierLocBuilder Builder; | ||||
11724 | Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), | ||||
11725 | QualifierLoc.getSourceRange()); | ||||
11726 | QualifierLoc = Builder.getWithLocInContext(Context); | ||||
11727 | } | ||||
11728 | |||||
11729 | // In this case, the name we introduce is the name of a derived class | ||||
11730 | // constructor. | ||||
11731 | auto *CurClass = cast<CXXRecordDecl>(CurContext); | ||||
11732 | UsingName.setName(Context.DeclarationNames.getCXXConstructorName( | ||||
11733 | Context.getCanonicalType(Context.getRecordType(CurClass)))); | ||||
11734 | UsingName.setNamedTypeInfo(nullptr); | ||||
11735 | for (auto *Ctor : LookupConstructors(RD)) | ||||
11736 | R.addDecl(Ctor); | ||||
11737 | R.resolveKind(); | ||||
11738 | } else { | ||||
11739 | // FIXME: Pick up all the declarations if we found an overloaded | ||||
11740 | // function. | ||||
11741 | UsingName.setName(ND->getDeclName()); | ||||
11742 | R.addDecl(ND); | ||||
11743 | } | ||||
11744 | } else { | ||||
11745 | Diag(IdentLoc, diag::err_no_member) | ||||
11746 | << NameInfo.getName() << LookupContext << SS.getRange(); | ||||
11747 | return BuildInvalid(); | ||||
11748 | } | ||||
11749 | } | ||||
11750 | |||||
11751 | if (R.isAmbiguous()) | ||||
11752 | return BuildInvalid(); | ||||
11753 | |||||
11754 | if (HasTypenameKeyword) { | ||||
11755 | // If we asked for a typename and got a non-type decl, error out. | ||||
11756 | if (!R.getAsSingle<TypeDecl>()) { | ||||
11757 | Diag(IdentLoc, diag::err_using_typename_non_type); | ||||
11758 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) | ||||
11759 | Diag((*I)->getUnderlyingDecl()->getLocation(), | ||||
11760 | diag::note_using_decl_target); | ||||
11761 | return BuildInvalid(); | ||||
11762 | } | ||||
11763 | } else { | ||||
11764 | // If we asked for a non-typename and we got a type, error out, | ||||
11765 | // but only if this is an instantiation of an unresolved using | ||||
11766 | // decl. Otherwise just silently find the type name. | ||||
11767 | if (IsInstantiation && R.getAsSingle<TypeDecl>()) { | ||||
11768 | Diag(IdentLoc, diag::err_using_dependent_value_is_type); | ||||
11769 | Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); | ||||
11770 | return BuildInvalid(); | ||||
11771 | } | ||||
11772 | } | ||||
11773 | |||||
11774 | // C++14 [namespace.udecl]p6: | ||||
11775 | // A using-declaration shall not name a namespace. | ||||
11776 | if (R.getAsSingle<NamespaceDecl>()) { | ||||
11777 | Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) | ||||
11778 | << SS.getRange(); | ||||
11779 | return BuildInvalid(); | ||||
11780 | } | ||||
11781 | |||||
11782 | // C++14 [namespace.udecl]p7: | ||||
11783 | // A using-declaration shall not name a scoped enumerator. | ||||
11784 | if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { | ||||
11785 | if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { | ||||
11786 | Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) | ||||
11787 | << SS.getRange(); | ||||
11788 | return BuildInvalid(); | ||||
11789 | } | ||||
11790 | } | ||||
11791 | |||||
11792 | UsingDecl *UD = BuildValid(); | ||||
11793 | |||||
11794 | // Some additional rules apply to inheriting constructors. | ||||
11795 | if (UsingName.getName().getNameKind() == | ||||
11796 | DeclarationName::CXXConstructorName) { | ||||
11797 | // Suppress access diagnostics; the access check is instead performed at the | ||||
11798 | // point of use for an inheriting constructor. | ||||
11799 | R.suppressDiagnostics(); | ||||
11800 | if (CheckInheritingConstructorUsingDecl(UD)) | ||||
11801 | return UD; | ||||
11802 | } | ||||
11803 | |||||
11804 | for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { | ||||
11805 | UsingShadowDecl *PrevDecl = nullptr; | ||||
11806 | if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) | ||||
11807 | BuildUsingShadowDecl(S, UD, *I, PrevDecl); | ||||
11808 | } | ||||
11809 | |||||
11810 | return UD; | ||||
11811 | } | ||||
11812 | |||||
11813 | NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, | ||||
11814 | ArrayRef<NamedDecl *> Expansions) { | ||||
11815 | assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||((isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa <UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa< UsingPackDecl>(InstantiatedFrom)) ? static_cast<void> (0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 11817, __PRETTY_FUNCTION__)) | ||||
11816 | isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||((isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa <UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa< UsingPackDecl>(InstantiatedFrom)) ? static_cast<void> (0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 11817, __PRETTY_FUNCTION__)) | ||||
11817 | isa<UsingPackDecl>(InstantiatedFrom))((isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa <UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa< UsingPackDecl>(InstantiatedFrom)) ? static_cast<void> (0) : __assert_fail ("isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || isa<UsingPackDecl>(InstantiatedFrom)" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 11817, __PRETTY_FUNCTION__)); | ||||
11818 | |||||
11819 | auto *UPD = | ||||
11820 | UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); | ||||
11821 | UPD->setAccess(InstantiatedFrom->getAccess()); | ||||
11822 | CurContext->addDecl(UPD); | ||||
11823 | return UPD; | ||||
11824 | } | ||||
11825 | |||||
11826 | /// Additional checks for a using declaration referring to a constructor name. | ||||
11827 | bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { | ||||
11828 | assert(!UD->hasTypename() && "expecting a constructor name")((!UD->hasTypename() && "expecting a constructor name" ) ? static_cast<void> (0) : __assert_fail ("!UD->hasTypename() && \"expecting a constructor name\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 11828, __PRETTY_FUNCTION__)); | ||||
11829 | |||||
11830 | const Type *SourceType = UD->getQualifier()->getAsType(); | ||||
11831 | assert(SourceType &&((SourceType && "Using decl naming constructor doesn't have type in scope spec." ) ? static_cast<void> (0) : __assert_fail ("SourceType && \"Using decl naming constructor doesn't have type in scope spec.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 11832, __PRETTY_FUNCTION__)) | ||||
11832 | "Using decl naming constructor doesn't have type in scope spec.")((SourceType && "Using decl naming constructor doesn't have type in scope spec." ) ? static_cast<void> (0) : __assert_fail ("SourceType && \"Using decl naming constructor doesn't have type in scope spec.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 11832, __PRETTY_FUNCTION__)); | ||||
11833 | CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); | ||||
11834 | |||||
11835 | // Check whether the named type is a direct base class. | ||||
11836 | bool AnyDependentBases = false; | ||||
11837 | auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), | ||||
11838 | AnyDependentBases); | ||||
11839 | if (!Base && !AnyDependentBases) { | ||||
11840 | Diag(UD->getUsingLoc(), | ||||
11841 | diag::err_using_decl_constructor_not_in_direct_base) | ||||
11842 | << UD->getNameInfo().getSourceRange() | ||||
11843 | << QualType(SourceType, 0) << TargetClass; | ||||
11844 | UD->setInvalidDecl(); | ||||
11845 | return true; | ||||
11846 | } | ||||
11847 | |||||
11848 | if (Base) | ||||
11849 | Base->setInheritConstructors(); | ||||
11850 | |||||
11851 | return false; | ||||
11852 | } | ||||
11853 | |||||
11854 | /// Checks that the given using declaration is not an invalid | ||||
11855 | /// redeclaration. Note that this is checking only for the using decl | ||||
11856 | /// itself, not for any ill-formedness among the UsingShadowDecls. | ||||
11857 | bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, | ||||
11858 | bool HasTypenameKeyword, | ||||
11859 | const CXXScopeSpec &SS, | ||||
11860 | SourceLocation NameLoc, | ||||
11861 | const LookupResult &Prev) { | ||||
11862 | NestedNameSpecifier *Qual = SS.getScopeRep(); | ||||
11863 | |||||
11864 | // C++03 [namespace.udecl]p8: | ||||
11865 | // C++0x [namespace.udecl]p10: | ||||
11866 | // A using-declaration is a declaration and can therefore be used | ||||
11867 | // repeatedly where (and only where) multiple declarations are | ||||
11868 | // allowed. | ||||
11869 | // | ||||
11870 | // That's in non-member contexts. | ||||
11871 | if (!CurContext->getRedeclContext()->isRecord()) { | ||||
11872 | // A dependent qualifier outside a class can only ever resolve to an | ||||
11873 | // enumeration type. Therefore it conflicts with any other non-type | ||||
11874 | // declaration in the same scope. | ||||
11875 | // FIXME: How should we check for dependent type-type conflicts at block | ||||
11876 | // scope? | ||||
11877 | if (Qual->isDependent() && !HasTypenameKeyword) { | ||||
11878 | for (auto *D : Prev) { | ||||
11879 | if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { | ||||
11880 | bool OldCouldBeEnumerator = | ||||
11881 | isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); | ||||
11882 | Diag(NameLoc, | ||||
11883 | OldCouldBeEnumerator ? diag::err_redefinition | ||||
11884 | : diag::err_redefinition_different_kind) | ||||
11885 | << Prev.getLookupName(); | ||||
11886 | Diag(D->getLocation(), diag::note_previous_definition); | ||||
11887 | return true; | ||||
11888 | } | ||||
11889 | } | ||||
11890 | } | ||||
11891 | return false; | ||||
11892 | } | ||||
11893 | |||||
11894 | for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { | ||||
11895 | NamedDecl *D = *I; | ||||
11896 | |||||
11897 | bool DTypename; | ||||
11898 | NestedNameSpecifier *DQual; | ||||
11899 | if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { | ||||
11900 | DTypename = UD->hasTypename(); | ||||
11901 | DQual = UD->getQualifier(); | ||||
11902 | } else if (UnresolvedUsingValueDecl *UD | ||||
11903 | = dyn_cast<UnresolvedUsingValueDecl>(D)) { | ||||
11904 | DTypename = false; | ||||
11905 | DQual = UD->getQualifier(); | ||||
11906 | } else if (UnresolvedUsingTypenameDecl *UD | ||||
11907 | = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { | ||||
11908 | DTypename = true; | ||||
11909 | DQual = UD->getQualifier(); | ||||
11910 | } else continue; | ||||
11911 | |||||
11912 | // using decls differ if one says 'typename' and the other doesn't. | ||||
11913 | // FIXME: non-dependent using decls? | ||||
11914 | if (HasTypenameKeyword != DTypename) continue; | ||||
11915 | |||||
11916 | // using decls differ if they name different scopes (but note that | ||||
11917 | // template instantiation can cause this check to trigger when it | ||||
11918 | // didn't before instantiation). | ||||
11919 | if (Context.getCanonicalNestedNameSpecifier(Qual) != | ||||
11920 | Context.getCanonicalNestedNameSpecifier(DQual)) | ||||
11921 | continue; | ||||
11922 | |||||
11923 | Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); | ||||
11924 | Diag(D->getLocation(), diag::note_using_decl) << 1; | ||||
11925 | return true; | ||||
11926 | } | ||||
11927 | |||||
11928 | return false; | ||||
11929 | } | ||||
11930 | |||||
11931 | |||||
11932 | /// Checks that the given nested-name qualifier used in a using decl | ||||
11933 | /// in the current context is appropriately related to the current | ||||
11934 | /// scope. If an error is found, diagnoses it and returns true. | ||||
11935 | bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, | ||||
11936 | bool HasTypename, | ||||
11937 | const CXXScopeSpec &SS, | ||||
11938 | const DeclarationNameInfo &NameInfo, | ||||
11939 | SourceLocation NameLoc) { | ||||
11940 | DeclContext *NamedContext = computeDeclContext(SS); | ||||
11941 | |||||
11942 | if (!CurContext->isRecord()) { | ||||
11943 | // C++03 [namespace.udecl]p3: | ||||
11944 | // C++0x [namespace.udecl]p8: | ||||
11945 | // A using-declaration for a class member shall be a member-declaration. | ||||
11946 | |||||
11947 | // If we weren't able to compute a valid scope, it might validly be a | ||||
11948 | // dependent class scope or a dependent enumeration unscoped scope. If | ||||
11949 | // we have a 'typename' keyword, the scope must resolve to a class type. | ||||
11950 | if ((HasTypename && !NamedContext) || | ||||
11951 | (NamedContext && NamedContext->getRedeclContext()->isRecord())) { | ||||
11952 | auto *RD = NamedContext | ||||
11953 | ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) | ||||
11954 | : nullptr; | ||||
11955 | if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) | ||||
11956 | RD = nullptr; | ||||
11957 | |||||
11958 | Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) | ||||
11959 | << SS.getRange(); | ||||
11960 | |||||
11961 | // If we have a complete, non-dependent source type, try to suggest a | ||||
11962 | // way to get the same effect. | ||||
11963 | if (!RD) | ||||
11964 | return true; | ||||
11965 | |||||
11966 | // Find what this using-declaration was referring to. | ||||
11967 | LookupResult R(*this, NameInfo, LookupOrdinaryName); | ||||
11968 | R.setHideTags(false); | ||||
11969 | R.suppressDiagnostics(); | ||||
11970 | LookupQualifiedName(R, RD); | ||||
11971 | |||||
11972 | if (R.getAsSingle<TypeDecl>()) { | ||||
11973 | if (getLangOpts().CPlusPlus11) { | ||||
11974 | // Convert 'using X::Y;' to 'using Y = X::Y;'. | ||||
11975 | Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) | ||||
11976 | << 0 // alias declaration | ||||
11977 | << FixItHint::CreateInsertion(SS.getBeginLoc(), | ||||
11978 | NameInfo.getName().getAsString() + | ||||
11979 | " = "); | ||||
11980 | } else { | ||||
11981 | // Convert 'using X::Y;' to 'typedef X::Y Y;'. | ||||
11982 | SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); | ||||
11983 | Diag(InsertLoc, diag::note_using_decl_class_member_workaround) | ||||
11984 | << 1 // typedef declaration | ||||
11985 | << FixItHint::CreateReplacement(UsingLoc, "typedef") | ||||
11986 | << FixItHint::CreateInsertion( | ||||
11987 | InsertLoc, " " + NameInfo.getName().getAsString()); | ||||
11988 | } | ||||
11989 | } else if (R.getAsSingle<VarDecl>()) { | ||||
11990 | // Don't provide a fixit outside C++11 mode; we don't want to suggest | ||||
11991 | // repeating the type of the static data member here. | ||||
11992 | FixItHint FixIt; | ||||
11993 | if (getLangOpts().CPlusPlus11) { | ||||
11994 | // Convert 'using X::Y;' to 'auto &Y = X::Y;'. | ||||
11995 | FixIt = FixItHint::CreateReplacement( | ||||
11996 | UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); | ||||
11997 | } | ||||
11998 | |||||
11999 | Diag(UsingLoc, diag::note_using_decl_class_member_workaround) | ||||
12000 | << 2 // reference declaration | ||||
12001 | << FixIt; | ||||
12002 | } else if (R.getAsSingle<EnumConstantDecl>()) { | ||||
12003 | // Don't provide a fixit outside C++11 mode; we don't want to suggest | ||||
12004 | // repeating the type of the enumeration here, and we can't do so if | ||||
12005 | // the type is anonymous. | ||||
12006 | FixItHint FixIt; | ||||
12007 | if (getLangOpts().CPlusPlus11) { | ||||
12008 | // Convert 'using X::Y;' to 'auto &Y = X::Y;'. | ||||
12009 | FixIt = FixItHint::CreateReplacement( | ||||
12010 | UsingLoc, | ||||
12011 | "constexpr auto " + NameInfo.getName().getAsString() + " = "); | ||||
12012 | } | ||||
12013 | |||||
12014 | Diag(UsingLoc, diag::note_using_decl_class_member_workaround) | ||||
12015 | << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable | ||||
12016 | << FixIt; | ||||
12017 | } | ||||
12018 | return true; | ||||
12019 | } | ||||
12020 | |||||
12021 | // Otherwise, this might be valid. | ||||
12022 | return false; | ||||
12023 | } | ||||
12024 | |||||
12025 | // The current scope is a record. | ||||
12026 | |||||
12027 | // If the named context is dependent, we can't decide much. | ||||
12028 | if (!NamedContext) { | ||||
12029 | // FIXME: in C++0x, we can diagnose if we can prove that the | ||||
12030 | // nested-name-specifier does not refer to a base class, which is | ||||
12031 | // still possible in some cases. | ||||
12032 | |||||
12033 | // Otherwise we have to conservatively report that things might be | ||||
12034 | // okay. | ||||
12035 | return false; | ||||
12036 | } | ||||
12037 | |||||
12038 | if (!NamedContext->isRecord()) { | ||||
12039 | // Ideally this would point at the last name in the specifier, | ||||
12040 | // but we don't have that level of source info. | ||||
12041 | Diag(SS.getRange().getBegin(), | ||||
12042 | diag::err_using_decl_nested_name_specifier_is_not_class) | ||||
12043 | << SS.getScopeRep() << SS.getRange(); | ||||
12044 | return true; | ||||
12045 | } | ||||
12046 | |||||
12047 | if (!NamedContext->isDependentContext() && | ||||
12048 | RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) | ||||
12049 | return true; | ||||
12050 | |||||
12051 | if (getLangOpts().CPlusPlus11) { | ||||
12052 | // C++11 [namespace.udecl]p3: | ||||
12053 | // In a using-declaration used as a member-declaration, the | ||||
12054 | // nested-name-specifier shall name a base class of the class | ||||
12055 | // being defined. | ||||
12056 | |||||
12057 | if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( | ||||
12058 | cast<CXXRecordDecl>(NamedContext))) { | ||||
12059 | if (CurContext == NamedContext) { | ||||
12060 | Diag(NameLoc, | ||||
12061 | diag::err_using_decl_nested_name_specifier_is_current_class) | ||||
12062 | << SS.getRange(); | ||||
12063 | return true; | ||||
12064 | } | ||||
12065 | |||||
12066 | if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { | ||||
12067 | Diag(SS.getRange().getBegin(), | ||||
12068 | diag::err_using_decl_nested_name_specifier_is_not_base_class) | ||||
12069 | << SS.getScopeRep() | ||||
12070 | << cast<CXXRecordDecl>(CurContext) | ||||
12071 | << SS.getRange(); | ||||
12072 | } | ||||
12073 | return true; | ||||
12074 | } | ||||
12075 | |||||
12076 | return false; | ||||
12077 | } | ||||
12078 | |||||
12079 | // C++03 [namespace.udecl]p4: | ||||
12080 | // A using-declaration used as a member-declaration shall refer | ||||
12081 | // to a member of a base class of the class being defined [etc.]. | ||||
12082 | |||||
12083 | // Salient point: SS doesn't have to name a base class as long as | ||||
12084 | // lookup only finds members from base classes. Therefore we can | ||||
12085 | // diagnose here only if we can prove that that can't happen, | ||||
12086 | // i.e. if the class hierarchies provably don't intersect. | ||||
12087 | |||||
12088 | // TODO: it would be nice if "definitely valid" results were cached | ||||
12089 | // in the UsingDecl and UsingShadowDecl so that these checks didn't | ||||
12090 | // need to be repeated. | ||||
12091 | |||||
12092 | llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; | ||||
12093 | auto Collect = [&Bases](const CXXRecordDecl *Base) { | ||||
12094 | Bases.insert(Base); | ||||
12095 | return true; | ||||
12096 | }; | ||||
12097 | |||||
12098 | // Collect all bases. Return false if we find a dependent base. | ||||
12099 | if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) | ||||
12100 | return false; | ||||
12101 | |||||
12102 | // Returns true if the base is dependent or is one of the accumulated base | ||||
12103 | // classes. | ||||
12104 | auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { | ||||
12105 | return !Bases.count(Base); | ||||
12106 | }; | ||||
12107 | |||||
12108 | // Return false if the class has a dependent base or if it or one | ||||
12109 | // of its bases is present in the base set of the current context. | ||||
12110 | if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || | ||||
12111 | !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) | ||||
12112 | return false; | ||||
12113 | |||||
12114 | Diag(SS.getRange().getBegin(), | ||||
12115 | diag::err_using_decl_nested_name_specifier_is_not_base_class) | ||||
12116 | << SS.getScopeRep() | ||||
12117 | << cast<CXXRecordDecl>(CurContext) | ||||
12118 | << SS.getRange(); | ||||
12119 | |||||
12120 | return true; | ||||
12121 | } | ||||
12122 | |||||
12123 | Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, | ||||
12124 | MultiTemplateParamsArg TemplateParamLists, | ||||
12125 | SourceLocation UsingLoc, UnqualifiedId &Name, | ||||
12126 | const ParsedAttributesView &AttrList, | ||||
12127 | TypeResult Type, Decl *DeclFromDeclSpec) { | ||||
12128 | // Skip up to the relevant declaration scope. | ||||
12129 | while (S->isTemplateParamScope()) | ||||
12130 | S = S->getParent(); | ||||
12131 | assert((S->getFlags() & Scope::DeclScope) &&(((S->getFlags() & Scope::DeclScope) && "got alias-declaration outside of declaration scope" ) ? static_cast<void> (0) : __assert_fail ("(S->getFlags() & Scope::DeclScope) && \"got alias-declaration outside of declaration scope\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12132, __PRETTY_FUNCTION__)) | ||||
12132 | "got alias-declaration outside of declaration scope")(((S->getFlags() & Scope::DeclScope) && "got alias-declaration outside of declaration scope" ) ? static_cast<void> (0) : __assert_fail ("(S->getFlags() & Scope::DeclScope) && \"got alias-declaration outside of declaration scope\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12132, __PRETTY_FUNCTION__)); | ||||
12133 | |||||
12134 | if (Type.isInvalid()) | ||||
12135 | return nullptr; | ||||
12136 | |||||
12137 | bool Invalid = false; | ||||
12138 | DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); | ||||
12139 | TypeSourceInfo *TInfo = nullptr; | ||||
12140 | GetTypeFromParser(Type.get(), &TInfo); | ||||
12141 | |||||
12142 | if (DiagnoseClassNameShadow(CurContext, NameInfo)) | ||||
12143 | return nullptr; | ||||
12144 | |||||
12145 | if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, | ||||
12146 | UPPC_DeclarationType)) { | ||||
12147 | Invalid = true; | ||||
12148 | TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, | ||||
12149 | TInfo->getTypeLoc().getBeginLoc()); | ||||
12150 | } | ||||
12151 | |||||
12152 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||
12153 | TemplateParamLists.size() | ||||
12154 | ? forRedeclarationInCurContext() | ||||
12155 | : ForVisibleRedeclaration); | ||||
12156 | LookupName(Previous, S); | ||||
12157 | |||||
12158 | // Warn about shadowing the name of a template parameter. | ||||
12159 | if (Previous.isSingleResult() && | ||||
12160 | Previous.getFoundDecl()->isTemplateParameter()) { | ||||
12161 | DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); | ||||
12162 | Previous.clear(); | ||||
12163 | } | ||||
12164 | |||||
12165 | assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&((Name.Kind == UnqualifiedIdKind::IK_Identifier && "name in alias declaration must be an identifier" ) ? static_cast<void> (0) : __assert_fail ("Name.Kind == UnqualifiedIdKind::IK_Identifier && \"name in alias declaration must be an identifier\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12166, __PRETTY_FUNCTION__)) | ||||
12166 | "name in alias declaration must be an identifier")((Name.Kind == UnqualifiedIdKind::IK_Identifier && "name in alias declaration must be an identifier" ) ? static_cast<void> (0) : __assert_fail ("Name.Kind == UnqualifiedIdKind::IK_Identifier && \"name in alias declaration must be an identifier\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12166, __PRETTY_FUNCTION__)); | ||||
12167 | TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, | ||||
12168 | Name.StartLocation, | ||||
12169 | Name.Identifier, TInfo); | ||||
12170 | |||||
12171 | NewTD->setAccess(AS); | ||||
12172 | |||||
12173 | if (Invalid) | ||||
12174 | NewTD->setInvalidDecl(); | ||||
12175 | |||||
12176 | ProcessDeclAttributeList(S, NewTD, AttrList); | ||||
12177 | AddPragmaAttributes(S, NewTD); | ||||
12178 | |||||
12179 | CheckTypedefForVariablyModifiedType(S, NewTD); | ||||
12180 | Invalid |= NewTD->isInvalidDecl(); | ||||
12181 | |||||
12182 | bool Redeclaration = false; | ||||
12183 | |||||
12184 | NamedDecl *NewND; | ||||
12185 | if (TemplateParamLists.size()) { | ||||
12186 | TypeAliasTemplateDecl *OldDecl = nullptr; | ||||
12187 | TemplateParameterList *OldTemplateParams = nullptr; | ||||
12188 | |||||
12189 | if (TemplateParamLists.size() != 1) { | ||||
12190 | Diag(UsingLoc, diag::err_alias_template_extra_headers) | ||||
12191 | << SourceRange(TemplateParamLists[1]->getTemplateLoc(), | ||||
12192 | TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); | ||||
12193 | } | ||||
12194 | TemplateParameterList *TemplateParams = TemplateParamLists[0]; | ||||
12195 | |||||
12196 | // Check that we can declare a template here. | ||||
12197 | if (CheckTemplateDeclScope(S, TemplateParams)) | ||||
12198 | return nullptr; | ||||
12199 | |||||
12200 | // Only consider previous declarations in the same scope. | ||||
12201 | FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, | ||||
12202 | /*ExplicitInstantiationOrSpecialization*/false); | ||||
12203 | if (!Previous.empty()) { | ||||
12204 | Redeclaration = true; | ||||
12205 | |||||
12206 | OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); | ||||
12207 | if (!OldDecl && !Invalid) { | ||||
12208 | Diag(UsingLoc, diag::err_redefinition_different_kind) | ||||
12209 | << Name.Identifier; | ||||
12210 | |||||
12211 | NamedDecl *OldD = Previous.getRepresentativeDecl(); | ||||
12212 | if (OldD->getLocation().isValid()) | ||||
12213 | Diag(OldD->getLocation(), diag::note_previous_definition); | ||||
12214 | |||||
12215 | Invalid = true; | ||||
12216 | } | ||||
12217 | |||||
12218 | if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { | ||||
12219 | if (TemplateParameterListsAreEqual(TemplateParams, | ||||
12220 | OldDecl->getTemplateParameters(), | ||||
12221 | /*Complain=*/true, | ||||
12222 | TPL_TemplateMatch)) | ||||
12223 | OldTemplateParams = | ||||
12224 | OldDecl->getMostRecentDecl()->getTemplateParameters(); | ||||
12225 | else | ||||
12226 | Invalid = true; | ||||
12227 | |||||
12228 | TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); | ||||
12229 | if (!Invalid && | ||||
12230 | !Context.hasSameType(OldTD->getUnderlyingType(), | ||||
12231 | NewTD->getUnderlyingType())) { | ||||
12232 | // FIXME: The C++0x standard does not clearly say this is ill-formed, | ||||
12233 | // but we can't reasonably accept it. | ||||
12234 | Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) | ||||
12235 | << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); | ||||
12236 | if (OldTD->getLocation().isValid()) | ||||
12237 | Diag(OldTD->getLocation(), diag::note_previous_definition); | ||||
12238 | Invalid = true; | ||||
12239 | } | ||||
12240 | } | ||||
12241 | } | ||||
12242 | |||||
12243 | // Merge any previous default template arguments into our parameters, | ||||
12244 | // and check the parameter list. | ||||
12245 | if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, | ||||
12246 | TPC_TypeAliasTemplate)) | ||||
12247 | return nullptr; | ||||
12248 | |||||
12249 | TypeAliasTemplateDecl *NewDecl = | ||||
12250 | TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, | ||||
12251 | Name.Identifier, TemplateParams, | ||||
12252 | NewTD); | ||||
12253 | NewTD->setDescribedAliasTemplate(NewDecl); | ||||
12254 | |||||
12255 | NewDecl->setAccess(AS); | ||||
12256 | |||||
12257 | if (Invalid) | ||||
12258 | NewDecl->setInvalidDecl(); | ||||
12259 | else if (OldDecl) { | ||||
12260 | NewDecl->setPreviousDecl(OldDecl); | ||||
12261 | CheckRedeclarationModuleOwnership(NewDecl, OldDecl); | ||||
12262 | } | ||||
12263 | |||||
12264 | NewND = NewDecl; | ||||
12265 | } else { | ||||
12266 | if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { | ||||
12267 | setTagNameForLinkagePurposes(TD, NewTD); | ||||
12268 | handleTagNumbering(TD, S); | ||||
12269 | } | ||||
12270 | ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); | ||||
12271 | NewND = NewTD; | ||||
12272 | } | ||||
12273 | |||||
12274 | PushOnScopeChains(NewND, S); | ||||
12275 | ActOnDocumentableDecl(NewND); | ||||
12276 | return NewND; | ||||
12277 | } | ||||
12278 | |||||
12279 | Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, | ||||
12280 | SourceLocation AliasLoc, | ||||
12281 | IdentifierInfo *Alias, CXXScopeSpec &SS, | ||||
12282 | SourceLocation IdentLoc, | ||||
12283 | IdentifierInfo *Ident) { | ||||
12284 | |||||
12285 | // Lookup the namespace name. | ||||
12286 | LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); | ||||
12287 | LookupParsedName(R, S, &SS); | ||||
12288 | |||||
12289 | if (R.isAmbiguous()) | ||||
12290 | return nullptr; | ||||
12291 | |||||
12292 | if (R.empty()) { | ||||
12293 | if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { | ||||
12294 | Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); | ||||
12295 | return nullptr; | ||||
12296 | } | ||||
12297 | } | ||||
12298 | assert(!R.isAmbiguous() && !R.empty())((!R.isAmbiguous() && !R.empty()) ? static_cast<void > (0) : __assert_fail ("!R.isAmbiguous() && !R.empty()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12298, __PRETTY_FUNCTION__)); | ||||
12299 | NamedDecl *ND = R.getRepresentativeDecl(); | ||||
12300 | |||||
12301 | // Check if we have a previous declaration with the same name. | ||||
12302 | LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, | ||||
12303 | ForVisibleRedeclaration); | ||||
12304 | LookupName(PrevR, S); | ||||
12305 | |||||
12306 | // Check we're not shadowing a template parameter. | ||||
12307 | if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { | ||||
12308 | DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); | ||||
12309 | PrevR.clear(); | ||||
12310 | } | ||||
12311 | |||||
12312 | // Filter out any other lookup result from an enclosing scope. | ||||
12313 | FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, | ||||
12314 | /*AllowInlineNamespace*/false); | ||||
12315 | |||||
12316 | // Find the previous declaration and check that we can redeclare it. | ||||
12317 | NamespaceAliasDecl *Prev = nullptr; | ||||
12318 | if (PrevR.isSingleResult()) { | ||||
12319 | NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); | ||||
12320 | if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { | ||||
12321 | // We already have an alias with the same name that points to the same | ||||
12322 | // namespace; check that it matches. | ||||
12323 | if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { | ||||
12324 | Prev = AD; | ||||
12325 | } else if (isVisible(PrevDecl)) { | ||||
12326 | Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) | ||||
12327 | << Alias; | ||||
12328 | Diag(AD->getLocation(), diag::note_previous_namespace_alias) | ||||
12329 | << AD->getNamespace(); | ||||
12330 | return nullptr; | ||||
12331 | } | ||||
12332 | } else if (isVisible(PrevDecl)) { | ||||
12333 | unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) | ||||
12334 | ? diag::err_redefinition | ||||
12335 | : diag::err_redefinition_different_kind; | ||||
12336 | Diag(AliasLoc, DiagID) << Alias; | ||||
12337 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); | ||||
12338 | return nullptr; | ||||
12339 | } | ||||
12340 | } | ||||
12341 | |||||
12342 | // The use of a nested name specifier may trigger deprecation warnings. | ||||
12343 | DiagnoseUseOfDecl(ND, IdentLoc); | ||||
12344 | |||||
12345 | NamespaceAliasDecl *AliasDecl = | ||||
12346 | NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, | ||||
12347 | Alias, SS.getWithLocInContext(Context), | ||||
12348 | IdentLoc, ND); | ||||
12349 | if (Prev) | ||||
12350 | AliasDecl->setPreviousDecl(Prev); | ||||
12351 | |||||
12352 | PushOnScopeChains(AliasDecl, S); | ||||
12353 | return AliasDecl; | ||||
12354 | } | ||||
12355 | |||||
12356 | namespace { | ||||
12357 | struct SpecialMemberExceptionSpecInfo | ||||
12358 | : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { | ||||
12359 | SourceLocation Loc; | ||||
12360 | Sema::ImplicitExceptionSpecification ExceptSpec; | ||||
12361 | |||||
12362 | SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, | ||||
12363 | Sema::CXXSpecialMember CSM, | ||||
12364 | Sema::InheritedConstructorInfo *ICI, | ||||
12365 | SourceLocation Loc) | ||||
12366 | : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} | ||||
12367 | |||||
12368 | bool visitBase(CXXBaseSpecifier *Base); | ||||
12369 | bool visitField(FieldDecl *FD); | ||||
12370 | |||||
12371 | void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, | ||||
12372 | unsigned Quals); | ||||
12373 | |||||
12374 | void visitSubobjectCall(Subobject Subobj, | ||||
12375 | Sema::SpecialMemberOverloadResult SMOR); | ||||
12376 | }; | ||||
12377 | } | ||||
12378 | |||||
12379 | bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { | ||||
12380 | auto *RT = Base->getType()->getAs<RecordType>(); | ||||
12381 | if (!RT) | ||||
12382 | return false; | ||||
12383 | |||||
12384 | auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); | ||||
12385 | Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); | ||||
12386 | if (auto *BaseCtor = SMOR.getMethod()) { | ||||
12387 | visitSubobjectCall(Base, BaseCtor); | ||||
12388 | return false; | ||||
12389 | } | ||||
12390 | |||||
12391 | visitClassSubobject(BaseClass, Base, 0); | ||||
12392 | return false; | ||||
12393 | } | ||||
12394 | |||||
12395 | bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { | ||||
12396 | if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { | ||||
12397 | Expr *E = FD->getInClassInitializer(); | ||||
12398 | if (!E) | ||||
12399 | // FIXME: It's a little wasteful to build and throw away a | ||||
12400 | // CXXDefaultInitExpr here. | ||||
12401 | // FIXME: We should have a single context note pointing at Loc, and | ||||
12402 | // this location should be MD->getLocation() instead, since that's | ||||
12403 | // the location where we actually use the default init expression. | ||||
12404 | E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); | ||||
12405 | if (E) | ||||
12406 | ExceptSpec.CalledExpr(E); | ||||
12407 | } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) | ||||
12408 | ->getAs<RecordType>()) { | ||||
12409 | visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, | ||||
12410 | FD->getType().getCVRQualifiers()); | ||||
12411 | } | ||||
12412 | return false; | ||||
12413 | } | ||||
12414 | |||||
12415 | void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, | ||||
12416 | Subobject Subobj, | ||||
12417 | unsigned Quals) { | ||||
12418 | FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); | ||||
12419 | bool IsMutable = Field && Field->isMutable(); | ||||
12420 | visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); | ||||
12421 | } | ||||
12422 | |||||
12423 | void SpecialMemberExceptionSpecInfo::visitSubobjectCall( | ||||
12424 | Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { | ||||
12425 | // Note, if lookup fails, it doesn't matter what exception specification we | ||||
12426 | // choose because the special member will be deleted. | ||||
12427 | if (CXXMethodDecl *MD = SMOR.getMethod()) | ||||
12428 | ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); | ||||
12429 | } | ||||
12430 | |||||
12431 | bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { | ||||
12432 | llvm::APSInt Result; | ||||
12433 | ExprResult Converted = CheckConvertedConstantExpression( | ||||
12434 | ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); | ||||
12435 | ExplicitSpec.setExpr(Converted.get()); | ||||
12436 | if (Converted.isUsable() && !Converted.get()->isValueDependent()) { | ||||
12437 | ExplicitSpec.setKind(Result.getBoolValue() | ||||
12438 | ? ExplicitSpecKind::ResolvedTrue | ||||
12439 | : ExplicitSpecKind::ResolvedFalse); | ||||
12440 | return true; | ||||
12441 | } | ||||
12442 | ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); | ||||
12443 | return false; | ||||
12444 | } | ||||
12445 | |||||
12446 | ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { | ||||
12447 | ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); | ||||
12448 | if (!ExplicitExpr->isTypeDependent()) | ||||
12449 | tryResolveExplicitSpecifier(ES); | ||||
12450 | return ES; | ||||
12451 | } | ||||
12452 | |||||
12453 | static Sema::ImplicitExceptionSpecification | ||||
12454 | ComputeDefaultedSpecialMemberExceptionSpec( | ||||
12455 | Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, | ||||
12456 | Sema::InheritedConstructorInfo *ICI) { | ||||
12457 | ComputingExceptionSpec CES(S, MD, Loc); | ||||
12458 | |||||
12459 | CXXRecordDecl *ClassDecl = MD->getParent(); | ||||
12460 | |||||
12461 | // C++ [except.spec]p14: | ||||
12462 | // An implicitly declared special member function (Clause 12) shall have an | ||||
12463 | // exception-specification. [...] | ||||
12464 | SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); | ||||
12465 | if (ClassDecl->isInvalidDecl()) | ||||
12466 | return Info.ExceptSpec; | ||||
12467 | |||||
12468 | // FIXME: If this diagnostic fires, we're probably missing a check for | ||||
12469 | // attempting to resolve an exception specification before it's known | ||||
12470 | // at a higher level. | ||||
12471 | if (S.RequireCompleteType(MD->getLocation(), | ||||
12472 | S.Context.getRecordType(ClassDecl), | ||||
12473 | diag::err_exception_spec_incomplete_type)) | ||||
12474 | return Info.ExceptSpec; | ||||
12475 | |||||
12476 | // C++1z [except.spec]p7: | ||||
12477 | // [Look for exceptions thrown by] a constructor selected [...] to | ||||
12478 | // initialize a potentially constructed subobject, | ||||
12479 | // C++1z [except.spec]p8: | ||||
12480 | // The exception specification for an implicitly-declared destructor, or a | ||||
12481 | // destructor without a noexcept-specifier, is potentially-throwing if and | ||||
12482 | // only if any of the destructors for any of its potentially constructed | ||||
12483 | // subojects is potentially throwing. | ||||
12484 | // FIXME: We respect the first rule but ignore the "potentially constructed" | ||||
12485 | // in the second rule to resolve a core issue (no number yet) that would have | ||||
12486 | // us reject: | ||||
12487 | // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; | ||||
12488 | // struct B : A {}; | ||||
12489 | // struct C : B { void f(); }; | ||||
12490 | // ... due to giving B::~B() a non-throwing exception specification. | ||||
12491 | Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases | ||||
12492 | : Info.VisitAllBases); | ||||
12493 | |||||
12494 | return Info.ExceptSpec; | ||||
12495 | } | ||||
12496 | |||||
12497 | namespace { | ||||
12498 | /// RAII object to register a special member as being currently declared. | ||||
12499 | struct DeclaringSpecialMember { | ||||
12500 | Sema &S; | ||||
12501 | Sema::SpecialMemberDecl D; | ||||
12502 | Sema::ContextRAII SavedContext; | ||||
12503 | bool WasAlreadyBeingDeclared; | ||||
12504 | |||||
12505 | DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) | ||||
12506 | : S(S), D(RD, CSM), SavedContext(S, RD) { | ||||
12507 | WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; | ||||
12508 | if (WasAlreadyBeingDeclared) | ||||
12509 | // This almost never happens, but if it does, ensure that our cache | ||||
12510 | // doesn't contain a stale result. | ||||
12511 | S.SpecialMemberCache.clear(); | ||||
12512 | else { | ||||
12513 | // Register a note to be produced if we encounter an error while | ||||
12514 | // declaring the special member. | ||||
12515 | Sema::CodeSynthesisContext Ctx; | ||||
12516 | Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; | ||||
12517 | // FIXME: We don't have a location to use here. Using the class's | ||||
12518 | // location maintains the fiction that we declare all special members | ||||
12519 | // with the class, but (1) it's not clear that lying about that helps our | ||||
12520 | // users understand what's going on, and (2) there may be outer contexts | ||||
12521 | // on the stack (some of which are relevant) and printing them exposes | ||||
12522 | // our lies. | ||||
12523 | Ctx.PointOfInstantiation = RD->getLocation(); | ||||
12524 | Ctx.Entity = RD; | ||||
12525 | Ctx.SpecialMember = CSM; | ||||
12526 | S.pushCodeSynthesisContext(Ctx); | ||||
12527 | } | ||||
12528 | } | ||||
12529 | ~DeclaringSpecialMember() { | ||||
12530 | if (!WasAlreadyBeingDeclared) { | ||||
12531 | S.SpecialMembersBeingDeclared.erase(D); | ||||
12532 | S.popCodeSynthesisContext(); | ||||
12533 | } | ||||
12534 | } | ||||
12535 | |||||
12536 | /// Are we already trying to declare this special member? | ||||
12537 | bool isAlreadyBeingDeclared() const { | ||||
12538 | return WasAlreadyBeingDeclared; | ||||
12539 | } | ||||
12540 | }; | ||||
12541 | } | ||||
12542 | |||||
12543 | void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { | ||||
12544 | // Look up any existing declarations, but don't trigger declaration of all | ||||
12545 | // implicit special members with this name. | ||||
12546 | DeclarationName Name = FD->getDeclName(); | ||||
12547 | LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, | ||||
12548 | ForExternalRedeclaration); | ||||
12549 | for (auto *D : FD->getParent()->lookup(Name)) | ||||
12550 | if (auto *Acceptable = R.getAcceptableDecl(D)) | ||||
12551 | R.addDecl(Acceptable); | ||||
12552 | R.resolveKind(); | ||||
12553 | R.suppressDiagnostics(); | ||||
12554 | |||||
12555 | CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); | ||||
12556 | } | ||||
12557 | |||||
12558 | void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, | ||||
12559 | QualType ResultTy, | ||||
12560 | ArrayRef<QualType> Args) { | ||||
12561 | // Build an exception specification pointing back at this constructor. | ||||
12562 | FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); | ||||
12563 | |||||
12564 | LangAS AS = getDefaultCXXMethodAddrSpace(); | ||||
12565 | if (AS != LangAS::Default) { | ||||
12566 | EPI.TypeQuals.addAddressSpace(AS); | ||||
12567 | } | ||||
12568 | |||||
12569 | auto QT = Context.getFunctionType(ResultTy, Args, EPI); | ||||
12570 | SpecialMem->setType(QT); | ||||
12571 | } | ||||
12572 | |||||
12573 | CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( | ||||
12574 | CXXRecordDecl *ClassDecl) { | ||||
12575 | // C++ [class.ctor]p5: | ||||
12576 | // A default constructor for a class X is a constructor of class X | ||||
12577 | // that can be called without an argument. If there is no | ||||
12578 | // user-declared constructor for class X, a default constructor is | ||||
12579 | // implicitly declared. An implicitly-declared default constructor | ||||
12580 | // is an inline public member of its class. | ||||
12581 | assert(ClassDecl->needsImplicitDefaultConstructor() &&((ClassDecl->needsImplicitDefaultConstructor() && "Should not build implicit default constructor!" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl->needsImplicitDefaultConstructor() && \"Should not build implicit default constructor!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12582, __PRETTY_FUNCTION__)) | ||||
12582 | "Should not build implicit default constructor!")((ClassDecl->needsImplicitDefaultConstructor() && "Should not build implicit default constructor!" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl->needsImplicitDefaultConstructor() && \"Should not build implicit default constructor!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12582, __PRETTY_FUNCTION__)); | ||||
12583 | |||||
12584 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); | ||||
12585 | if (DSM.isAlreadyBeingDeclared()) | ||||
12586 | return nullptr; | ||||
12587 | |||||
12588 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | ||||
12589 | CXXDefaultConstructor, | ||||
12590 | false); | ||||
12591 | |||||
12592 | // Create the actual constructor declaration. | ||||
12593 | CanQualType ClassType | ||||
12594 | = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); | ||||
12595 | SourceLocation ClassLoc = ClassDecl->getLocation(); | ||||
12596 | DeclarationName Name | ||||
12597 | = Context.DeclarationNames.getCXXConstructorName(ClassType); | ||||
12598 | DeclarationNameInfo NameInfo(Name, ClassLoc); | ||||
12599 | CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( | ||||
12600 | Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), | ||||
12601 | /*TInfo=*/nullptr, ExplicitSpecifier(), | ||||
12602 | /*isInline=*/true, /*isImplicitlyDeclared=*/true, | ||||
12603 | Constexpr ? CSK_constexpr : CSK_unspecified); | ||||
12604 | DefaultCon->setAccess(AS_public); | ||||
12605 | DefaultCon->setDefaulted(); | ||||
12606 | |||||
12607 | if (getLangOpts().CUDA) { | ||||
12608 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, | ||||
12609 | DefaultCon, | ||||
12610 | /* ConstRHS */ false, | ||||
12611 | /* Diagnose */ false); | ||||
12612 | } | ||||
12613 | |||||
12614 | setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); | ||||
12615 | |||||
12616 | // We don't need to use SpecialMemberIsTrivial here; triviality for default | ||||
12617 | // constructors is easy to compute. | ||||
12618 | DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); | ||||
12619 | |||||
12620 | // Note that we have declared this constructor. | ||||
12621 | ++getASTContext().NumImplicitDefaultConstructorsDeclared; | ||||
12622 | |||||
12623 | Scope *S = getScopeForContext(ClassDecl); | ||||
12624 | CheckImplicitSpecialMemberDeclaration(S, DefaultCon); | ||||
12625 | |||||
12626 | if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) | ||||
12627 | SetDeclDeleted(DefaultCon, ClassLoc); | ||||
12628 | |||||
12629 | if (S) | ||||
12630 | PushOnScopeChains(DefaultCon, S, false); | ||||
12631 | ClassDecl->addDecl(DefaultCon); | ||||
12632 | |||||
12633 | return DefaultCon; | ||||
12634 | } | ||||
12635 | |||||
12636 | void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, | ||||
12637 | CXXConstructorDecl *Constructor) { | ||||
12638 | assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&(((Constructor->isDefaulted() && Constructor->isDefaultConstructor () && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor" ) ? static_cast<void> (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12641, __PRETTY_FUNCTION__)) | ||||
12639 | !Constructor->doesThisDeclarationHaveABody() &&(((Constructor->isDefaulted() && Constructor->isDefaultConstructor () && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor" ) ? static_cast<void> (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12641, __PRETTY_FUNCTION__)) | ||||
12640 | !Constructor->isDeleted()) &&(((Constructor->isDefaulted() && Constructor->isDefaultConstructor () && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor" ) ? static_cast<void> (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12641, __PRETTY_FUNCTION__)) | ||||
12641 | "DefineImplicitDefaultConstructor - call it for implicit default ctor")(((Constructor->isDefaulted() && Constructor->isDefaultConstructor () && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && "DefineImplicitDefaultConstructor - call it for implicit default ctor" ) ? static_cast<void> (0) : __assert_fail ("(Constructor->isDefaulted() && Constructor->isDefaultConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()) && \"DefineImplicitDefaultConstructor - call it for implicit default ctor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12641, __PRETTY_FUNCTION__)); | ||||
12642 | if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) | ||||
12643 | return; | ||||
12644 | |||||
12645 | CXXRecordDecl *ClassDecl = Constructor->getParent(); | ||||
12646 | assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor")((ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitDefaultConstructor - invalid constructor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12646, __PRETTY_FUNCTION__)); | ||||
12647 | |||||
12648 | SynthesizedFunctionScope Scope(*this, Constructor); | ||||
12649 | |||||
12650 | // The exception specification is needed because we are defining the | ||||
12651 | // function. | ||||
12652 | ResolveExceptionSpec(CurrentLocation, | ||||
12653 | Constructor->getType()->castAs<FunctionProtoType>()); | ||||
12654 | MarkVTableUsed(CurrentLocation, ClassDecl); | ||||
12655 | |||||
12656 | // Add a context note for diagnostics produced after this point. | ||||
12657 | Scope.addContextNote(CurrentLocation); | ||||
12658 | |||||
12659 | if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { | ||||
12660 | Constructor->setInvalidDecl(); | ||||
12661 | return; | ||||
12662 | } | ||||
12663 | |||||
12664 | SourceLocation Loc = Constructor->getEndLoc().isValid() | ||||
12665 | ? Constructor->getEndLoc() | ||||
12666 | : Constructor->getLocation(); | ||||
12667 | Constructor->setBody(new (Context) CompoundStmt(Loc)); | ||||
12668 | Constructor->markUsed(Context); | ||||
12669 | |||||
12670 | if (ASTMutationListener *L = getASTMutationListener()) { | ||||
12671 | L->CompletedImplicitDefinition(Constructor); | ||||
12672 | } | ||||
12673 | |||||
12674 | DiagnoseUninitializedFields(*this, Constructor); | ||||
12675 | } | ||||
12676 | |||||
12677 | void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { | ||||
12678 | // Perform any delayed checks on exception specifications. | ||||
12679 | CheckDelayedMemberExceptionSpecs(); | ||||
12680 | } | ||||
12681 | |||||
12682 | /// Find or create the fake constructor we synthesize to model constructing an | ||||
12683 | /// object of a derived class via a constructor of a base class. | ||||
12684 | CXXConstructorDecl * | ||||
12685 | Sema::findInheritingConstructor(SourceLocation Loc, | ||||
12686 | CXXConstructorDecl *BaseCtor, | ||||
12687 | ConstructorUsingShadowDecl *Shadow) { | ||||
12688 | CXXRecordDecl *Derived = Shadow->getParent(); | ||||
12689 | SourceLocation UsingLoc = Shadow->getLocation(); | ||||
12690 | |||||
12691 | // FIXME: Add a new kind of DeclarationName for an inherited constructor. | ||||
12692 | // For now we use the name of the base class constructor as a member of the | ||||
12693 | // derived class to indicate a (fake) inherited constructor name. | ||||
12694 | DeclarationName Name = BaseCtor->getDeclName(); | ||||
12695 | |||||
12696 | // Check to see if we already have a fake constructor for this inherited | ||||
12697 | // constructor call. | ||||
12698 | for (NamedDecl *Ctor : Derived->lookup(Name)) | ||||
12699 | if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) | ||||
12700 | ->getInheritedConstructor() | ||||
12701 | .getConstructor(), | ||||
12702 | BaseCtor)) | ||||
12703 | return cast<CXXConstructorDecl>(Ctor); | ||||
12704 | |||||
12705 | DeclarationNameInfo NameInfo(Name, UsingLoc); | ||||
12706 | TypeSourceInfo *TInfo = | ||||
12707 | Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); | ||||
12708 | FunctionProtoTypeLoc ProtoLoc = | ||||
12709 | TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); | ||||
12710 | |||||
12711 | // Check the inherited constructor is valid and find the list of base classes | ||||
12712 | // from which it was inherited. | ||||
12713 | InheritedConstructorInfo ICI(*this, Loc, Shadow); | ||||
12714 | |||||
12715 | bool Constexpr = | ||||
12716 | BaseCtor->isConstexpr() && | ||||
12717 | defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, | ||||
12718 | false, BaseCtor, &ICI); | ||||
12719 | |||||
12720 | CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( | ||||
12721 | Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, | ||||
12722 | BaseCtor->getExplicitSpecifier(), /*isInline=*/true, | ||||
12723 | /*isImplicitlyDeclared=*/true, | ||||
12724 | Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified, | ||||
12725 | InheritedConstructor(Shadow, BaseCtor), | ||||
12726 | BaseCtor->getTrailingRequiresClause()); | ||||
12727 | if (Shadow->isInvalidDecl()) | ||||
12728 | DerivedCtor->setInvalidDecl(); | ||||
12729 | |||||
12730 | // Build an unevaluated exception specification for this fake constructor. | ||||
12731 | const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); | ||||
12732 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | ||||
12733 | EPI.ExceptionSpec.Type = EST_Unevaluated; | ||||
12734 | EPI.ExceptionSpec.SourceDecl = DerivedCtor; | ||||
12735 | DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), | ||||
12736 | FPT->getParamTypes(), EPI)); | ||||
12737 | |||||
12738 | // Build the parameter declarations. | ||||
12739 | SmallVector<ParmVarDecl *, 16> ParamDecls; | ||||
12740 | for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { | ||||
12741 | TypeSourceInfo *TInfo = | ||||
12742 | Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); | ||||
12743 | ParmVarDecl *PD = ParmVarDecl::Create( | ||||
12744 | Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, | ||||
12745 | FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); | ||||
12746 | PD->setScopeInfo(0, I); | ||||
12747 | PD->setImplicit(); | ||||
12748 | // Ensure attributes are propagated onto parameters (this matters for | ||||
12749 | // format, pass_object_size, ...). | ||||
12750 | mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); | ||||
12751 | ParamDecls.push_back(PD); | ||||
12752 | ProtoLoc.setParam(I, PD); | ||||
12753 | } | ||||
12754 | |||||
12755 | // Set up the new constructor. | ||||
12756 | assert(!BaseCtor->isDeleted() && "should not use deleted constructor")((!BaseCtor->isDeleted() && "should not use deleted constructor" ) ? static_cast<void> (0) : __assert_fail ("!BaseCtor->isDeleted() && \"should not use deleted constructor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12756, __PRETTY_FUNCTION__)); | ||||
12757 | DerivedCtor->setAccess(BaseCtor->getAccess()); | ||||
12758 | DerivedCtor->setParams(ParamDecls); | ||||
12759 | Derived->addDecl(DerivedCtor); | ||||
12760 | |||||
12761 | if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) | ||||
12762 | SetDeclDeleted(DerivedCtor, UsingLoc); | ||||
12763 | |||||
12764 | return DerivedCtor; | ||||
12765 | } | ||||
12766 | |||||
12767 | void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { | ||||
12768 | InheritedConstructorInfo ICI(*this, Ctor->getLocation(), | ||||
12769 | Ctor->getInheritedConstructor().getShadowDecl()); | ||||
12770 | ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, | ||||
12771 | /*Diagnose*/true); | ||||
12772 | } | ||||
12773 | |||||
12774 | void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, | ||||
12775 | CXXConstructorDecl *Constructor) { | ||||
12776 | CXXRecordDecl *ClassDecl = Constructor->getParent(); | ||||
12777 | assert(Constructor->getInheritedConstructor() &&((Constructor->getInheritedConstructor() && !Constructor ->doesThisDeclarationHaveABody() && !Constructor-> isDeleted()) ? static_cast<void> (0) : __assert_fail ("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12779, __PRETTY_FUNCTION__)) | ||||
12778 | !Constructor->doesThisDeclarationHaveABody() &&((Constructor->getInheritedConstructor() && !Constructor ->doesThisDeclarationHaveABody() && !Constructor-> isDeleted()) ? static_cast<void> (0) : __assert_fail ("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12779, __PRETTY_FUNCTION__)) | ||||
12779 | !Constructor->isDeleted())((Constructor->getInheritedConstructor() && !Constructor ->doesThisDeclarationHaveABody() && !Constructor-> isDeleted()) ? static_cast<void> (0) : __assert_fail ("Constructor->getInheritedConstructor() && !Constructor->doesThisDeclarationHaveABody() && !Constructor->isDeleted()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12779, __PRETTY_FUNCTION__)); | ||||
12780 | if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) | ||||
12781 | return; | ||||
12782 | |||||
12783 | // Initializations are performed "as if by a defaulted default constructor", | ||||
12784 | // so enter the appropriate scope. | ||||
12785 | SynthesizedFunctionScope Scope(*this, Constructor); | ||||
12786 | |||||
12787 | // The exception specification is needed because we are defining the | ||||
12788 | // function. | ||||
12789 | ResolveExceptionSpec(CurrentLocation, | ||||
12790 | Constructor->getType()->castAs<FunctionProtoType>()); | ||||
12791 | MarkVTableUsed(CurrentLocation, ClassDecl); | ||||
12792 | |||||
12793 | // Add a context note for diagnostics produced after this point. | ||||
12794 | Scope.addContextNote(CurrentLocation); | ||||
12795 | |||||
12796 | ConstructorUsingShadowDecl *Shadow = | ||||
12797 | Constructor->getInheritedConstructor().getShadowDecl(); | ||||
12798 | CXXConstructorDecl *InheritedCtor = | ||||
12799 | Constructor->getInheritedConstructor().getConstructor(); | ||||
12800 | |||||
12801 | // [class.inhctor.init]p1: | ||||
12802 | // initialization proceeds as if a defaulted default constructor is used to | ||||
12803 | // initialize the D object and each base class subobject from which the | ||||
12804 | // constructor was inherited | ||||
12805 | |||||
12806 | InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); | ||||
12807 | CXXRecordDecl *RD = Shadow->getParent(); | ||||
12808 | SourceLocation InitLoc = Shadow->getLocation(); | ||||
12809 | |||||
12810 | // Build explicit initializers for all base classes from which the | ||||
12811 | // constructor was inherited. | ||||
12812 | SmallVector<CXXCtorInitializer*, 8> Inits; | ||||
12813 | for (bool VBase : {false, true}) { | ||||
12814 | for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { | ||||
12815 | if (B.isVirtual() != VBase) | ||||
12816 | continue; | ||||
12817 | |||||
12818 | auto *BaseRD = B.getType()->getAsCXXRecordDecl(); | ||||
12819 | if (!BaseRD) | ||||
12820 | continue; | ||||
12821 | |||||
12822 | auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); | ||||
12823 | if (!BaseCtor.first) | ||||
12824 | continue; | ||||
12825 | |||||
12826 | MarkFunctionReferenced(CurrentLocation, BaseCtor.first); | ||||
12827 | ExprResult Init = new (Context) CXXInheritedCtorInitExpr( | ||||
12828 | InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); | ||||
12829 | |||||
12830 | auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); | ||||
12831 | Inits.push_back(new (Context) CXXCtorInitializer( | ||||
12832 | Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, | ||||
12833 | SourceLocation())); | ||||
12834 | } | ||||
12835 | } | ||||
12836 | |||||
12837 | // We now proceed as if for a defaulted default constructor, with the relevant | ||||
12838 | // initializers replaced. | ||||
12839 | |||||
12840 | if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { | ||||
12841 | Constructor->setInvalidDecl(); | ||||
12842 | return; | ||||
12843 | } | ||||
12844 | |||||
12845 | Constructor->setBody(new (Context) CompoundStmt(InitLoc)); | ||||
12846 | Constructor->markUsed(Context); | ||||
12847 | |||||
12848 | if (ASTMutationListener *L = getASTMutationListener()) { | ||||
12849 | L->CompletedImplicitDefinition(Constructor); | ||||
12850 | } | ||||
12851 | |||||
12852 | DiagnoseUninitializedFields(*this, Constructor); | ||||
12853 | } | ||||
12854 | |||||
12855 | CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { | ||||
12856 | // C++ [class.dtor]p2: | ||||
12857 | // If a class has no user-declared destructor, a destructor is | ||||
12858 | // declared implicitly. An implicitly-declared destructor is an | ||||
12859 | // inline public member of its class. | ||||
12860 | assert(ClassDecl->needsImplicitDestructor())((ClassDecl->needsImplicitDestructor()) ? static_cast<void > (0) : __assert_fail ("ClassDecl->needsImplicitDestructor()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12860, __PRETTY_FUNCTION__)); | ||||
12861 | |||||
12862 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); | ||||
12863 | if (DSM.isAlreadyBeingDeclared()) | ||||
12864 | return nullptr; | ||||
12865 | |||||
12866 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | ||||
12867 | CXXDestructor, | ||||
12868 | false); | ||||
12869 | |||||
12870 | // Create the actual destructor declaration. | ||||
12871 | CanQualType ClassType | ||||
12872 | = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); | ||||
12873 | SourceLocation ClassLoc = ClassDecl->getLocation(); | ||||
12874 | DeclarationName Name | ||||
12875 | = Context.DeclarationNames.getCXXDestructorName(ClassType); | ||||
12876 | DeclarationNameInfo NameInfo(Name, ClassLoc); | ||||
12877 | CXXDestructorDecl *Destructor = | ||||
12878 | CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, | ||||
12879 | QualType(), nullptr, /*isInline=*/true, | ||||
12880 | /*isImplicitlyDeclared=*/true, | ||||
12881 | Constexpr ? CSK_constexpr : CSK_unspecified); | ||||
12882 | Destructor->setAccess(AS_public); | ||||
12883 | Destructor->setDefaulted(); | ||||
12884 | |||||
12885 | if (getLangOpts().CUDA) { | ||||
12886 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, | ||||
12887 | Destructor, | ||||
12888 | /* ConstRHS */ false, | ||||
12889 | /* Diagnose */ false); | ||||
12890 | } | ||||
12891 | |||||
12892 | setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); | ||||
12893 | |||||
12894 | // We don't need to use SpecialMemberIsTrivial here; triviality for | ||||
12895 | // destructors is easy to compute. | ||||
12896 | Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); | ||||
12897 | Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || | ||||
12898 | ClassDecl->hasTrivialDestructorForCall()); | ||||
12899 | |||||
12900 | // Note that we have declared this destructor. | ||||
12901 | ++getASTContext().NumImplicitDestructorsDeclared; | ||||
12902 | |||||
12903 | Scope *S = getScopeForContext(ClassDecl); | ||||
12904 | CheckImplicitSpecialMemberDeclaration(S, Destructor); | ||||
12905 | |||||
12906 | // We can't check whether an implicit destructor is deleted before we complete | ||||
12907 | // the definition of the class, because its validity depends on the alignment | ||||
12908 | // of the class. We'll check this from ActOnFields once the class is complete. | ||||
12909 | if (ClassDecl->isCompleteDefinition() && | ||||
12910 | ShouldDeleteSpecialMember(Destructor, CXXDestructor)) | ||||
12911 | SetDeclDeleted(Destructor, ClassLoc); | ||||
12912 | |||||
12913 | // Introduce this destructor into its scope. | ||||
12914 | if (S) | ||||
12915 | PushOnScopeChains(Destructor, S, false); | ||||
12916 | ClassDecl->addDecl(Destructor); | ||||
12917 | |||||
12918 | return Destructor; | ||||
12919 | } | ||||
12920 | |||||
12921 | void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, | ||||
12922 | CXXDestructorDecl *Destructor) { | ||||
12923 | assert((Destructor->isDefaulted() &&(((Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody () && !Destructor->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor" ) ? static_cast<void> (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12926, __PRETTY_FUNCTION__)) | ||||
12924 | !Destructor->doesThisDeclarationHaveABody() &&(((Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody () && !Destructor->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor" ) ? static_cast<void> (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12926, __PRETTY_FUNCTION__)) | ||||
12925 | !Destructor->isDeleted()) &&(((Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody () && !Destructor->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor" ) ? static_cast<void> (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12926, __PRETTY_FUNCTION__)) | ||||
12926 | "DefineImplicitDestructor - call it for implicit default dtor")(((Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody () && !Destructor->isDeleted()) && "DefineImplicitDestructor - call it for implicit default dtor" ) ? static_cast<void> (0) : __assert_fail ("(Destructor->isDefaulted() && !Destructor->doesThisDeclarationHaveABody() && !Destructor->isDeleted()) && \"DefineImplicitDestructor - call it for implicit default dtor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12926, __PRETTY_FUNCTION__)); | ||||
12927 | if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) | ||||
12928 | return; | ||||
12929 | |||||
12930 | CXXRecordDecl *ClassDecl = Destructor->getParent(); | ||||
12931 | assert(ClassDecl && "DefineImplicitDestructor - invalid destructor")((ClassDecl && "DefineImplicitDestructor - invalid destructor" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitDestructor - invalid destructor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 12931, __PRETTY_FUNCTION__)); | ||||
12932 | |||||
12933 | SynthesizedFunctionScope Scope(*this, Destructor); | ||||
12934 | |||||
12935 | // The exception specification is needed because we are defining the | ||||
12936 | // function. | ||||
12937 | ResolveExceptionSpec(CurrentLocation, | ||||
12938 | Destructor->getType()->castAs<FunctionProtoType>()); | ||||
12939 | MarkVTableUsed(CurrentLocation, ClassDecl); | ||||
12940 | |||||
12941 | // Add a context note for diagnostics produced after this point. | ||||
12942 | Scope.addContextNote(CurrentLocation); | ||||
12943 | |||||
12944 | MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), | ||||
12945 | Destructor->getParent()); | ||||
12946 | |||||
12947 | if (CheckDestructor(Destructor)) { | ||||
12948 | Destructor->setInvalidDecl(); | ||||
12949 | return; | ||||
12950 | } | ||||
12951 | |||||
12952 | SourceLocation Loc = Destructor->getEndLoc().isValid() | ||||
12953 | ? Destructor->getEndLoc() | ||||
12954 | : Destructor->getLocation(); | ||||
12955 | Destructor->setBody(new (Context) CompoundStmt(Loc)); | ||||
12956 | Destructor->markUsed(Context); | ||||
12957 | |||||
12958 | if (ASTMutationListener *L = getASTMutationListener()) { | ||||
12959 | L->CompletedImplicitDefinition(Destructor); | ||||
12960 | } | ||||
12961 | } | ||||
12962 | |||||
12963 | /// Perform any semantic analysis which needs to be delayed until all | ||||
12964 | /// pending class member declarations have been parsed. | ||||
12965 | void Sema::ActOnFinishCXXMemberDecls() { | ||||
12966 | // If the context is an invalid C++ class, just suppress these checks. | ||||
12967 | if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { | ||||
12968 | if (Record->isInvalidDecl()) { | ||||
12969 | DelayedOverridingExceptionSpecChecks.clear(); | ||||
12970 | DelayedEquivalentExceptionSpecChecks.clear(); | ||||
12971 | return; | ||||
12972 | } | ||||
12973 | checkForMultipleExportedDefaultConstructors(*this, Record); | ||||
12974 | } | ||||
12975 | } | ||||
12976 | |||||
12977 | void Sema::ActOnFinishCXXNonNestedClass() { | ||||
12978 | referenceDLLExportedClassMethods(); | ||||
12979 | |||||
12980 | if (!DelayedDllExportMemberFunctions.empty()) { | ||||
12981 | SmallVector<CXXMethodDecl*, 4> WorkList; | ||||
12982 | std::swap(DelayedDllExportMemberFunctions, WorkList); | ||||
12983 | for (CXXMethodDecl *M : WorkList) { | ||||
12984 | DefineImplicitSpecialMember(*this, M, M->getLocation()); | ||||
12985 | |||||
12986 | // Pass the method to the consumer to get emitted. This is not necessary | ||||
12987 | // for explicit instantiation definitions, as they will get emitted | ||||
12988 | // anyway. | ||||
12989 | if (M->getParent()->getTemplateSpecializationKind() != | ||||
12990 | TSK_ExplicitInstantiationDefinition) | ||||
12991 | ActOnFinishInlineFunctionDef(M); | ||||
12992 | } | ||||
12993 | } | ||||
12994 | } | ||||
12995 | |||||
12996 | void Sema::referenceDLLExportedClassMethods() { | ||||
12997 | if (!DelayedDllExportClasses.empty()) { | ||||
12998 | // Calling ReferenceDllExportedMembers might cause the current function to | ||||
12999 | // be called again, so use a local copy of DelayedDllExportClasses. | ||||
13000 | SmallVector<CXXRecordDecl *, 4> WorkList; | ||||
13001 | std::swap(DelayedDllExportClasses, WorkList); | ||||
13002 | for (CXXRecordDecl *Class : WorkList) | ||||
13003 | ReferenceDllExportedMembers(*this, Class); | ||||
13004 | } | ||||
13005 | } | ||||
13006 | |||||
13007 | void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { | ||||
13008 | assert(getLangOpts().CPlusPlus11 &&((getLangOpts().CPlusPlus11 && "adjusting dtor exception specs was introduced in c++11" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus11 && \"adjusting dtor exception specs was introduced in c++11\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13009, __PRETTY_FUNCTION__)) | ||||
13009 | "adjusting dtor exception specs was introduced in c++11")((getLangOpts().CPlusPlus11 && "adjusting dtor exception specs was introduced in c++11" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus11 && \"adjusting dtor exception specs was introduced in c++11\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13009, __PRETTY_FUNCTION__)); | ||||
13010 | |||||
13011 | if (Destructor->isDependentContext()) | ||||
13012 | return; | ||||
13013 | |||||
13014 | // C++11 [class.dtor]p3: | ||||
13015 | // A declaration of a destructor that does not have an exception- | ||||
13016 | // specification is implicitly considered to have the same exception- | ||||
13017 | // specification as an implicit declaration. | ||||
13018 | const FunctionProtoType *DtorType = Destructor->getType()-> | ||||
13019 | getAs<FunctionProtoType>(); | ||||
13020 | if (DtorType->hasExceptionSpec()) | ||||
13021 | return; | ||||
13022 | |||||
13023 | // Replace the destructor's type, building off the existing one. Fortunately, | ||||
13024 | // the only thing of interest in the destructor type is its extended info. | ||||
13025 | // The return and arguments are fixed. | ||||
13026 | FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); | ||||
13027 | EPI.ExceptionSpec.Type = EST_Unevaluated; | ||||
13028 | EPI.ExceptionSpec.SourceDecl = Destructor; | ||||
13029 | Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); | ||||
13030 | |||||
13031 | // FIXME: If the destructor has a body that could throw, and the newly created | ||||
13032 | // spec doesn't allow exceptions, we should emit a warning, because this | ||||
13033 | // change in behavior can break conforming C++03 programs at runtime. | ||||
13034 | // However, we don't have a body or an exception specification yet, so it | ||||
13035 | // needs to be done somewhere else. | ||||
13036 | } | ||||
13037 | |||||
13038 | namespace { | ||||
13039 | /// An abstract base class for all helper classes used in building the | ||||
13040 | // copy/move operators. These classes serve as factory functions and help us | ||||
13041 | // avoid using the same Expr* in the AST twice. | ||||
13042 | class ExprBuilder { | ||||
13043 | ExprBuilder(const ExprBuilder&) = delete; | ||||
13044 | ExprBuilder &operator=(const ExprBuilder&) = delete; | ||||
13045 | |||||
13046 | protected: | ||||
13047 | static Expr *assertNotNull(Expr *E) { | ||||
13048 | assert(E && "Expression construction must not fail.")((E && "Expression construction must not fail.") ? static_cast <void> (0) : __assert_fail ("E && \"Expression construction must not fail.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13048, __PRETTY_FUNCTION__)); | ||||
13049 | return E; | ||||
13050 | } | ||||
13051 | |||||
13052 | public: | ||||
13053 | ExprBuilder() {} | ||||
13054 | virtual ~ExprBuilder() {} | ||||
13055 | |||||
13056 | virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; | ||||
13057 | }; | ||||
13058 | |||||
13059 | class RefBuilder: public ExprBuilder { | ||||
13060 | VarDecl *Var; | ||||
13061 | QualType VarType; | ||||
13062 | |||||
13063 | public: | ||||
13064 | Expr *build(Sema &S, SourceLocation Loc) const override { | ||||
13065 | return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); | ||||
13066 | } | ||||
13067 | |||||
13068 | RefBuilder(VarDecl *Var, QualType VarType) | ||||
13069 | : Var(Var), VarType(VarType) {} | ||||
13070 | }; | ||||
13071 | |||||
13072 | class ThisBuilder: public ExprBuilder { | ||||
13073 | public: | ||||
13074 | Expr *build(Sema &S, SourceLocation Loc) const override { | ||||
13075 | return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); | ||||
13076 | } | ||||
13077 | }; | ||||
13078 | |||||
13079 | class CastBuilder: public ExprBuilder { | ||||
13080 | const ExprBuilder &Builder; | ||||
13081 | QualType Type; | ||||
13082 | ExprValueKind Kind; | ||||
13083 | const CXXCastPath &Path; | ||||
13084 | |||||
13085 | public: | ||||
13086 | Expr *build(Sema &S, SourceLocation Loc) const override { | ||||
13087 | return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, | ||||
13088 | CK_UncheckedDerivedToBase, Kind, | ||||
13089 | &Path).get()); | ||||
13090 | } | ||||
13091 | |||||
13092 | CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, | ||||
13093 | const CXXCastPath &Path) | ||||
13094 | : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} | ||||
13095 | }; | ||||
13096 | |||||
13097 | class DerefBuilder: public ExprBuilder { | ||||
13098 | const ExprBuilder &Builder; | ||||
13099 | |||||
13100 | public: | ||||
13101 | Expr *build(Sema &S, SourceLocation Loc) const override { | ||||
13102 | return assertNotNull( | ||||
13103 | S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); | ||||
13104 | } | ||||
13105 | |||||
13106 | DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} | ||||
13107 | }; | ||||
13108 | |||||
13109 | class MemberBuilder: public ExprBuilder { | ||||
13110 | const ExprBuilder &Builder; | ||||
13111 | QualType Type; | ||||
13112 | CXXScopeSpec SS; | ||||
13113 | bool IsArrow; | ||||
13114 | LookupResult &MemberLookup; | ||||
13115 | |||||
13116 | public: | ||||
13117 | Expr *build(Sema &S, SourceLocation Loc) const override { | ||||
13118 | return assertNotNull(S.BuildMemberReferenceExpr( | ||||
13119 | Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), | ||||
13120 | nullptr, MemberLookup, nullptr, nullptr).get()); | ||||
13121 | } | ||||
13122 | |||||
13123 | MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, | ||||
13124 | LookupResult &MemberLookup) | ||||
13125 | : Builder(Builder), Type(Type), IsArrow(IsArrow), | ||||
13126 | MemberLookup(MemberLookup) {} | ||||
13127 | }; | ||||
13128 | |||||
13129 | class MoveCastBuilder: public ExprBuilder { | ||||
13130 | const ExprBuilder &Builder; | ||||
13131 | |||||
13132 | public: | ||||
13133 | Expr *build(Sema &S, SourceLocation Loc) const override { | ||||
13134 | return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); | ||||
13135 | } | ||||
13136 | |||||
13137 | MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} | ||||
13138 | }; | ||||
13139 | |||||
13140 | class LvalueConvBuilder: public ExprBuilder { | ||||
13141 | const ExprBuilder &Builder; | ||||
13142 | |||||
13143 | public: | ||||
13144 | Expr *build(Sema &S, SourceLocation Loc) const override { | ||||
13145 | return assertNotNull( | ||||
13146 | S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); | ||||
13147 | } | ||||
13148 | |||||
13149 | LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} | ||||
13150 | }; | ||||
13151 | |||||
13152 | class SubscriptBuilder: public ExprBuilder { | ||||
13153 | const ExprBuilder &Base; | ||||
13154 | const ExprBuilder &Index; | ||||
13155 | |||||
13156 | public: | ||||
13157 | Expr *build(Sema &S, SourceLocation Loc) const override { | ||||
13158 | return assertNotNull(S.CreateBuiltinArraySubscriptExpr( | ||||
13159 | Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); | ||||
13160 | } | ||||
13161 | |||||
13162 | SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) | ||||
13163 | : Base(Base), Index(Index) {} | ||||
13164 | }; | ||||
13165 | |||||
13166 | } // end anonymous namespace | ||||
13167 | |||||
13168 | /// When generating a defaulted copy or move assignment operator, if a field | ||||
13169 | /// should be copied with __builtin_memcpy rather than via explicit assignments, | ||||
13170 | /// do so. This optimization only applies for arrays of scalars, and for arrays | ||||
13171 | /// of class type where the selected copy/move-assignment operator is trivial. | ||||
13172 | static StmtResult | ||||
13173 | buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, | ||||
13174 | const ExprBuilder &ToB, const ExprBuilder &FromB) { | ||||
13175 | // Compute the size of the memory buffer to be copied. | ||||
13176 | QualType SizeType = S.Context.getSizeType(); | ||||
13177 | llvm::APInt Size(S.Context.getTypeSize(SizeType), | ||||
13178 | S.Context.getTypeSizeInChars(T).getQuantity()); | ||||
13179 | |||||
13180 | // Take the address of the field references for "from" and "to". We | ||||
13181 | // directly construct UnaryOperators here because semantic analysis | ||||
13182 | // does not permit us to take the address of an xvalue. | ||||
13183 | Expr *From = FromB.build(S, Loc); | ||||
13184 | From = new (S.Context) UnaryOperator(From, UO_AddrOf, | ||||
13185 | S.Context.getPointerType(From->getType()), | ||||
13186 | VK_RValue, OK_Ordinary, Loc, false); | ||||
13187 | Expr *To = ToB.build(S, Loc); | ||||
13188 | To = new (S.Context) UnaryOperator(To, UO_AddrOf, | ||||
13189 | S.Context.getPointerType(To->getType()), | ||||
13190 | VK_RValue, OK_Ordinary, Loc, false); | ||||
13191 | |||||
13192 | const Type *E = T->getBaseElementTypeUnsafe(); | ||||
13193 | bool NeedsCollectableMemCpy = | ||||
13194 | E->isRecordType() && | ||||
13195 | E->castAs<RecordType>()->getDecl()->hasObjectMember(); | ||||
13196 | |||||
13197 | // Create a reference to the __builtin_objc_memmove_collectable function | ||||
13198 | StringRef MemCpyName = NeedsCollectableMemCpy ? | ||||
13199 | "__builtin_objc_memmove_collectable" : | ||||
13200 | "__builtin_memcpy"; | ||||
13201 | LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, | ||||
13202 | Sema::LookupOrdinaryName); | ||||
13203 | S.LookupName(R, S.TUScope, true); | ||||
13204 | |||||
13205 | FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); | ||||
13206 | if (!MemCpy) | ||||
13207 | // Something went horribly wrong earlier, and we will have complained | ||||
13208 | // about it. | ||||
13209 | return StmtError(); | ||||
13210 | |||||
13211 | ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, | ||||
13212 | VK_RValue, Loc, nullptr); | ||||
13213 | assert(MemCpyRef.isUsable() && "Builtin reference cannot fail")((MemCpyRef.isUsable() && "Builtin reference cannot fail" ) ? static_cast<void> (0) : __assert_fail ("MemCpyRef.isUsable() && \"Builtin reference cannot fail\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13213, __PRETTY_FUNCTION__)); | ||||
13214 | |||||
13215 | Expr *CallArgs[] = { | ||||
13216 | To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) | ||||
13217 | }; | ||||
13218 | ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), | ||||
13219 | Loc, CallArgs, Loc); | ||||
13220 | |||||
13221 | assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!")((!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!" ) ? static_cast<void> (0) : __assert_fail ("!Call.isInvalid() && \"Call to __builtin_memcpy cannot fail!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13221, __PRETTY_FUNCTION__)); | ||||
13222 | return Call.getAs<Stmt>(); | ||||
13223 | } | ||||
13224 | |||||
13225 | /// Builds a statement that copies/moves the given entity from \p From to | ||||
13226 | /// \c To. | ||||
13227 | /// | ||||
13228 | /// This routine is used to copy/move the members of a class with an | ||||
13229 | /// implicitly-declared copy/move assignment operator. When the entities being | ||||
13230 | /// copied are arrays, this routine builds for loops to copy them. | ||||
13231 | /// | ||||
13232 | /// \param S The Sema object used for type-checking. | ||||
13233 | /// | ||||
13234 | /// \param Loc The location where the implicit copy/move is being generated. | ||||
13235 | /// | ||||
13236 | /// \param T The type of the expressions being copied/moved. Both expressions | ||||
13237 | /// must have this type. | ||||
13238 | /// | ||||
13239 | /// \param To The expression we are copying/moving to. | ||||
13240 | /// | ||||
13241 | /// \param From The expression we are copying/moving from. | ||||
13242 | /// | ||||
13243 | /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. | ||||
13244 | /// Otherwise, it's a non-static member subobject. | ||||
13245 | /// | ||||
13246 | /// \param Copying Whether we're copying or moving. | ||||
13247 | /// | ||||
13248 | /// \param Depth Internal parameter recording the depth of the recursion. | ||||
13249 | /// | ||||
13250 | /// \returns A statement or a loop that copies the expressions, or StmtResult(0) | ||||
13251 | /// if a memcpy should be used instead. | ||||
13252 | static StmtResult | ||||
13253 | buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, | ||||
13254 | const ExprBuilder &To, const ExprBuilder &From, | ||||
13255 | bool CopyingBaseSubobject, bool Copying, | ||||
13256 | unsigned Depth = 0) { | ||||
13257 | // C++11 [class.copy]p28: | ||||
13258 | // Each subobject is assigned in the manner appropriate to its type: | ||||
13259 | // | ||||
13260 | // - if the subobject is of class type, as if by a call to operator= with | ||||
13261 | // the subobject as the object expression and the corresponding | ||||
13262 | // subobject of x as a single function argument (as if by explicit | ||||
13263 | // qualification; that is, ignoring any possible virtual overriding | ||||
13264 | // functions in more derived classes); | ||||
13265 | // | ||||
13266 | // C++03 [class.copy]p13: | ||||
13267 | // - if the subobject is of class type, the copy assignment operator for | ||||
13268 | // the class is used (as if by explicit qualification; that is, | ||||
13269 | // ignoring any possible virtual overriding functions in more derived | ||||
13270 | // classes); | ||||
13271 | if (const RecordType *RecordTy = T->getAs<RecordType>()) { | ||||
13272 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); | ||||
13273 | |||||
13274 | // Look for operator=. | ||||
13275 | DeclarationName Name | ||||
13276 | = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); | ||||
13277 | LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); | ||||
13278 | S.LookupQualifiedName(OpLookup, ClassDecl, false); | ||||
13279 | |||||
13280 | // Prior to C++11, filter out any result that isn't a copy/move-assignment | ||||
13281 | // operator. | ||||
13282 | if (!S.getLangOpts().CPlusPlus11) { | ||||
13283 | LookupResult::Filter F = OpLookup.makeFilter(); | ||||
13284 | while (F.hasNext()) { | ||||
13285 | NamedDecl *D = F.next(); | ||||
13286 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) | ||||
13287 | if (Method->isCopyAssignmentOperator() || | ||||
13288 | (!Copying && Method->isMoveAssignmentOperator())) | ||||
13289 | continue; | ||||
13290 | |||||
13291 | F.erase(); | ||||
13292 | } | ||||
13293 | F.done(); | ||||
13294 | } | ||||
13295 | |||||
13296 | // Suppress the protected check (C++ [class.protected]) for each of the | ||||
13297 | // assignment operators we found. This strange dance is required when | ||||
13298 | // we're assigning via a base classes's copy-assignment operator. To | ||||
13299 | // ensure that we're getting the right base class subobject (without | ||||
13300 | // ambiguities), we need to cast "this" to that subobject type; to | ||||
13301 | // ensure that we don't go through the virtual call mechanism, we need | ||||
13302 | // to qualify the operator= name with the base class (see below). However, | ||||
13303 | // this means that if the base class has a protected copy assignment | ||||
13304 | // operator, the protected member access check will fail. So, we | ||||
13305 | // rewrite "protected" access to "public" access in this case, since we | ||||
13306 | // know by construction that we're calling from a derived class. | ||||
13307 | if (CopyingBaseSubobject) { | ||||
13308 | for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); | ||||
13309 | L != LEnd; ++L) { | ||||
13310 | if (L.getAccess() == AS_protected) | ||||
13311 | L.setAccess(AS_public); | ||||
13312 | } | ||||
13313 | } | ||||
13314 | |||||
13315 | // Create the nested-name-specifier that will be used to qualify the | ||||
13316 | // reference to operator=; this is required to suppress the virtual | ||||
13317 | // call mechanism. | ||||
13318 | CXXScopeSpec SS; | ||||
13319 | const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); | ||||
13320 | SS.MakeTrivial(S.Context, | ||||
13321 | NestedNameSpecifier::Create(S.Context, nullptr, false, | ||||
13322 | CanonicalT), | ||||
13323 | Loc); | ||||
13324 | |||||
13325 | // Create the reference to operator=. | ||||
13326 | ExprResult OpEqualRef | ||||
13327 | = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, | ||||
13328 | SS, /*TemplateKWLoc=*/SourceLocation(), | ||||
13329 | /*FirstQualifierInScope=*/nullptr, | ||||
13330 | OpLookup, | ||||
13331 | /*TemplateArgs=*/nullptr, /*S*/nullptr, | ||||
13332 | /*SuppressQualifierCheck=*/true); | ||||
13333 | if (OpEqualRef.isInvalid()) | ||||
13334 | return StmtError(); | ||||
13335 | |||||
13336 | // Build the call to the assignment operator. | ||||
13337 | |||||
13338 | Expr *FromInst = From.build(S, Loc); | ||||
13339 | ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, | ||||
13340 | OpEqualRef.getAs<Expr>(), | ||||
13341 | Loc, FromInst, Loc); | ||||
13342 | if (Call.isInvalid()) | ||||
13343 | return StmtError(); | ||||
13344 | |||||
13345 | // If we built a call to a trivial 'operator=' while copying an array, | ||||
13346 | // bail out. We'll replace the whole shebang with a memcpy. | ||||
13347 | CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); | ||||
13348 | if (CE && CE->getMethodDecl()->isTrivial() && Depth) | ||||
13349 | return StmtResult((Stmt*)nullptr); | ||||
13350 | |||||
13351 | // Convert to an expression-statement, and clean up any produced | ||||
13352 | // temporaries. | ||||
13353 | return S.ActOnExprStmt(Call); | ||||
13354 | } | ||||
13355 | |||||
13356 | // - if the subobject is of scalar type, the built-in assignment | ||||
13357 | // operator is used. | ||||
13358 | const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); | ||||
13359 | if (!ArrayTy) { | ||||
13360 | ExprResult Assignment = S.CreateBuiltinBinOp( | ||||
13361 | Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); | ||||
13362 | if (Assignment.isInvalid()) | ||||
13363 | return StmtError(); | ||||
13364 | return S.ActOnExprStmt(Assignment); | ||||
13365 | } | ||||
13366 | |||||
13367 | // - if the subobject is an array, each element is assigned, in the | ||||
13368 | // manner appropriate to the element type; | ||||
13369 | |||||
13370 | // Construct a loop over the array bounds, e.g., | ||||
13371 | // | ||||
13372 | // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) | ||||
13373 | // | ||||
13374 | // that will copy each of the array elements. | ||||
13375 | QualType SizeType = S.Context.getSizeType(); | ||||
13376 | |||||
13377 | // Create the iteration variable. | ||||
13378 | IdentifierInfo *IterationVarName = nullptr; | ||||
13379 | { | ||||
13380 | SmallString<8> Str; | ||||
13381 | llvm::raw_svector_ostream OS(Str); | ||||
13382 | OS << "__i" << Depth; | ||||
13383 | IterationVarName = &S.Context.Idents.get(OS.str()); | ||||
13384 | } | ||||
13385 | VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, | ||||
13386 | IterationVarName, SizeType, | ||||
13387 | S.Context.getTrivialTypeSourceInfo(SizeType, Loc), | ||||
13388 | SC_None); | ||||
13389 | |||||
13390 | // Initialize the iteration variable to zero. | ||||
13391 | llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); | ||||
13392 | IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); | ||||
13393 | |||||
13394 | // Creates a reference to the iteration variable. | ||||
13395 | RefBuilder IterationVarRef(IterationVar, SizeType); | ||||
13396 | LvalueConvBuilder IterationVarRefRVal(IterationVarRef); | ||||
13397 | |||||
13398 | // Create the DeclStmt that holds the iteration variable. | ||||
13399 | Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); | ||||
13400 | |||||
13401 | // Subscript the "from" and "to" expressions with the iteration variable. | ||||
13402 | SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); | ||||
13403 | MoveCastBuilder FromIndexMove(FromIndexCopy); | ||||
13404 | const ExprBuilder *FromIndex; | ||||
13405 | if (Copying) | ||||
13406 | FromIndex = &FromIndexCopy; | ||||
13407 | else | ||||
13408 | FromIndex = &FromIndexMove; | ||||
13409 | |||||
13410 | SubscriptBuilder ToIndex(To, IterationVarRefRVal); | ||||
13411 | |||||
13412 | // Build the copy/move for an individual element of the array. | ||||
13413 | StmtResult Copy = | ||||
13414 | buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), | ||||
13415 | ToIndex, *FromIndex, CopyingBaseSubobject, | ||||
13416 | Copying, Depth + 1); | ||||
13417 | // Bail out if copying fails or if we determined that we should use memcpy. | ||||
13418 | if (Copy.isInvalid() || !Copy.get()) | ||||
13419 | return Copy; | ||||
13420 | |||||
13421 | // Create the comparison against the array bound. | ||||
13422 | llvm::APInt Upper | ||||
13423 | = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); | ||||
13424 | Expr *Comparison | ||||
13425 | = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), | ||||
13426 | IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), | ||||
13427 | BO_NE, S.Context.BoolTy, | ||||
13428 | VK_RValue, OK_Ordinary, Loc, FPOptions()); | ||||
13429 | |||||
13430 | // Create the pre-increment of the iteration variable. We can determine | ||||
13431 | // whether the increment will overflow based on the value of the array | ||||
13432 | // bound. | ||||
13433 | Expr *Increment = new (S.Context) | ||||
13434 | UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, | ||||
13435 | VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); | ||||
13436 | |||||
13437 | // Construct the loop that copies all elements of this array. | ||||
13438 | return S.ActOnForStmt( | ||||
13439 | Loc, Loc, InitStmt, | ||||
13440 | S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), | ||||
13441 | S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); | ||||
13442 | } | ||||
13443 | |||||
13444 | static StmtResult | ||||
13445 | buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, | ||||
13446 | const ExprBuilder &To, const ExprBuilder &From, | ||||
13447 | bool CopyingBaseSubobject, bool Copying) { | ||||
13448 | // Maybe we should use a memcpy? | ||||
13449 | if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && | ||||
13450 | T.isTriviallyCopyableType(S.Context)) | ||||
13451 | return buildMemcpyForAssignmentOp(S, Loc, T, To, From); | ||||
13452 | |||||
13453 | StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, | ||||
13454 | CopyingBaseSubobject, | ||||
13455 | Copying, 0)); | ||||
13456 | |||||
13457 | // If we ended up picking a trivial assignment operator for an array of a | ||||
13458 | // non-trivially-copyable class type, just emit a memcpy. | ||||
13459 | if (!Result.isInvalid() && !Result.get()) | ||||
13460 | return buildMemcpyForAssignmentOp(S, Loc, T, To, From); | ||||
13461 | |||||
13462 | return Result; | ||||
13463 | } | ||||
13464 | |||||
13465 | CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { | ||||
13466 | // Note: The following rules are largely analoguous to the copy | ||||
13467 | // constructor rules. Note that virtual bases are not taken into account | ||||
13468 | // for determining the argument type of the operator. Note also that | ||||
13469 | // operators taking an object instead of a reference are allowed. | ||||
13470 | assert(ClassDecl->needsImplicitCopyAssignment())((ClassDecl->needsImplicitCopyAssignment()) ? static_cast< void> (0) : __assert_fail ("ClassDecl->needsImplicitCopyAssignment()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13470, __PRETTY_FUNCTION__)); | ||||
13471 | |||||
13472 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); | ||||
13473 | if (DSM.isAlreadyBeingDeclared()) | ||||
13474 | return nullptr; | ||||
13475 | |||||
13476 | QualType ArgType = Context.getTypeDeclType(ClassDecl); | ||||
13477 | LangAS AS = getDefaultCXXMethodAddrSpace(); | ||||
13478 | if (AS != LangAS::Default) | ||||
13479 | ArgType = Context.getAddrSpaceQualType(ArgType, AS); | ||||
13480 | QualType RetType = Context.getLValueReferenceType(ArgType); | ||||
13481 | bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); | ||||
13482 | if (Const) | ||||
13483 | ArgType = ArgType.withConst(); | ||||
13484 | |||||
13485 | ArgType = Context.getLValueReferenceType(ArgType); | ||||
13486 | |||||
13487 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | ||||
13488 | CXXCopyAssignment, | ||||
13489 | Const); | ||||
13490 | |||||
13491 | // An implicitly-declared copy assignment operator is an inline public | ||||
13492 | // member of its class. | ||||
13493 | DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); | ||||
13494 | SourceLocation ClassLoc = ClassDecl->getLocation(); | ||||
13495 | DeclarationNameInfo NameInfo(Name, ClassLoc); | ||||
13496 | CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( | ||||
13497 | Context, ClassDecl, ClassLoc, NameInfo, QualType(), | ||||
13498 | /*TInfo=*/nullptr, /*StorageClass=*/SC_None, | ||||
13499 | /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, | ||||
13500 | SourceLocation()); | ||||
13501 | CopyAssignment->setAccess(AS_public); | ||||
13502 | CopyAssignment->setDefaulted(); | ||||
13503 | CopyAssignment->setImplicit(); | ||||
13504 | |||||
13505 | if (getLangOpts().CUDA) { | ||||
13506 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, | ||||
13507 | CopyAssignment, | ||||
13508 | /* ConstRHS */ Const, | ||||
13509 | /* Diagnose */ false); | ||||
13510 | } | ||||
13511 | |||||
13512 | setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); | ||||
13513 | |||||
13514 | // Add the parameter to the operator. | ||||
13515 | ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, | ||||
13516 | ClassLoc, ClassLoc, | ||||
13517 | /*Id=*/nullptr, ArgType, | ||||
13518 | /*TInfo=*/nullptr, SC_None, | ||||
13519 | nullptr); | ||||
13520 | CopyAssignment->setParams(FromParam); | ||||
13521 | |||||
13522 | CopyAssignment->setTrivial( | ||||
13523 | ClassDecl->needsOverloadResolutionForCopyAssignment() | ||||
13524 | ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) | ||||
13525 | : ClassDecl->hasTrivialCopyAssignment()); | ||||
13526 | |||||
13527 | // Note that we have added this copy-assignment operator. | ||||
13528 | ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; | ||||
13529 | |||||
13530 | Scope *S = getScopeForContext(ClassDecl); | ||||
13531 | CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); | ||||
13532 | |||||
13533 | if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) | ||||
13534 | SetDeclDeleted(CopyAssignment, ClassLoc); | ||||
13535 | |||||
13536 | if (S) | ||||
13537 | PushOnScopeChains(CopyAssignment, S, false); | ||||
13538 | ClassDecl->addDecl(CopyAssignment); | ||||
13539 | |||||
13540 | return CopyAssignment; | ||||
13541 | } | ||||
13542 | |||||
13543 | /// Diagnose an implicit copy operation for a class which is odr-used, but | ||||
13544 | /// which is deprecated because the class has a user-declared copy constructor, | ||||
13545 | /// copy assignment operator, or destructor. | ||||
13546 | static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { | ||||
13547 | assert(CopyOp->isImplicit())((CopyOp->isImplicit()) ? static_cast<void> (0) : __assert_fail ("CopyOp->isImplicit()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13547, __PRETTY_FUNCTION__)); | ||||
13548 | |||||
13549 | CXXRecordDecl *RD = CopyOp->getParent(); | ||||
13550 | CXXMethodDecl *UserDeclaredOperation = nullptr; | ||||
13551 | |||||
13552 | // In Microsoft mode, assignment operations don't affect constructors and | ||||
13553 | // vice versa. | ||||
13554 | if (RD->hasUserDeclaredDestructor()) { | ||||
13555 | UserDeclaredOperation = RD->getDestructor(); | ||||
13556 | } else if (!isa<CXXConstructorDecl>(CopyOp) && | ||||
13557 | RD->hasUserDeclaredCopyConstructor() && | ||||
13558 | !S.getLangOpts().MSVCCompat) { | ||||
13559 | // Find any user-declared copy constructor. | ||||
13560 | for (auto *I : RD->ctors()) { | ||||
13561 | if (I->isCopyConstructor()) { | ||||
13562 | UserDeclaredOperation = I; | ||||
13563 | break; | ||||
13564 | } | ||||
13565 | } | ||||
13566 | assert(UserDeclaredOperation)((UserDeclaredOperation) ? static_cast<void> (0) : __assert_fail ("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13566, __PRETTY_FUNCTION__)); | ||||
13567 | } else if (isa<CXXConstructorDecl>(CopyOp) && | ||||
13568 | RD->hasUserDeclaredCopyAssignment() && | ||||
13569 | !S.getLangOpts().MSVCCompat) { | ||||
13570 | // Find any user-declared move assignment operator. | ||||
13571 | for (auto *I : RD->methods()) { | ||||
13572 | if (I->isCopyAssignmentOperator()) { | ||||
13573 | UserDeclaredOperation = I; | ||||
13574 | break; | ||||
13575 | } | ||||
13576 | } | ||||
13577 | assert(UserDeclaredOperation)((UserDeclaredOperation) ? static_cast<void> (0) : __assert_fail ("UserDeclaredOperation", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13577, __PRETTY_FUNCTION__)); | ||||
13578 | } | ||||
13579 | |||||
13580 | if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) { | ||||
13581 | S.Diag(UserDeclaredOperation->getLocation(), | ||||
13582 | isa<CXXDestructorDecl>(UserDeclaredOperation) | ||||
13583 | ? diag::warn_deprecated_copy_dtor_operation | ||||
13584 | : diag::warn_deprecated_copy_operation) | ||||
13585 | << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp); | ||||
13586 | } | ||||
13587 | } | ||||
13588 | |||||
13589 | void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, | ||||
13590 | CXXMethodDecl *CopyAssignOperator) { | ||||
13591 | assert((CopyAssignOperator->isDefaulted() &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator ->isOverloadedOperator() && CopyAssignOperator-> getOverloadedOperator() == OO_Equal && !CopyAssignOperator ->doesThisDeclarationHaveABody() && !CopyAssignOperator ->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function" ) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13596, __PRETTY_FUNCTION__)) | ||||
13592 | CopyAssignOperator->isOverloadedOperator() &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator ->isOverloadedOperator() && CopyAssignOperator-> getOverloadedOperator() == OO_Equal && !CopyAssignOperator ->doesThisDeclarationHaveABody() && !CopyAssignOperator ->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function" ) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13596, __PRETTY_FUNCTION__)) | ||||
13593 | CopyAssignOperator->getOverloadedOperator() == OO_Equal &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator ->isOverloadedOperator() && CopyAssignOperator-> getOverloadedOperator() == OO_Equal && !CopyAssignOperator ->doesThisDeclarationHaveABody() && !CopyAssignOperator ->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function" ) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13596, __PRETTY_FUNCTION__)) | ||||
13594 | !CopyAssignOperator->doesThisDeclarationHaveABody() &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator ->isOverloadedOperator() && CopyAssignOperator-> getOverloadedOperator() == OO_Equal && !CopyAssignOperator ->doesThisDeclarationHaveABody() && !CopyAssignOperator ->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function" ) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13596, __PRETTY_FUNCTION__)) | ||||
13595 | !CopyAssignOperator->isDeleted()) &&(((CopyAssignOperator->isDefaulted() && CopyAssignOperator ->isOverloadedOperator() && CopyAssignOperator-> getOverloadedOperator() == OO_Equal && !CopyAssignOperator ->doesThisDeclarationHaveABody() && !CopyAssignOperator ->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function" ) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13596, __PRETTY_FUNCTION__)) | ||||
13596 | "DefineImplicitCopyAssignment called for wrong function")(((CopyAssignOperator->isDefaulted() && CopyAssignOperator ->isOverloadedOperator() && CopyAssignOperator-> getOverloadedOperator() == OO_Equal && !CopyAssignOperator ->doesThisDeclarationHaveABody() && !CopyAssignOperator ->isDeleted()) && "DefineImplicitCopyAssignment called for wrong function" ) ? static_cast<void> (0) : __assert_fail ("(CopyAssignOperator->isDefaulted() && CopyAssignOperator->isOverloadedOperator() && CopyAssignOperator->getOverloadedOperator() == OO_Equal && !CopyAssignOperator->doesThisDeclarationHaveABody() && !CopyAssignOperator->isDeleted()) && \"DefineImplicitCopyAssignment called for wrong function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13596, __PRETTY_FUNCTION__)); | ||||
13597 | if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) | ||||
13598 | return; | ||||
13599 | |||||
13600 | CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); | ||||
13601 | if (ClassDecl->isInvalidDecl()) { | ||||
13602 | CopyAssignOperator->setInvalidDecl(); | ||||
13603 | return; | ||||
13604 | } | ||||
13605 | |||||
13606 | SynthesizedFunctionScope Scope(*this, CopyAssignOperator); | ||||
13607 | |||||
13608 | // The exception specification is needed because we are defining the | ||||
13609 | // function. | ||||
13610 | ResolveExceptionSpec(CurrentLocation, | ||||
13611 | CopyAssignOperator->getType()->castAs<FunctionProtoType>()); | ||||
13612 | |||||
13613 | // Add a context note for diagnostics produced after this point. | ||||
13614 | Scope.addContextNote(CurrentLocation); | ||||
13615 | |||||
13616 | // C++11 [class.copy]p18: | ||||
13617 | // The [definition of an implicitly declared copy assignment operator] is | ||||
13618 | // deprecated if the class has a user-declared copy constructor or a | ||||
13619 | // user-declared destructor. | ||||
13620 | if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) | ||||
13621 | diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); | ||||
13622 | |||||
13623 | // C++0x [class.copy]p30: | ||||
13624 | // The implicitly-defined or explicitly-defaulted copy assignment operator | ||||
13625 | // for a non-union class X performs memberwise copy assignment of its | ||||
13626 | // subobjects. The direct base classes of X are assigned first, in the | ||||
13627 | // order of their declaration in the base-specifier-list, and then the | ||||
13628 | // immediate non-static data members of X are assigned, in the order in | ||||
13629 | // which they were declared in the class definition. | ||||
13630 | |||||
13631 | // The statements that form the synthesized function body. | ||||
13632 | SmallVector<Stmt*, 8> Statements; | ||||
13633 | |||||
13634 | // The parameter for the "other" object, which we are copying from. | ||||
13635 | ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); | ||||
13636 | Qualifiers OtherQuals = Other->getType().getQualifiers(); | ||||
13637 | QualType OtherRefType = Other->getType(); | ||||
13638 | if (const LValueReferenceType *OtherRef | ||||
13639 | = OtherRefType->getAs<LValueReferenceType>()) { | ||||
13640 | OtherRefType = OtherRef->getPointeeType(); | ||||
13641 | OtherQuals = OtherRefType.getQualifiers(); | ||||
13642 | } | ||||
13643 | |||||
13644 | // Our location for everything implicitly-generated. | ||||
13645 | SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() | ||||
13646 | ? CopyAssignOperator->getEndLoc() | ||||
13647 | : CopyAssignOperator->getLocation(); | ||||
13648 | |||||
13649 | // Builds a DeclRefExpr for the "other" object. | ||||
13650 | RefBuilder OtherRef(Other, OtherRefType); | ||||
13651 | |||||
13652 | // Builds the "this" pointer. | ||||
13653 | ThisBuilder This; | ||||
13654 | |||||
13655 | // Assign base classes. | ||||
13656 | bool Invalid = false; | ||||
13657 | for (auto &Base : ClassDecl->bases()) { | ||||
13658 | // Form the assignment: | ||||
13659 | // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); | ||||
13660 | QualType BaseType = Base.getType().getUnqualifiedType(); | ||||
13661 | if (!BaseType->isRecordType()) { | ||||
13662 | Invalid = true; | ||||
13663 | continue; | ||||
13664 | } | ||||
13665 | |||||
13666 | CXXCastPath BasePath; | ||||
13667 | BasePath.push_back(&Base); | ||||
13668 | |||||
13669 | // Construct the "from" expression, which is an implicit cast to the | ||||
13670 | // appropriately-qualified base type. | ||||
13671 | CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), | ||||
13672 | VK_LValue, BasePath); | ||||
13673 | |||||
13674 | // Dereference "this". | ||||
13675 | DerefBuilder DerefThis(This); | ||||
13676 | CastBuilder To(DerefThis, | ||||
13677 | Context.getQualifiedType( | ||||
13678 | BaseType, CopyAssignOperator->getMethodQualifiers()), | ||||
13679 | VK_LValue, BasePath); | ||||
13680 | |||||
13681 | // Build the copy. | ||||
13682 | StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, | ||||
13683 | To, From, | ||||
13684 | /*CopyingBaseSubobject=*/true, | ||||
13685 | /*Copying=*/true); | ||||
13686 | if (Copy.isInvalid()) { | ||||
13687 | CopyAssignOperator->setInvalidDecl(); | ||||
13688 | return; | ||||
13689 | } | ||||
13690 | |||||
13691 | // Success! Record the copy. | ||||
13692 | Statements.push_back(Copy.getAs<Expr>()); | ||||
13693 | } | ||||
13694 | |||||
13695 | // Assign non-static members. | ||||
13696 | for (auto *Field : ClassDecl->fields()) { | ||||
13697 | // FIXME: We should form some kind of AST representation for the implied | ||||
13698 | // memcpy in a union copy operation. | ||||
13699 | if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) | ||||
13700 | continue; | ||||
13701 | |||||
13702 | if (Field->isInvalidDecl()) { | ||||
13703 | Invalid = true; | ||||
13704 | continue; | ||||
13705 | } | ||||
13706 | |||||
13707 | // Check for members of reference type; we can't copy those. | ||||
13708 | if (Field->getType()->isReferenceType()) { | ||||
13709 | Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) | ||||
13710 | << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); | ||||
13711 | Diag(Field->getLocation(), diag::note_declared_at); | ||||
13712 | Invalid = true; | ||||
13713 | continue; | ||||
13714 | } | ||||
13715 | |||||
13716 | // Check for members of const-qualified, non-class type. | ||||
13717 | QualType BaseType = Context.getBaseElementType(Field->getType()); | ||||
13718 | if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { | ||||
13719 | Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) | ||||
13720 | << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); | ||||
13721 | Diag(Field->getLocation(), diag::note_declared_at); | ||||
13722 | Invalid = true; | ||||
13723 | continue; | ||||
13724 | } | ||||
13725 | |||||
13726 | // Suppress assigning zero-width bitfields. | ||||
13727 | if (Field->isZeroLengthBitField(Context)) | ||||
13728 | continue; | ||||
13729 | |||||
13730 | QualType FieldType = Field->getType().getNonReferenceType(); | ||||
13731 | if (FieldType->isIncompleteArrayType()) { | ||||
13732 | assert(ClassDecl->hasFlexibleArrayMember() &&((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13733, __PRETTY_FUNCTION__)) | ||||
13733 | "Incomplete array type is not valid")((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13733, __PRETTY_FUNCTION__)); | ||||
13734 | continue; | ||||
13735 | } | ||||
13736 | |||||
13737 | // Build references to the field in the object we're copying from and to. | ||||
13738 | CXXScopeSpec SS; // Intentionally empty | ||||
13739 | LookupResult MemberLookup(*this, Field->getDeclName(), Loc, | ||||
13740 | LookupMemberName); | ||||
13741 | MemberLookup.addDecl(Field); | ||||
13742 | MemberLookup.resolveKind(); | ||||
13743 | |||||
13744 | MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); | ||||
13745 | |||||
13746 | MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); | ||||
13747 | |||||
13748 | // Build the copy of this field. | ||||
13749 | StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, | ||||
13750 | To, From, | ||||
13751 | /*CopyingBaseSubobject=*/false, | ||||
13752 | /*Copying=*/true); | ||||
13753 | if (Copy.isInvalid()) { | ||||
13754 | CopyAssignOperator->setInvalidDecl(); | ||||
13755 | return; | ||||
13756 | } | ||||
13757 | |||||
13758 | // Success! Record the copy. | ||||
13759 | Statements.push_back(Copy.getAs<Stmt>()); | ||||
13760 | } | ||||
13761 | |||||
13762 | if (!Invalid) { | ||||
13763 | // Add a "return *this;" | ||||
13764 | ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); | ||||
13765 | |||||
13766 | StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); | ||||
13767 | if (Return.isInvalid()) | ||||
13768 | Invalid = true; | ||||
13769 | else | ||||
13770 | Statements.push_back(Return.getAs<Stmt>()); | ||||
13771 | } | ||||
13772 | |||||
13773 | if (Invalid) { | ||||
13774 | CopyAssignOperator->setInvalidDecl(); | ||||
13775 | return; | ||||
13776 | } | ||||
13777 | |||||
13778 | StmtResult Body; | ||||
13779 | { | ||||
13780 | CompoundScopeRAII CompoundScope(*this); | ||||
13781 | Body = ActOnCompoundStmt(Loc, Loc, Statements, | ||||
13782 | /*isStmtExpr=*/false); | ||||
13783 | assert(!Body.isInvalid() && "Compound statement creation cannot fail")((!Body.isInvalid() && "Compound statement creation cannot fail" ) ? static_cast<void> (0) : __assert_fail ("!Body.isInvalid() && \"Compound statement creation cannot fail\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13783, __PRETTY_FUNCTION__)); | ||||
13784 | } | ||||
13785 | CopyAssignOperator->setBody(Body.getAs<Stmt>()); | ||||
13786 | CopyAssignOperator->markUsed(Context); | ||||
13787 | |||||
13788 | if (ASTMutationListener *L = getASTMutationListener()) { | ||||
13789 | L->CompletedImplicitDefinition(CopyAssignOperator); | ||||
13790 | } | ||||
13791 | } | ||||
13792 | |||||
13793 | CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { | ||||
13794 | assert(ClassDecl->needsImplicitMoveAssignment())((ClassDecl->needsImplicitMoveAssignment()) ? static_cast< void> (0) : __assert_fail ("ClassDecl->needsImplicitMoveAssignment()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13794, __PRETTY_FUNCTION__)); | ||||
13795 | |||||
13796 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); | ||||
13797 | if (DSM.isAlreadyBeingDeclared()) | ||||
13798 | return nullptr; | ||||
13799 | |||||
13800 | // Note: The following rules are largely analoguous to the move | ||||
13801 | // constructor rules. | ||||
13802 | |||||
13803 | QualType ArgType = Context.getTypeDeclType(ClassDecl); | ||||
13804 | LangAS AS = getDefaultCXXMethodAddrSpace(); | ||||
13805 | if (AS != LangAS::Default) | ||||
13806 | ArgType = Context.getAddrSpaceQualType(ArgType, AS); | ||||
13807 | QualType RetType = Context.getLValueReferenceType(ArgType); | ||||
13808 | ArgType = Context.getRValueReferenceType(ArgType); | ||||
13809 | |||||
13810 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | ||||
13811 | CXXMoveAssignment, | ||||
13812 | false); | ||||
13813 | |||||
13814 | // An implicitly-declared move assignment operator is an inline public | ||||
13815 | // member of its class. | ||||
13816 | DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); | ||||
13817 | SourceLocation ClassLoc = ClassDecl->getLocation(); | ||||
13818 | DeclarationNameInfo NameInfo(Name, ClassLoc); | ||||
13819 | CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( | ||||
13820 | Context, ClassDecl, ClassLoc, NameInfo, QualType(), | ||||
13821 | /*TInfo=*/nullptr, /*StorageClass=*/SC_None, | ||||
13822 | /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, | ||||
13823 | SourceLocation()); | ||||
13824 | MoveAssignment->setAccess(AS_public); | ||||
13825 | MoveAssignment->setDefaulted(); | ||||
13826 | MoveAssignment->setImplicit(); | ||||
13827 | |||||
13828 | if (getLangOpts().CUDA) { | ||||
13829 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, | ||||
13830 | MoveAssignment, | ||||
13831 | /* ConstRHS */ false, | ||||
13832 | /* Diagnose */ false); | ||||
13833 | } | ||||
13834 | |||||
13835 | // Build an exception specification pointing back at this member. | ||||
13836 | FunctionProtoType::ExtProtoInfo EPI = | ||||
13837 | getImplicitMethodEPI(*this, MoveAssignment); | ||||
13838 | MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); | ||||
13839 | |||||
13840 | // Add the parameter to the operator. | ||||
13841 | ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, | ||||
13842 | ClassLoc, ClassLoc, | ||||
13843 | /*Id=*/nullptr, ArgType, | ||||
13844 | /*TInfo=*/nullptr, SC_None, | ||||
13845 | nullptr); | ||||
13846 | MoveAssignment->setParams(FromParam); | ||||
13847 | |||||
13848 | MoveAssignment->setTrivial( | ||||
13849 | ClassDecl->needsOverloadResolutionForMoveAssignment() | ||||
13850 | ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) | ||||
13851 | : ClassDecl->hasTrivialMoveAssignment()); | ||||
13852 | |||||
13853 | // Note that we have added this copy-assignment operator. | ||||
13854 | ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; | ||||
13855 | |||||
13856 | Scope *S = getScopeForContext(ClassDecl); | ||||
13857 | CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); | ||||
13858 | |||||
13859 | if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { | ||||
13860 | ClassDecl->setImplicitMoveAssignmentIsDeleted(); | ||||
13861 | SetDeclDeleted(MoveAssignment, ClassLoc); | ||||
13862 | } | ||||
13863 | |||||
13864 | if (S) | ||||
13865 | PushOnScopeChains(MoveAssignment, S, false); | ||||
13866 | ClassDecl->addDecl(MoveAssignment); | ||||
13867 | |||||
13868 | return MoveAssignment; | ||||
13869 | } | ||||
13870 | |||||
13871 | /// Check if we're implicitly defining a move assignment operator for a class | ||||
13872 | /// with virtual bases. Such a move assignment might move-assign the virtual | ||||
13873 | /// base multiple times. | ||||
13874 | static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, | ||||
13875 | SourceLocation CurrentLocation) { | ||||
13876 | assert(!Class->isDependentContext() && "should not define dependent move")((!Class->isDependentContext() && "should not define dependent move" ) ? static_cast<void> (0) : __assert_fail ("!Class->isDependentContext() && \"should not define dependent move\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13876, __PRETTY_FUNCTION__)); | ||||
13877 | |||||
13878 | // Only a virtual base could get implicitly move-assigned multiple times. | ||||
13879 | // Only a non-trivial move assignment can observe this. We only want to | ||||
13880 | // diagnose if we implicitly define an assignment operator that assigns | ||||
13881 | // two base classes, both of which move-assign the same virtual base. | ||||
13882 | if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || | ||||
13883 | Class->getNumBases() < 2) | ||||
13884 | return; | ||||
13885 | |||||
13886 | llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; | ||||
13887 | typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; | ||||
13888 | VBaseMap VBases; | ||||
13889 | |||||
13890 | for (auto &BI : Class->bases()) { | ||||
13891 | Worklist.push_back(&BI); | ||||
13892 | while (!Worklist.empty()) { | ||||
13893 | CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); | ||||
13894 | CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); | ||||
13895 | |||||
13896 | // If the base has no non-trivial move assignment operators, | ||||
13897 | // we don't care about moves from it. | ||||
13898 | if (!Base->hasNonTrivialMoveAssignment()) | ||||
13899 | continue; | ||||
13900 | |||||
13901 | // If there's nothing virtual here, skip it. | ||||
13902 | if (!BaseSpec->isVirtual() && !Base->getNumVBases()) | ||||
13903 | continue; | ||||
13904 | |||||
13905 | // If we're not actually going to call a move assignment for this base, | ||||
13906 | // or the selected move assignment is trivial, skip it. | ||||
13907 | Sema::SpecialMemberOverloadResult SMOR = | ||||
13908 | S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, | ||||
13909 | /*ConstArg*/false, /*VolatileArg*/false, | ||||
13910 | /*RValueThis*/true, /*ConstThis*/false, | ||||
13911 | /*VolatileThis*/false); | ||||
13912 | if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || | ||||
13913 | !SMOR.getMethod()->isMoveAssignmentOperator()) | ||||
13914 | continue; | ||||
13915 | |||||
13916 | if (BaseSpec->isVirtual()) { | ||||
13917 | // We're going to move-assign this virtual base, and its move | ||||
13918 | // assignment operator is not trivial. If this can happen for | ||||
13919 | // multiple distinct direct bases of Class, diagnose it. (If it | ||||
13920 | // only happens in one base, we'll diagnose it when synthesizing | ||||
13921 | // that base class's move assignment operator.) | ||||
13922 | CXXBaseSpecifier *&Existing = | ||||
13923 | VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) | ||||
13924 | .first->second; | ||||
13925 | if (Existing && Existing != &BI) { | ||||
13926 | S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) | ||||
13927 | << Class << Base; | ||||
13928 | S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) | ||||
13929 | << (Base->getCanonicalDecl() == | ||||
13930 | Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) | ||||
13931 | << Base << Existing->getType() << Existing->getSourceRange(); | ||||
13932 | S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) | ||||
13933 | << (Base->getCanonicalDecl() == | ||||
13934 | BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) | ||||
13935 | << Base << BI.getType() << BaseSpec->getSourceRange(); | ||||
13936 | |||||
13937 | // Only diagnose each vbase once. | ||||
13938 | Existing = nullptr; | ||||
13939 | } | ||||
13940 | } else { | ||||
13941 | // Only walk over bases that have defaulted move assignment operators. | ||||
13942 | // We assume that any user-provided move assignment operator handles | ||||
13943 | // the multiple-moves-of-vbase case itself somehow. | ||||
13944 | if (!SMOR.getMethod()->isDefaulted()) | ||||
13945 | continue; | ||||
13946 | |||||
13947 | // We're going to move the base classes of Base. Add them to the list. | ||||
13948 | for (auto &BI : Base->bases()) | ||||
13949 | Worklist.push_back(&BI); | ||||
13950 | } | ||||
13951 | } | ||||
13952 | } | ||||
13953 | } | ||||
13954 | |||||
13955 | void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, | ||||
13956 | CXXMethodDecl *MoveAssignOperator) { | ||||
13957 | assert((MoveAssignOperator->isDefaulted() &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator ->isOverloadedOperator() && MoveAssignOperator-> getOverloadedOperator() == OO_Equal && !MoveAssignOperator ->doesThisDeclarationHaveABody() && !MoveAssignOperator ->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function" ) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13962, __PRETTY_FUNCTION__)) | ||||
13958 | MoveAssignOperator->isOverloadedOperator() &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator ->isOverloadedOperator() && MoveAssignOperator-> getOverloadedOperator() == OO_Equal && !MoveAssignOperator ->doesThisDeclarationHaveABody() && !MoveAssignOperator ->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function" ) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13962, __PRETTY_FUNCTION__)) | ||||
13959 | MoveAssignOperator->getOverloadedOperator() == OO_Equal &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator ->isOverloadedOperator() && MoveAssignOperator-> getOverloadedOperator() == OO_Equal && !MoveAssignOperator ->doesThisDeclarationHaveABody() && !MoveAssignOperator ->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function" ) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13962, __PRETTY_FUNCTION__)) | ||||
13960 | !MoveAssignOperator->doesThisDeclarationHaveABody() &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator ->isOverloadedOperator() && MoveAssignOperator-> getOverloadedOperator() == OO_Equal && !MoveAssignOperator ->doesThisDeclarationHaveABody() && !MoveAssignOperator ->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function" ) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13962, __PRETTY_FUNCTION__)) | ||||
13961 | !MoveAssignOperator->isDeleted()) &&(((MoveAssignOperator->isDefaulted() && MoveAssignOperator ->isOverloadedOperator() && MoveAssignOperator-> getOverloadedOperator() == OO_Equal && !MoveAssignOperator ->doesThisDeclarationHaveABody() && !MoveAssignOperator ->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function" ) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13962, __PRETTY_FUNCTION__)) | ||||
13962 | "DefineImplicitMoveAssignment called for wrong function")(((MoveAssignOperator->isDefaulted() && MoveAssignOperator ->isOverloadedOperator() && MoveAssignOperator-> getOverloadedOperator() == OO_Equal && !MoveAssignOperator ->doesThisDeclarationHaveABody() && !MoveAssignOperator ->isDeleted()) && "DefineImplicitMoveAssignment called for wrong function" ) ? static_cast<void> (0) : __assert_fail ("(MoveAssignOperator->isDefaulted() && MoveAssignOperator->isOverloadedOperator() && MoveAssignOperator->getOverloadedOperator() == OO_Equal && !MoveAssignOperator->doesThisDeclarationHaveABody() && !MoveAssignOperator->isDeleted()) && \"DefineImplicitMoveAssignment called for wrong function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 13962, __PRETTY_FUNCTION__)); | ||||
13963 | if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) | ||||
13964 | return; | ||||
13965 | |||||
13966 | CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); | ||||
13967 | if (ClassDecl->isInvalidDecl()) { | ||||
13968 | MoveAssignOperator->setInvalidDecl(); | ||||
13969 | return; | ||||
13970 | } | ||||
13971 | |||||
13972 | // C++0x [class.copy]p28: | ||||
13973 | // The implicitly-defined or move assignment operator for a non-union class | ||||
13974 | // X performs memberwise move assignment of its subobjects. The direct base | ||||
13975 | // classes of X are assigned first, in the order of their declaration in the | ||||
13976 | // base-specifier-list, and then the immediate non-static data members of X | ||||
13977 | // are assigned, in the order in which they were declared in the class | ||||
13978 | // definition. | ||||
13979 | |||||
13980 | // Issue a warning if our implicit move assignment operator will move | ||||
13981 | // from a virtual base more than once. | ||||
13982 | checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); | ||||
13983 | |||||
13984 | SynthesizedFunctionScope Scope(*this, MoveAssignOperator); | ||||
13985 | |||||
13986 | // The exception specification is needed because we are defining the | ||||
13987 | // function. | ||||
13988 | ResolveExceptionSpec(CurrentLocation, | ||||
13989 | MoveAssignOperator->getType()->castAs<FunctionProtoType>()); | ||||
13990 | |||||
13991 | // Add a context note for diagnostics produced after this point. | ||||
13992 | Scope.addContextNote(CurrentLocation); | ||||
13993 | |||||
13994 | // The statements that form the synthesized function body. | ||||
13995 | SmallVector<Stmt*, 8> Statements; | ||||
13996 | |||||
13997 | // The parameter for the "other" object, which we are move from. | ||||
13998 | ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); | ||||
13999 | QualType OtherRefType = Other->getType()-> | ||||
14000 | getAs<RValueReferenceType>()->getPointeeType(); | ||||
14001 | |||||
14002 | // Our location for everything implicitly-generated. | ||||
14003 | SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() | ||||
14004 | ? MoveAssignOperator->getEndLoc() | ||||
14005 | : MoveAssignOperator->getLocation(); | ||||
14006 | |||||
14007 | // Builds a reference to the "other" object. | ||||
14008 | RefBuilder OtherRef(Other, OtherRefType); | ||||
14009 | // Cast to rvalue. | ||||
14010 | MoveCastBuilder MoveOther(OtherRef); | ||||
14011 | |||||
14012 | // Builds the "this" pointer. | ||||
14013 | ThisBuilder This; | ||||
14014 | |||||
14015 | // Assign base classes. | ||||
14016 | bool Invalid = false; | ||||
14017 | for (auto &Base : ClassDecl->bases()) { | ||||
14018 | // C++11 [class.copy]p28: | ||||
14019 | // It is unspecified whether subobjects representing virtual base classes | ||||
14020 | // are assigned more than once by the implicitly-defined copy assignment | ||||
14021 | // operator. | ||||
14022 | // FIXME: Do not assign to a vbase that will be assigned by some other base | ||||
14023 | // class. For a move-assignment, this can result in the vbase being moved | ||||
14024 | // multiple times. | ||||
14025 | |||||
14026 | // Form the assignment: | ||||
14027 | // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); | ||||
14028 | QualType BaseType = Base.getType().getUnqualifiedType(); | ||||
14029 | if (!BaseType->isRecordType()) { | ||||
14030 | Invalid = true; | ||||
14031 | continue; | ||||
14032 | } | ||||
14033 | |||||
14034 | CXXCastPath BasePath; | ||||
14035 | BasePath.push_back(&Base); | ||||
14036 | |||||
14037 | // Construct the "from" expression, which is an implicit cast to the | ||||
14038 | // appropriately-qualified base type. | ||||
14039 | CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); | ||||
14040 | |||||
14041 | // Dereference "this". | ||||
14042 | DerefBuilder DerefThis(This); | ||||
14043 | |||||
14044 | // Implicitly cast "this" to the appropriately-qualified base type. | ||||
14045 | CastBuilder To(DerefThis, | ||||
14046 | Context.getQualifiedType( | ||||
14047 | BaseType, MoveAssignOperator->getMethodQualifiers()), | ||||
14048 | VK_LValue, BasePath); | ||||
14049 | |||||
14050 | // Build the move. | ||||
14051 | StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, | ||||
14052 | To, From, | ||||
14053 | /*CopyingBaseSubobject=*/true, | ||||
14054 | /*Copying=*/false); | ||||
14055 | if (Move.isInvalid()) { | ||||
14056 | MoveAssignOperator->setInvalidDecl(); | ||||
14057 | return; | ||||
14058 | } | ||||
14059 | |||||
14060 | // Success! Record the move. | ||||
14061 | Statements.push_back(Move.getAs<Expr>()); | ||||
14062 | } | ||||
14063 | |||||
14064 | // Assign non-static members. | ||||
14065 | for (auto *Field : ClassDecl->fields()) { | ||||
14066 | // FIXME: We should form some kind of AST representation for the implied | ||||
14067 | // memcpy in a union copy operation. | ||||
14068 | if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) | ||||
14069 | continue; | ||||
14070 | |||||
14071 | if (Field->isInvalidDecl()) { | ||||
14072 | Invalid = true; | ||||
14073 | continue; | ||||
14074 | } | ||||
14075 | |||||
14076 | // Check for members of reference type; we can't move those. | ||||
14077 | if (Field->getType()->isReferenceType()) { | ||||
14078 | Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) | ||||
14079 | << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); | ||||
14080 | Diag(Field->getLocation(), diag::note_declared_at); | ||||
14081 | Invalid = true; | ||||
14082 | continue; | ||||
14083 | } | ||||
14084 | |||||
14085 | // Check for members of const-qualified, non-class type. | ||||
14086 | QualType BaseType = Context.getBaseElementType(Field->getType()); | ||||
14087 | if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { | ||||
14088 | Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) | ||||
14089 | << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); | ||||
14090 | Diag(Field->getLocation(), diag::note_declared_at); | ||||
14091 | Invalid = true; | ||||
14092 | continue; | ||||
14093 | } | ||||
14094 | |||||
14095 | // Suppress assigning zero-width bitfields. | ||||
14096 | if (Field->isZeroLengthBitField(Context)) | ||||
14097 | continue; | ||||
14098 | |||||
14099 | QualType FieldType = Field->getType().getNonReferenceType(); | ||||
14100 | if (FieldType->isIncompleteArrayType()) { | ||||
14101 | assert(ClassDecl->hasFlexibleArrayMember() &&((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14102, __PRETTY_FUNCTION__)) | ||||
14102 | "Incomplete array type is not valid")((ClassDecl->hasFlexibleArrayMember() && "Incomplete array type is not valid" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl->hasFlexibleArrayMember() && \"Incomplete array type is not valid\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14102, __PRETTY_FUNCTION__)); | ||||
14103 | continue; | ||||
14104 | } | ||||
14105 | |||||
14106 | // Build references to the field in the object we're copying from and to. | ||||
14107 | LookupResult MemberLookup(*this, Field->getDeclName(), Loc, | ||||
14108 | LookupMemberName); | ||||
14109 | MemberLookup.addDecl(Field); | ||||
14110 | MemberLookup.resolveKind(); | ||||
14111 | MemberBuilder From(MoveOther, OtherRefType, | ||||
14112 | /*IsArrow=*/false, MemberLookup); | ||||
14113 | MemberBuilder To(This, getCurrentThisType(), | ||||
14114 | /*IsArrow=*/true, MemberLookup); | ||||
14115 | |||||
14116 | assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue((!From.build(*this, Loc)->isLValue() && "Member reference with rvalue base must be rvalue except for reference " "members, which aren't allowed for move assignment.") ? static_cast <void> (0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14118, __PRETTY_FUNCTION__)) | ||||
14117 | "Member reference with rvalue base must be rvalue except for reference "((!From.build(*this, Loc)->isLValue() && "Member reference with rvalue base must be rvalue except for reference " "members, which aren't allowed for move assignment.") ? static_cast <void> (0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14118, __PRETTY_FUNCTION__)) | ||||
14118 | "members, which aren't allowed for move assignment.")((!From.build(*this, Loc)->isLValue() && "Member reference with rvalue base must be rvalue except for reference " "members, which aren't allowed for move assignment.") ? static_cast <void> (0) : __assert_fail ("!From.build(*this, Loc)->isLValue() && \"Member reference with rvalue base must be rvalue except for reference \" \"members, which aren't allowed for move assignment.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14118, __PRETTY_FUNCTION__)); | ||||
14119 | |||||
14120 | // Build the move of this field. | ||||
14121 | StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, | ||||
14122 | To, From, | ||||
14123 | /*CopyingBaseSubobject=*/false, | ||||
14124 | /*Copying=*/false); | ||||
14125 | if (Move.isInvalid()) { | ||||
14126 | MoveAssignOperator->setInvalidDecl(); | ||||
14127 | return; | ||||
14128 | } | ||||
14129 | |||||
14130 | // Success! Record the copy. | ||||
14131 | Statements.push_back(Move.getAs<Stmt>()); | ||||
14132 | } | ||||
14133 | |||||
14134 | if (!Invalid) { | ||||
14135 | // Add a "return *this;" | ||||
14136 | ExprResult ThisObj = | ||||
14137 | CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); | ||||
14138 | |||||
14139 | StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); | ||||
14140 | if (Return.isInvalid()) | ||||
14141 | Invalid = true; | ||||
14142 | else | ||||
14143 | Statements.push_back(Return.getAs<Stmt>()); | ||||
14144 | } | ||||
14145 | |||||
14146 | if (Invalid) { | ||||
14147 | MoveAssignOperator->setInvalidDecl(); | ||||
14148 | return; | ||||
14149 | } | ||||
14150 | |||||
14151 | StmtResult Body; | ||||
14152 | { | ||||
14153 | CompoundScopeRAII CompoundScope(*this); | ||||
14154 | Body = ActOnCompoundStmt(Loc, Loc, Statements, | ||||
14155 | /*isStmtExpr=*/false); | ||||
14156 | assert(!Body.isInvalid() && "Compound statement creation cannot fail")((!Body.isInvalid() && "Compound statement creation cannot fail" ) ? static_cast<void> (0) : __assert_fail ("!Body.isInvalid() && \"Compound statement creation cannot fail\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14156, __PRETTY_FUNCTION__)); | ||||
14157 | } | ||||
14158 | MoveAssignOperator->setBody(Body.getAs<Stmt>()); | ||||
14159 | MoveAssignOperator->markUsed(Context); | ||||
14160 | |||||
14161 | if (ASTMutationListener *L = getASTMutationListener()) { | ||||
14162 | L->CompletedImplicitDefinition(MoveAssignOperator); | ||||
14163 | } | ||||
14164 | } | ||||
14165 | |||||
14166 | CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( | ||||
14167 | CXXRecordDecl *ClassDecl) { | ||||
14168 | // C++ [class.copy]p4: | ||||
14169 | // If the class definition does not explicitly declare a copy | ||||
14170 | // constructor, one is declared implicitly. | ||||
14171 | assert(ClassDecl->needsImplicitCopyConstructor())((ClassDecl->needsImplicitCopyConstructor()) ? static_cast <void> (0) : __assert_fail ("ClassDecl->needsImplicitCopyConstructor()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14171, __PRETTY_FUNCTION__)); | ||||
14172 | |||||
14173 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); | ||||
14174 | if (DSM.isAlreadyBeingDeclared()) | ||||
14175 | return nullptr; | ||||
14176 | |||||
14177 | QualType ClassType = Context.getTypeDeclType(ClassDecl); | ||||
14178 | QualType ArgType = ClassType; | ||||
14179 | bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); | ||||
14180 | if (Const) | ||||
14181 | ArgType = ArgType.withConst(); | ||||
14182 | |||||
14183 | LangAS AS = getDefaultCXXMethodAddrSpace(); | ||||
14184 | if (AS != LangAS::Default) | ||||
14185 | ArgType = Context.getAddrSpaceQualType(ArgType, AS); | ||||
14186 | |||||
14187 | ArgType = Context.getLValueReferenceType(ArgType); | ||||
14188 | |||||
14189 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | ||||
14190 | CXXCopyConstructor, | ||||
14191 | Const); | ||||
14192 | |||||
14193 | DeclarationName Name | ||||
14194 | = Context.DeclarationNames.getCXXConstructorName( | ||||
14195 | Context.getCanonicalType(ClassType)); | ||||
14196 | SourceLocation ClassLoc = ClassDecl->getLocation(); | ||||
14197 | DeclarationNameInfo NameInfo(Name, ClassLoc); | ||||
14198 | |||||
14199 | // An implicitly-declared copy constructor is an inline public | ||||
14200 | // member of its class. | ||||
14201 | CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( | ||||
14202 | Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, | ||||
14203 | ExplicitSpecifier(), | ||||
14204 | /*isInline=*/true, | ||||
14205 | /*isImplicitlyDeclared=*/true, | ||||
14206 | Constexpr ? CSK_constexpr : CSK_unspecified); | ||||
14207 | CopyConstructor->setAccess(AS_public); | ||||
14208 | CopyConstructor->setDefaulted(); | ||||
14209 | |||||
14210 | if (getLangOpts().CUDA) { | ||||
14211 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, | ||||
14212 | CopyConstructor, | ||||
14213 | /* ConstRHS */ Const, | ||||
14214 | /* Diagnose */ false); | ||||
14215 | } | ||||
14216 | |||||
14217 | setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); | ||||
14218 | |||||
14219 | // Add the parameter to the constructor. | ||||
14220 | ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, | ||||
14221 | ClassLoc, ClassLoc, | ||||
14222 | /*IdentifierInfo=*/nullptr, | ||||
14223 | ArgType, /*TInfo=*/nullptr, | ||||
14224 | SC_None, nullptr); | ||||
14225 | CopyConstructor->setParams(FromParam); | ||||
14226 | |||||
14227 | CopyConstructor->setTrivial( | ||||
14228 | ClassDecl->needsOverloadResolutionForCopyConstructor() | ||||
14229 | ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) | ||||
14230 | : ClassDecl->hasTrivialCopyConstructor()); | ||||
14231 | |||||
14232 | CopyConstructor->setTrivialForCall( | ||||
14233 | ClassDecl->hasAttr<TrivialABIAttr>() || | ||||
14234 | (ClassDecl->needsOverloadResolutionForCopyConstructor() | ||||
14235 | ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, | ||||
14236 | TAH_ConsiderTrivialABI) | ||||
14237 | : ClassDecl->hasTrivialCopyConstructorForCall())); | ||||
14238 | |||||
14239 | // Note that we have declared this constructor. | ||||
14240 | ++getASTContext().NumImplicitCopyConstructorsDeclared; | ||||
14241 | |||||
14242 | Scope *S = getScopeForContext(ClassDecl); | ||||
14243 | CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); | ||||
14244 | |||||
14245 | if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { | ||||
14246 | ClassDecl->setImplicitCopyConstructorIsDeleted(); | ||||
14247 | SetDeclDeleted(CopyConstructor, ClassLoc); | ||||
14248 | } | ||||
14249 | |||||
14250 | if (S) | ||||
14251 | PushOnScopeChains(CopyConstructor, S, false); | ||||
14252 | ClassDecl->addDecl(CopyConstructor); | ||||
14253 | |||||
14254 | return CopyConstructor; | ||||
14255 | } | ||||
14256 | |||||
14257 | void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, | ||||
14258 | CXXConstructorDecl *CopyConstructor) { | ||||
14259 | assert((CopyConstructor->isDefaulted() &&(((CopyConstructor->isDefaulted() && CopyConstructor ->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody () && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor" ) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14263, __PRETTY_FUNCTION__)) | ||||
14260 | CopyConstructor->isCopyConstructor() &&(((CopyConstructor->isDefaulted() && CopyConstructor ->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody () && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor" ) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14263, __PRETTY_FUNCTION__)) | ||||
14261 | !CopyConstructor->doesThisDeclarationHaveABody() &&(((CopyConstructor->isDefaulted() && CopyConstructor ->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody () && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor" ) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14263, __PRETTY_FUNCTION__)) | ||||
14262 | !CopyConstructor->isDeleted()) &&(((CopyConstructor->isDefaulted() && CopyConstructor ->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody () && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor" ) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14263, __PRETTY_FUNCTION__)) | ||||
14263 | "DefineImplicitCopyConstructor - call it for implicit copy ctor")(((CopyConstructor->isDefaulted() && CopyConstructor ->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody () && !CopyConstructor->isDeleted()) && "DefineImplicitCopyConstructor - call it for implicit copy ctor" ) ? static_cast<void> (0) : __assert_fail ("(CopyConstructor->isDefaulted() && CopyConstructor->isCopyConstructor() && !CopyConstructor->doesThisDeclarationHaveABody() && !CopyConstructor->isDeleted()) && \"DefineImplicitCopyConstructor - call it for implicit copy ctor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14263, __PRETTY_FUNCTION__)); | ||||
14264 | if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) | ||||
14265 | return; | ||||
14266 | |||||
14267 | CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); | ||||
14268 | assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor")((ClassDecl && "DefineImplicitCopyConstructor - invalid constructor" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitCopyConstructor - invalid constructor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14268, __PRETTY_FUNCTION__)); | ||||
14269 | |||||
14270 | SynthesizedFunctionScope Scope(*this, CopyConstructor); | ||||
14271 | |||||
14272 | // The exception specification is needed because we are defining the | ||||
14273 | // function. | ||||
14274 | ResolveExceptionSpec(CurrentLocation, | ||||
14275 | CopyConstructor->getType()->castAs<FunctionProtoType>()); | ||||
14276 | MarkVTableUsed(CurrentLocation, ClassDecl); | ||||
14277 | |||||
14278 | // Add a context note for diagnostics produced after this point. | ||||
14279 | Scope.addContextNote(CurrentLocation); | ||||
14280 | |||||
14281 | // C++11 [class.copy]p7: | ||||
14282 | // The [definition of an implicitly declared copy constructor] is | ||||
14283 | // deprecated if the class has a user-declared copy assignment operator | ||||
14284 | // or a user-declared destructor. | ||||
14285 | if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) | ||||
14286 | diagnoseDeprecatedCopyOperation(*this, CopyConstructor); | ||||
14287 | |||||
14288 | if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { | ||||
14289 | CopyConstructor->setInvalidDecl(); | ||||
14290 | } else { | ||||
14291 | SourceLocation Loc = CopyConstructor->getEndLoc().isValid() | ||||
14292 | ? CopyConstructor->getEndLoc() | ||||
14293 | : CopyConstructor->getLocation(); | ||||
14294 | Sema::CompoundScopeRAII CompoundScope(*this); | ||||
14295 | CopyConstructor->setBody( | ||||
14296 | ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); | ||||
14297 | CopyConstructor->markUsed(Context); | ||||
14298 | } | ||||
14299 | |||||
14300 | if (ASTMutationListener *L = getASTMutationListener()) { | ||||
14301 | L->CompletedImplicitDefinition(CopyConstructor); | ||||
14302 | } | ||||
14303 | } | ||||
14304 | |||||
14305 | CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( | ||||
14306 | CXXRecordDecl *ClassDecl) { | ||||
14307 | assert(ClassDecl->needsImplicitMoveConstructor())((ClassDecl->needsImplicitMoveConstructor()) ? static_cast <void> (0) : __assert_fail ("ClassDecl->needsImplicitMoveConstructor()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14307, __PRETTY_FUNCTION__)); | ||||
14308 | |||||
14309 | DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); | ||||
14310 | if (DSM.isAlreadyBeingDeclared()) | ||||
14311 | return nullptr; | ||||
14312 | |||||
14313 | QualType ClassType = Context.getTypeDeclType(ClassDecl); | ||||
14314 | |||||
14315 | QualType ArgType = ClassType; | ||||
14316 | LangAS AS = getDefaultCXXMethodAddrSpace(); | ||||
14317 | if (AS != LangAS::Default) | ||||
14318 | ArgType = Context.getAddrSpaceQualType(ClassType, AS); | ||||
14319 | ArgType = Context.getRValueReferenceType(ArgType); | ||||
14320 | |||||
14321 | bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, | ||||
14322 | CXXMoveConstructor, | ||||
14323 | false); | ||||
14324 | |||||
14325 | DeclarationName Name | ||||
14326 | = Context.DeclarationNames.getCXXConstructorName( | ||||
14327 | Context.getCanonicalType(ClassType)); | ||||
14328 | SourceLocation ClassLoc = ClassDecl->getLocation(); | ||||
14329 | DeclarationNameInfo NameInfo(Name, ClassLoc); | ||||
14330 | |||||
14331 | // C++11 [class.copy]p11: | ||||
14332 | // An implicitly-declared copy/move constructor is an inline public | ||||
14333 | // member of its class. | ||||
14334 | CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( | ||||
14335 | Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, | ||||
14336 | ExplicitSpecifier(), | ||||
14337 | /*isInline=*/true, | ||||
14338 | /*isImplicitlyDeclared=*/true, | ||||
14339 | Constexpr ? CSK_constexpr : CSK_unspecified); | ||||
14340 | MoveConstructor->setAccess(AS_public); | ||||
14341 | MoveConstructor->setDefaulted(); | ||||
14342 | |||||
14343 | if (getLangOpts().CUDA) { | ||||
14344 | inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, | ||||
14345 | MoveConstructor, | ||||
14346 | /* ConstRHS */ false, | ||||
14347 | /* Diagnose */ false); | ||||
14348 | } | ||||
14349 | |||||
14350 | setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); | ||||
14351 | |||||
14352 | // Add the parameter to the constructor. | ||||
14353 | ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, | ||||
14354 | ClassLoc, ClassLoc, | ||||
14355 | /*IdentifierInfo=*/nullptr, | ||||
14356 | ArgType, /*TInfo=*/nullptr, | ||||
14357 | SC_None, nullptr); | ||||
14358 | MoveConstructor->setParams(FromParam); | ||||
14359 | |||||
14360 | MoveConstructor->setTrivial( | ||||
14361 | ClassDecl->needsOverloadResolutionForMoveConstructor() | ||||
14362 | ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) | ||||
14363 | : ClassDecl->hasTrivialMoveConstructor()); | ||||
14364 | |||||
14365 | MoveConstructor->setTrivialForCall( | ||||
14366 | ClassDecl->hasAttr<TrivialABIAttr>() || | ||||
14367 | (ClassDecl->needsOverloadResolutionForMoveConstructor() | ||||
14368 | ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, | ||||
14369 | TAH_ConsiderTrivialABI) | ||||
14370 | : ClassDecl->hasTrivialMoveConstructorForCall())); | ||||
14371 | |||||
14372 | // Note that we have declared this constructor. | ||||
14373 | ++getASTContext().NumImplicitMoveConstructorsDeclared; | ||||
14374 | |||||
14375 | Scope *S = getScopeForContext(ClassDecl); | ||||
14376 | CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); | ||||
14377 | |||||
14378 | if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { | ||||
14379 | ClassDecl->setImplicitMoveConstructorIsDeleted(); | ||||
14380 | SetDeclDeleted(MoveConstructor, ClassLoc); | ||||
14381 | } | ||||
14382 | |||||
14383 | if (S) | ||||
14384 | PushOnScopeChains(MoveConstructor, S, false); | ||||
14385 | ClassDecl->addDecl(MoveConstructor); | ||||
14386 | |||||
14387 | return MoveConstructor; | ||||
14388 | } | ||||
14389 | |||||
14390 | void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, | ||||
14391 | CXXConstructorDecl *MoveConstructor) { | ||||
14392 | assert((MoveConstructor->isDefaulted() &&(((MoveConstructor->isDefaulted() && MoveConstructor ->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody () && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor" ) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14396, __PRETTY_FUNCTION__)) | ||||
14393 | MoveConstructor->isMoveConstructor() &&(((MoveConstructor->isDefaulted() && MoveConstructor ->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody () && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor" ) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14396, __PRETTY_FUNCTION__)) | ||||
14394 | !MoveConstructor->doesThisDeclarationHaveABody() &&(((MoveConstructor->isDefaulted() && MoveConstructor ->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody () && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor" ) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14396, __PRETTY_FUNCTION__)) | ||||
14395 | !MoveConstructor->isDeleted()) &&(((MoveConstructor->isDefaulted() && MoveConstructor ->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody () && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor" ) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14396, __PRETTY_FUNCTION__)) | ||||
14396 | "DefineImplicitMoveConstructor - call it for implicit move ctor")(((MoveConstructor->isDefaulted() && MoveConstructor ->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody () && !MoveConstructor->isDeleted()) && "DefineImplicitMoveConstructor - call it for implicit move ctor" ) ? static_cast<void> (0) : __assert_fail ("(MoveConstructor->isDefaulted() && MoveConstructor->isMoveConstructor() && !MoveConstructor->doesThisDeclarationHaveABody() && !MoveConstructor->isDeleted()) && \"DefineImplicitMoveConstructor - call it for implicit move ctor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14396, __PRETTY_FUNCTION__)); | ||||
14397 | if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) | ||||
14398 | return; | ||||
14399 | |||||
14400 | CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); | ||||
14401 | assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor")((ClassDecl && "DefineImplicitMoveConstructor - invalid constructor" ) ? static_cast<void> (0) : __assert_fail ("ClassDecl && \"DefineImplicitMoveConstructor - invalid constructor\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14401, __PRETTY_FUNCTION__)); | ||||
14402 | |||||
14403 | SynthesizedFunctionScope Scope(*this, MoveConstructor); | ||||
14404 | |||||
14405 | // The exception specification is needed because we are defining the | ||||
14406 | // function. | ||||
14407 | ResolveExceptionSpec(CurrentLocation, | ||||
14408 | MoveConstructor->getType()->castAs<FunctionProtoType>()); | ||||
14409 | MarkVTableUsed(CurrentLocation, ClassDecl); | ||||
14410 | |||||
14411 | // Add a context note for diagnostics produced after this point. | ||||
14412 | Scope.addContextNote(CurrentLocation); | ||||
14413 | |||||
14414 | if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { | ||||
14415 | MoveConstructor->setInvalidDecl(); | ||||
14416 | } else { | ||||
14417 | SourceLocation Loc = MoveConstructor->getEndLoc().isValid() | ||||
14418 | ? MoveConstructor->getEndLoc() | ||||
14419 | : MoveConstructor->getLocation(); | ||||
14420 | Sema::CompoundScopeRAII CompoundScope(*this); | ||||
14421 | MoveConstructor->setBody(ActOnCompoundStmt( | ||||
14422 | Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); | ||||
14423 | MoveConstructor->markUsed(Context); | ||||
14424 | } | ||||
14425 | |||||
14426 | if (ASTMutationListener *L = getASTMutationListener()) { | ||||
14427 | L->CompletedImplicitDefinition(MoveConstructor); | ||||
14428 | } | ||||
14429 | } | ||||
14430 | |||||
14431 | bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { | ||||
14432 | return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); | ||||
14433 | } | ||||
14434 | |||||
14435 | void Sema::DefineImplicitLambdaToFunctionPointerConversion( | ||||
14436 | SourceLocation CurrentLocation, | ||||
14437 | CXXConversionDecl *Conv) { | ||||
14438 | SynthesizedFunctionScope Scope(*this, Conv); | ||||
14439 | assert(!Conv->getReturnType()->isUndeducedType())((!Conv->getReturnType()->isUndeducedType()) ? static_cast <void> (0) : __assert_fail ("!Conv->getReturnType()->isUndeducedType()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14439, __PRETTY_FUNCTION__)); | ||||
14440 | |||||
14441 | CXXRecordDecl *Lambda = Conv->getParent(); | ||||
14442 | FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); | ||||
14443 | FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); | ||||
14444 | |||||
14445 | if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { | ||||
14446 | CallOp = InstantiateFunctionDeclaration( | ||||
14447 | CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); | ||||
14448 | if (!CallOp) | ||||
14449 | return; | ||||
14450 | |||||
14451 | Invoker = InstantiateFunctionDeclaration( | ||||
14452 | Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); | ||||
14453 | if (!Invoker) | ||||
14454 | return; | ||||
14455 | } | ||||
14456 | |||||
14457 | if (CallOp->isInvalidDecl()) | ||||
14458 | return; | ||||
14459 | |||||
14460 | // Mark the call operator referenced (and add to pending instantiations | ||||
14461 | // if necessary). | ||||
14462 | // For both the conversion and static-invoker template specializations | ||||
14463 | // we construct their body's in this function, so no need to add them | ||||
14464 | // to the PendingInstantiations. | ||||
14465 | MarkFunctionReferenced(CurrentLocation, CallOp); | ||||
14466 | |||||
14467 | // Fill in the __invoke function with a dummy implementation. IR generation | ||||
14468 | // will fill in the actual details. Update its type in case it contained | ||||
14469 | // an 'auto'. | ||||
14470 | Invoker->markUsed(Context); | ||||
14471 | Invoker->setReferenced(); | ||||
14472 | Invoker->setType(Conv->getReturnType()->getPointeeType()); | ||||
14473 | Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); | ||||
14474 | |||||
14475 | // Construct the body of the conversion function { return __invoke; }. | ||||
14476 | Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), | ||||
14477 | VK_LValue, Conv->getLocation()); | ||||
14478 | assert(FunctionRef && "Can't refer to __invoke function?")((FunctionRef && "Can't refer to __invoke function?") ? static_cast<void> (0) : __assert_fail ("FunctionRef && \"Can't refer to __invoke function?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14478, __PRETTY_FUNCTION__)); | ||||
14479 | Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); | ||||
14480 | Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), | ||||
14481 | Conv->getLocation())); | ||||
14482 | Conv->markUsed(Context); | ||||
14483 | Conv->setReferenced(); | ||||
14484 | |||||
14485 | if (ASTMutationListener *L = getASTMutationListener()) { | ||||
14486 | L->CompletedImplicitDefinition(Conv); | ||||
14487 | L->CompletedImplicitDefinition(Invoker); | ||||
14488 | } | ||||
14489 | } | ||||
14490 | |||||
14491 | |||||
14492 | |||||
14493 | void Sema::DefineImplicitLambdaToBlockPointerConversion( | ||||
14494 | SourceLocation CurrentLocation, | ||||
14495 | CXXConversionDecl *Conv) | ||||
14496 | { | ||||
14497 | assert(!Conv->getParent()->isGenericLambda())((!Conv->getParent()->isGenericLambda()) ? static_cast< void> (0) : __assert_fail ("!Conv->getParent()->isGenericLambda()" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14497, __PRETTY_FUNCTION__)); | ||||
14498 | |||||
14499 | SynthesizedFunctionScope Scope(*this, Conv); | ||||
14500 | |||||
14501 | // Copy-initialize the lambda object as needed to capture it. | ||||
14502 | Expr *This = ActOnCXXThis(CurrentLocation).get(); | ||||
14503 | Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); | ||||
14504 | |||||
14505 | ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, | ||||
14506 | Conv->getLocation(), | ||||
14507 | Conv, DerefThis); | ||||
14508 | |||||
14509 | // If we're not under ARC, make sure we still get the _Block_copy/autorelease | ||||
14510 | // behavior. Note that only the general conversion function does this | ||||
14511 | // (since it's unusable otherwise); in the case where we inline the | ||||
14512 | // block literal, it has block literal lifetime semantics. | ||||
14513 | if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) | ||||
14514 | BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), | ||||
14515 | CK_CopyAndAutoreleaseBlockObject, | ||||
14516 | BuildBlock.get(), nullptr, VK_RValue); | ||||
14517 | |||||
14518 | if (BuildBlock.isInvalid()) { | ||||
14519 | Diag(CurrentLocation, diag::note_lambda_to_block_conv); | ||||
14520 | Conv->setInvalidDecl(); | ||||
14521 | return; | ||||
14522 | } | ||||
14523 | |||||
14524 | // Create the return statement that returns the block from the conversion | ||||
14525 | // function. | ||||
14526 | StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); | ||||
14527 | if (Return.isInvalid()) { | ||||
14528 | Diag(CurrentLocation, diag::note_lambda_to_block_conv); | ||||
14529 | Conv->setInvalidDecl(); | ||||
14530 | return; | ||||
14531 | } | ||||
14532 | |||||
14533 | // Set the body of the conversion function. | ||||
14534 | Stmt *ReturnS = Return.get(); | ||||
14535 | Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), | ||||
14536 | Conv->getLocation())); | ||||
14537 | Conv->markUsed(Context); | ||||
14538 | |||||
14539 | // We're done; notify the mutation listener, if any. | ||||
14540 | if (ASTMutationListener *L = getASTMutationListener()) { | ||||
14541 | L->CompletedImplicitDefinition(Conv); | ||||
14542 | } | ||||
14543 | } | ||||
14544 | |||||
14545 | /// Determine whether the given list arguments contains exactly one | ||||
14546 | /// "real" (non-default) argument. | ||||
14547 | static bool hasOneRealArgument(MultiExprArg Args) { | ||||
14548 | switch (Args.size()) { | ||||
14549 | case 0: | ||||
14550 | return false; | ||||
14551 | |||||
14552 | default: | ||||
14553 | if (!Args[1]->isDefaultArgument()) | ||||
14554 | return false; | ||||
14555 | |||||
14556 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
14557 | case 1: | ||||
14558 | return !Args[0]->isDefaultArgument(); | ||||
14559 | } | ||||
14560 | |||||
14561 | return false; | ||||
14562 | } | ||||
14563 | |||||
14564 | ExprResult | ||||
14565 | Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, | ||||
14566 | NamedDecl *FoundDecl, | ||||
14567 | CXXConstructorDecl *Constructor, | ||||
14568 | MultiExprArg ExprArgs, | ||||
14569 | bool HadMultipleCandidates, | ||||
14570 | bool IsListInitialization, | ||||
14571 | bool IsStdInitListInitialization, | ||||
14572 | bool RequiresZeroInit, | ||||
14573 | unsigned ConstructKind, | ||||
14574 | SourceRange ParenRange) { | ||||
14575 | bool Elidable = false; | ||||
14576 | |||||
14577 | // C++0x [class.copy]p34: | ||||
14578 | // When certain criteria are met, an implementation is allowed to | ||||
14579 | // omit the copy/move construction of a class object, even if the | ||||
14580 | // copy/move constructor and/or destructor for the object have | ||||
14581 | // side effects. [...] | ||||
14582 | // - when a temporary class object that has not been bound to a | ||||
14583 | // reference (12.2) would be copied/moved to a class object | ||||
14584 | // with the same cv-unqualified type, the copy/move operation | ||||
14585 | // can be omitted by constructing the temporary object | ||||
14586 | // directly into the target of the omitted copy/move | ||||
14587 | if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && | ||||
14588 | Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { | ||||
14589 | Expr *SubExpr = ExprArgs[0]; | ||||
14590 | Elidable = SubExpr->isTemporaryObject( | ||||
14591 | Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); | ||||
14592 | } | ||||
14593 | |||||
14594 | return BuildCXXConstructExpr(ConstructLoc, DeclInitType, | ||||
14595 | FoundDecl, Constructor, | ||||
14596 | Elidable, ExprArgs, HadMultipleCandidates, | ||||
14597 | IsListInitialization, | ||||
14598 | IsStdInitListInitialization, RequiresZeroInit, | ||||
14599 | ConstructKind, ParenRange); | ||||
14600 | } | ||||
14601 | |||||
14602 | ExprResult | ||||
14603 | Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, | ||||
14604 | NamedDecl *FoundDecl, | ||||
14605 | CXXConstructorDecl *Constructor, | ||||
14606 | bool Elidable, | ||||
14607 | MultiExprArg ExprArgs, | ||||
14608 | bool HadMultipleCandidates, | ||||
14609 | bool IsListInitialization, | ||||
14610 | bool IsStdInitListInitialization, | ||||
14611 | bool RequiresZeroInit, | ||||
14612 | unsigned ConstructKind, | ||||
14613 | SourceRange ParenRange) { | ||||
14614 | if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { | ||||
14615 | Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); | ||||
14616 | if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) | ||||
14617 | return ExprError(); | ||||
14618 | } | ||||
14619 | |||||
14620 | return BuildCXXConstructExpr( | ||||
14621 | ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, | ||||
14622 | HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, | ||||
14623 | RequiresZeroInit, ConstructKind, ParenRange); | ||||
14624 | } | ||||
14625 | |||||
14626 | /// BuildCXXConstructExpr - Creates a complete call to a constructor, | ||||
14627 | /// including handling of its default argument expressions. | ||||
14628 | ExprResult | ||||
14629 | Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, | ||||
14630 | CXXConstructorDecl *Constructor, | ||||
14631 | bool Elidable, | ||||
14632 | MultiExprArg ExprArgs, | ||||
14633 | bool HadMultipleCandidates, | ||||
14634 | bool IsListInitialization, | ||||
14635 | bool IsStdInitListInitialization, | ||||
14636 | bool RequiresZeroInit, | ||||
14637 | unsigned ConstructKind, | ||||
14638 | SourceRange ParenRange) { | ||||
14639 | assert(declaresSameEntity(((declaresSameEntity( Constructor->getParent(), DeclInitType ->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && "given constructor for wrong type") ? static_cast<void> (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14642, __PRETTY_FUNCTION__)) | ||||
14640 | Constructor->getParent(),((declaresSameEntity( Constructor->getParent(), DeclInitType ->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && "given constructor for wrong type") ? static_cast<void> (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14642, __PRETTY_FUNCTION__)) | ||||
14641 | DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&((declaresSameEntity( Constructor->getParent(), DeclInitType ->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && "given constructor for wrong type") ? static_cast<void> (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14642, __PRETTY_FUNCTION__)) | ||||
14642 | "given constructor for wrong type")((declaresSameEntity( Constructor->getParent(), DeclInitType ->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && "given constructor for wrong type") ? static_cast<void> (0) : __assert_fail ("declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && \"given constructor for wrong type\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14642, __PRETTY_FUNCTION__)); | ||||
14643 | MarkFunctionReferenced(ConstructLoc, Constructor); | ||||
14644 | if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) | ||||
14645 | return ExprError(); | ||||
14646 | |||||
14647 | return CXXConstructExpr::Create( | ||||
14648 | Context, DeclInitType, ConstructLoc, Constructor, Elidable, | ||||
14649 | ExprArgs, HadMultipleCandidates, IsListInitialization, | ||||
14650 | IsStdInitListInitialization, RequiresZeroInit, | ||||
14651 | static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), | ||||
14652 | ParenRange); | ||||
14653 | } | ||||
14654 | |||||
14655 | ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { | ||||
14656 | assert(Field->hasInClassInitializer())((Field->hasInClassInitializer()) ? static_cast<void> (0) : __assert_fail ("Field->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14656, __PRETTY_FUNCTION__)); | ||||
14657 | |||||
14658 | // If we already have the in-class initializer nothing needs to be done. | ||||
14659 | if (Field->getInClassInitializer()) | ||||
14660 | return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); | ||||
14661 | |||||
14662 | // If we might have already tried and failed to instantiate, don't try again. | ||||
14663 | if (Field->isInvalidDecl()) | ||||
14664 | return ExprError(); | ||||
14665 | |||||
14666 | // Maybe we haven't instantiated the in-class initializer. Go check the | ||||
14667 | // pattern FieldDecl to see if it has one. | ||||
14668 | CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); | ||||
14669 | |||||
14670 | if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { | ||||
14671 | CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); | ||||
14672 | DeclContext::lookup_result Lookup = | ||||
14673 | ClassPattern->lookup(Field->getDeclName()); | ||||
14674 | |||||
14675 | // Lookup can return at most two results: the pattern for the field, or the | ||||
14676 | // injected class name of the parent record. No other member can have the | ||||
14677 | // same name as the field. | ||||
14678 | // In modules mode, lookup can return multiple results (coming from | ||||
14679 | // different modules). | ||||
14680 | assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&(((getLangOpts().Modules || (!Lookup.empty() && Lookup .size() <= 2)) && "more than two lookup results for field name" ) ? static_cast<void> (0) : __assert_fail ("(getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && \"more than two lookup results for field name\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14681, __PRETTY_FUNCTION__)) | ||||
14681 | "more than two lookup results for field name")(((getLangOpts().Modules || (!Lookup.empty() && Lookup .size() <= 2)) && "more than two lookup results for field name" ) ? static_cast<void> (0) : __assert_fail ("(getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && \"more than two lookup results for field name\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14681, __PRETTY_FUNCTION__)); | ||||
14682 | FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); | ||||
14683 | if (!Pattern) { | ||||
14684 | assert(isa<CXXRecordDecl>(Lookup[0]) &&((isa<CXXRecordDecl>(Lookup[0]) && "cannot have other non-field member with same name" ) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(Lookup[0]) && \"cannot have other non-field member with same name\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14685, __PRETTY_FUNCTION__)) | ||||
14685 | "cannot have other non-field member with same name")((isa<CXXRecordDecl>(Lookup[0]) && "cannot have other non-field member with same name" ) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(Lookup[0]) && \"cannot have other non-field member with same name\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14685, __PRETTY_FUNCTION__)); | ||||
14686 | for (auto L : Lookup) | ||||
14687 | if (isa<FieldDecl>(L)) { | ||||
14688 | Pattern = cast<FieldDecl>(L); | ||||
14689 | break; | ||||
14690 | } | ||||
14691 | assert(Pattern && "We must have set the Pattern!")((Pattern && "We must have set the Pattern!") ? static_cast <void> (0) : __assert_fail ("Pattern && \"We must have set the Pattern!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14691, __PRETTY_FUNCTION__)); | ||||
14692 | } | ||||
14693 | |||||
14694 | if (!Pattern->hasInClassInitializer() || | ||||
14695 | InstantiateInClassInitializer(Loc, Field, Pattern, | ||||
14696 | getTemplateInstantiationArgs(Field))) { | ||||
14697 | // Don't diagnose this again. | ||||
14698 | Field->setInvalidDecl(); | ||||
14699 | return ExprError(); | ||||
14700 | } | ||||
14701 | return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); | ||||
14702 | } | ||||
14703 | |||||
14704 | // DR1351: | ||||
14705 | // If the brace-or-equal-initializer of a non-static data member | ||||
14706 | // invokes a defaulted default constructor of its class or of an | ||||
14707 | // enclosing class in a potentially evaluated subexpression, the | ||||
14708 | // program is ill-formed. | ||||
14709 | // | ||||
14710 | // This resolution is unworkable: the exception specification of the | ||||
14711 | // default constructor can be needed in an unevaluated context, in | ||||
14712 | // particular, in the operand of a noexcept-expression, and we can be | ||||
14713 | // unable to compute an exception specification for an enclosed class. | ||||
14714 | // | ||||
14715 | // Any attempt to resolve the exception specification of a defaulted default | ||||
14716 | // constructor before the initializer is lexically complete will ultimately | ||||
14717 | // come here at which point we can diagnose it. | ||||
14718 | RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); | ||||
14719 | Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) | ||||
14720 | << OutermostClass << Field; | ||||
14721 | Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); | ||||
14722 | // Recover by marking the field invalid, unless we're in a SFINAE context. | ||||
14723 | if (!isSFINAEContext()) | ||||
14724 | Field->setInvalidDecl(); | ||||
14725 | return ExprError(); | ||||
14726 | } | ||||
14727 | |||||
14728 | void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { | ||||
14729 | if (VD->isInvalidDecl()) return; | ||||
14730 | |||||
14731 | CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); | ||||
14732 | if (ClassDecl->isInvalidDecl()) return; | ||||
14733 | if (ClassDecl->hasIrrelevantDestructor()) return; | ||||
14734 | if (ClassDecl->isDependentContext()) return; | ||||
14735 | |||||
14736 | if (VD->isNoDestroy(getASTContext())) | ||||
14737 | return; | ||||
14738 | |||||
14739 | CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); | ||||
14740 | |||||
14741 | // If this is an array, we'll require the destructor during initialization, so | ||||
14742 | // we can skip over this. We still want to emit exit-time destructor warnings | ||||
14743 | // though. | ||||
14744 | if (!VD->getType()->isArrayType()) { | ||||
14745 | MarkFunctionReferenced(VD->getLocation(), Destructor); | ||||
14746 | CheckDestructorAccess(VD->getLocation(), Destructor, | ||||
14747 | PDiag(diag::err_access_dtor_var) | ||||
14748 | << VD->getDeclName() << VD->getType()); | ||||
14749 | DiagnoseUseOfDecl(Destructor, VD->getLocation()); | ||||
14750 | } | ||||
14751 | |||||
14752 | if (Destructor->isTrivial()) return; | ||||
14753 | |||||
14754 | // If the destructor is constexpr, check whether the variable has constant | ||||
14755 | // destruction now. | ||||
14756 | if (Destructor->isConstexpr() && VD->getInit() && | ||||
14757 | !VD->getInit()->isValueDependent() && VD->evaluateValue()) { | ||||
14758 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||
14759 | if (!VD->evaluateDestruction(Notes) && VD->isConstexpr()) { | ||||
14760 | Diag(VD->getLocation(), | ||||
14761 | diag::err_constexpr_var_requires_const_destruction) << VD; | ||||
14762 | for (unsigned I = 0, N = Notes.size(); I != N; ++I) | ||||
14763 | Diag(Notes[I].first, Notes[I].second); | ||||
14764 | } | ||||
14765 | } | ||||
14766 | |||||
14767 | if (!VD->hasGlobalStorage()) return; | ||||
14768 | |||||
14769 | // Emit warning for non-trivial dtor in global scope (a real global, | ||||
14770 | // class-static, function-static). | ||||
14771 | Diag(VD->getLocation(), diag::warn_exit_time_destructor); | ||||
14772 | |||||
14773 | // TODO: this should be re-enabled for static locals by !CXAAtExit | ||||
14774 | if (!VD->isStaticLocal()) | ||||
14775 | Diag(VD->getLocation(), diag::warn_global_destructor); | ||||
14776 | } | ||||
14777 | |||||
14778 | /// Given a constructor and the set of arguments provided for the | ||||
14779 | /// constructor, convert the arguments and add any required default arguments | ||||
14780 | /// to form a proper call to this constructor. | ||||
14781 | /// | ||||
14782 | /// \returns true if an error occurred, false otherwise. | ||||
14783 | bool | ||||
14784 | Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, | ||||
14785 | MultiExprArg ArgsPtr, | ||||
14786 | SourceLocation Loc, | ||||
14787 | SmallVectorImpl<Expr*> &ConvertedArgs, | ||||
14788 | bool AllowExplicit, | ||||
14789 | bool IsListInitialization) { | ||||
14790 | // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. | ||||
14791 | unsigned NumArgs = ArgsPtr.size(); | ||||
14792 | Expr **Args = ArgsPtr.data(); | ||||
14793 | |||||
14794 | const FunctionProtoType *Proto | ||||
14795 | = Constructor->getType()->getAs<FunctionProtoType>(); | ||||
14796 | assert(Proto && "Constructor without a prototype?")((Proto && "Constructor without a prototype?") ? static_cast <void> (0) : __assert_fail ("Proto && \"Constructor without a prototype?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14796, __PRETTY_FUNCTION__)); | ||||
14797 | unsigned NumParams = Proto->getNumParams(); | ||||
14798 | |||||
14799 | // If too few arguments are available, we'll fill in the rest with defaults. | ||||
14800 | if (NumArgs < NumParams) | ||||
14801 | ConvertedArgs.reserve(NumParams); | ||||
14802 | else | ||||
14803 | ConvertedArgs.reserve(NumArgs); | ||||
14804 | |||||
14805 | VariadicCallType CallType = | ||||
14806 | Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; | ||||
14807 | SmallVector<Expr *, 8> AllArgs; | ||||
14808 | bool Invalid = GatherArgumentsForCall(Loc, Constructor, | ||||
14809 | Proto, 0, | ||||
14810 | llvm::makeArrayRef(Args, NumArgs), | ||||
14811 | AllArgs, | ||||
14812 | CallType, AllowExplicit, | ||||
14813 | IsListInitialization); | ||||
14814 | ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); | ||||
14815 | |||||
14816 | DiagnoseSentinelCalls(Constructor, Loc, AllArgs); | ||||
14817 | |||||
14818 | CheckConstructorCall(Constructor, | ||||
14819 | llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), | ||||
14820 | Proto, Loc); | ||||
14821 | |||||
14822 | return Invalid; | ||||
14823 | } | ||||
14824 | |||||
14825 | static inline bool | ||||
14826 | CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, | ||||
14827 | const FunctionDecl *FnDecl) { | ||||
14828 | const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); | ||||
14829 | if (isa<NamespaceDecl>(DC)) { | ||||
14830 | return SemaRef.Diag(FnDecl->getLocation(), | ||||
14831 | diag::err_operator_new_delete_declared_in_namespace) | ||||
14832 | << FnDecl->getDeclName(); | ||||
14833 | } | ||||
14834 | |||||
14835 | if (isa<TranslationUnitDecl>(DC) && | ||||
14836 | FnDecl->getStorageClass() == SC_Static) { | ||||
14837 | return SemaRef.Diag(FnDecl->getLocation(), | ||||
14838 | diag::err_operator_new_delete_declared_static) | ||||
14839 | << FnDecl->getDeclName(); | ||||
14840 | } | ||||
14841 | |||||
14842 | return false; | ||||
14843 | } | ||||
14844 | |||||
14845 | static QualType | ||||
14846 | RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { | ||||
14847 | QualType QTy = PtrTy->getPointeeType(); | ||||
14848 | QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); | ||||
14849 | return SemaRef.Context.getPointerType(QTy); | ||||
14850 | } | ||||
14851 | |||||
14852 | static inline bool | ||||
14853 | CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, | ||||
14854 | CanQualType ExpectedResultType, | ||||
14855 | CanQualType ExpectedFirstParamType, | ||||
14856 | unsigned DependentParamTypeDiag, | ||||
14857 | unsigned InvalidParamTypeDiag) { | ||||
14858 | QualType ResultType = | ||||
14859 | FnDecl->getType()->getAs<FunctionType>()->getReturnType(); | ||||
14860 | |||||
14861 | // Check that the result type is not dependent. | ||||
14862 | if (ResultType->isDependentType()) | ||||
14863 | return SemaRef.Diag(FnDecl->getLocation(), | ||||
14864 | diag::err_operator_new_delete_dependent_result_type) | ||||
14865 | << FnDecl->getDeclName() << ExpectedResultType; | ||||
14866 | |||||
14867 | // The operator is valid on any address space for OpenCL. | ||||
14868 | if (SemaRef.getLangOpts().OpenCLCPlusPlus) { | ||||
14869 | if (auto *PtrTy = ResultType->getAs<PointerType>()) { | ||||
14870 | ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); | ||||
14871 | } | ||||
14872 | } | ||||
14873 | |||||
14874 | // Check that the result type is what we expect. | ||||
14875 | if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) | ||||
14876 | return SemaRef.Diag(FnDecl->getLocation(), | ||||
14877 | diag::err_operator_new_delete_invalid_result_type) | ||||
14878 | << FnDecl->getDeclName() << ExpectedResultType; | ||||
14879 | |||||
14880 | // A function template must have at least 2 parameters. | ||||
14881 | if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) | ||||
14882 | return SemaRef.Diag(FnDecl->getLocation(), | ||||
14883 | diag::err_operator_new_delete_template_too_few_parameters) | ||||
14884 | << FnDecl->getDeclName(); | ||||
14885 | |||||
14886 | // The function decl must have at least 1 parameter. | ||||
14887 | if (FnDecl->getNumParams() == 0) | ||||
14888 | return SemaRef.Diag(FnDecl->getLocation(), | ||||
14889 | diag::err_operator_new_delete_too_few_parameters) | ||||
14890 | << FnDecl->getDeclName(); | ||||
14891 | |||||
14892 | // Check the first parameter type is not dependent. | ||||
14893 | QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); | ||||
14894 | if (FirstParamType->isDependentType()) | ||||
14895 | return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) | ||||
14896 | << FnDecl->getDeclName() << ExpectedFirstParamType; | ||||
14897 | |||||
14898 | // Check that the first parameter type is what we expect. | ||||
14899 | if (SemaRef.getLangOpts().OpenCLCPlusPlus) { | ||||
14900 | // The operator is valid on any address space for OpenCL. | ||||
14901 | if (auto *PtrTy = | ||||
14902 | FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { | ||||
14903 | FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); | ||||
14904 | } | ||||
14905 | } | ||||
14906 | if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != | ||||
14907 | ExpectedFirstParamType) | ||||
14908 | return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) | ||||
14909 | << FnDecl->getDeclName() << ExpectedFirstParamType; | ||||
14910 | |||||
14911 | return false; | ||||
14912 | } | ||||
14913 | |||||
14914 | static bool | ||||
14915 | CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { | ||||
14916 | // C++ [basic.stc.dynamic.allocation]p1: | ||||
14917 | // A program is ill-formed if an allocation function is declared in a | ||||
14918 | // namespace scope other than global scope or declared static in global | ||||
14919 | // scope. | ||||
14920 | if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) | ||||
14921 | return true; | ||||
14922 | |||||
14923 | CanQualType SizeTy = | ||||
14924 | SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); | ||||
14925 | |||||
14926 | // C++ [basic.stc.dynamic.allocation]p1: | ||||
14927 | // The return type shall be void*. The first parameter shall have type | ||||
14928 | // std::size_t. | ||||
14929 | if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, | ||||
14930 | SizeTy, | ||||
14931 | diag::err_operator_new_dependent_param_type, | ||||
14932 | diag::err_operator_new_param_type)) | ||||
14933 | return true; | ||||
14934 | |||||
14935 | // C++ [basic.stc.dynamic.allocation]p1: | ||||
14936 | // The first parameter shall not have an associated default argument. | ||||
14937 | if (FnDecl->getParamDecl(0)->hasDefaultArg()) | ||||
14938 | return SemaRef.Diag(FnDecl->getLocation(), | ||||
14939 | diag::err_operator_new_default_arg) | ||||
14940 | << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); | ||||
14941 | |||||
14942 | return false; | ||||
14943 | } | ||||
14944 | |||||
14945 | static bool | ||||
14946 | CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { | ||||
14947 | // C++ [basic.stc.dynamic.deallocation]p1: | ||||
14948 | // A program is ill-formed if deallocation functions are declared in a | ||||
14949 | // namespace scope other than global scope or declared static in global | ||||
14950 | // scope. | ||||
14951 | if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) | ||||
14952 | return true; | ||||
14953 | |||||
14954 | auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); | ||||
14955 | |||||
14956 | // C++ P0722: | ||||
14957 | // Within a class C, the first parameter of a destroying operator delete | ||||
14958 | // shall be of type C *. The first parameter of any other deallocation | ||||
14959 | // function shall be of type void *. | ||||
14960 | CanQualType ExpectedFirstParamType = | ||||
14961 | MD && MD->isDestroyingOperatorDelete() | ||||
14962 | ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( | ||||
14963 | SemaRef.Context.getRecordType(MD->getParent()))) | ||||
14964 | : SemaRef.Context.VoidPtrTy; | ||||
14965 | |||||
14966 | // C++ [basic.stc.dynamic.deallocation]p2: | ||||
14967 | // Each deallocation function shall return void | ||||
14968 | if (CheckOperatorNewDeleteTypes( | ||||
14969 | SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, | ||||
14970 | diag::err_operator_delete_dependent_param_type, | ||||
14971 | diag::err_operator_delete_param_type)) | ||||
14972 | return true; | ||||
14973 | |||||
14974 | // C++ P0722: | ||||
14975 | // A destroying operator delete shall be a usual deallocation function. | ||||
14976 | if (MD && !MD->getParent()->isDependentContext() && | ||||
14977 | MD->isDestroyingOperatorDelete() && | ||||
14978 | !SemaRef.isUsualDeallocationFunction(MD)) { | ||||
14979 | SemaRef.Diag(MD->getLocation(), | ||||
14980 | diag::err_destroying_operator_delete_not_usual); | ||||
14981 | return true; | ||||
14982 | } | ||||
14983 | |||||
14984 | return false; | ||||
14985 | } | ||||
14986 | |||||
14987 | /// CheckOverloadedOperatorDeclaration - Check whether the declaration | ||||
14988 | /// of this overloaded operator is well-formed. If so, returns false; | ||||
14989 | /// otherwise, emits appropriate diagnostics and returns true. | ||||
14990 | bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { | ||||
14991 | assert(FnDecl && FnDecl->isOverloadedOperator() &&((FnDecl && FnDecl->isOverloadedOperator() && "Expected an overloaded operator declaration") ? static_cast <void> (0) : __assert_fail ("FnDecl && FnDecl->isOverloadedOperator() && \"Expected an overloaded operator declaration\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14992, __PRETTY_FUNCTION__)) | ||||
14992 | "Expected an overloaded operator declaration")((FnDecl && FnDecl->isOverloadedOperator() && "Expected an overloaded operator declaration") ? static_cast <void> (0) : __assert_fail ("FnDecl && FnDecl->isOverloadedOperator() && \"Expected an overloaded operator declaration\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 14992, __PRETTY_FUNCTION__)); | ||||
14993 | |||||
14994 | OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); | ||||
14995 | |||||
14996 | // C++ [over.oper]p5: | ||||
14997 | // The allocation and deallocation functions, operator new, | ||||
14998 | // operator new[], operator delete and operator delete[], are | ||||
14999 | // described completely in 3.7.3. The attributes and restrictions | ||||
15000 | // found in the rest of this subclause do not apply to them unless | ||||
15001 | // explicitly stated in 3.7.3. | ||||
15002 | if (Op == OO_Delete || Op == OO_Array_Delete) | ||||
15003 | return CheckOperatorDeleteDeclaration(*this, FnDecl); | ||||
15004 | |||||
15005 | if (Op == OO_New || Op == OO_Array_New) | ||||
15006 | return CheckOperatorNewDeclaration(*this, FnDecl); | ||||
15007 | |||||
15008 | // C++ [over.oper]p6: | ||||
15009 | // An operator function shall either be a non-static member | ||||
15010 | // function or be a non-member function and have at least one | ||||
15011 | // parameter whose type is a class, a reference to a class, an | ||||
15012 | // enumeration, or a reference to an enumeration. | ||||
15013 | if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { | ||||
15014 | if (MethodDecl->isStatic()) | ||||
15015 | return Diag(FnDecl->getLocation(), | ||||
15016 | diag::err_operator_overload_static) << FnDecl->getDeclName(); | ||||
15017 | } else { | ||||
15018 | bool ClassOrEnumParam = false; | ||||
15019 | for (auto Param : FnDecl->parameters()) { | ||||
15020 | QualType ParamType = Param->getType().getNonReferenceType(); | ||||
15021 | if (ParamType->isDependentType() || ParamType->isRecordType() || | ||||
15022 | ParamType->isEnumeralType()) { | ||||
15023 | ClassOrEnumParam = true; | ||||
15024 | break; | ||||
15025 | } | ||||
15026 | } | ||||
15027 | |||||
15028 | if (!ClassOrEnumParam) | ||||
15029 | return Diag(FnDecl->getLocation(), | ||||
15030 | diag::err_operator_overload_needs_class_or_enum) | ||||
15031 | << FnDecl->getDeclName(); | ||||
15032 | } | ||||
15033 | |||||
15034 | // C++ [over.oper]p8: | ||||
15035 | // An operator function cannot have default arguments (8.3.6), | ||||
15036 | // except where explicitly stated below. | ||||
15037 | // | ||||
15038 | // Only the function-call operator allows default arguments | ||||
15039 | // (C++ [over.call]p1). | ||||
15040 | if (Op != OO_Call) { | ||||
15041 | for (auto Param : FnDecl->parameters()) { | ||||
15042 | if (Param->hasDefaultArg()) | ||||
15043 | return Diag(Param->getLocation(), | ||||
15044 | diag::err_operator_overload_default_arg) | ||||
15045 | << FnDecl->getDeclName() << Param->getDefaultArgRange(); | ||||
15046 | } | ||||
15047 | } | ||||
15048 | |||||
15049 | static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { | ||||
15050 | { false, false, false } | ||||
15051 | #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ | ||||
15052 | , { Unary, Binary, MemberOnly } | ||||
15053 | #include "clang/Basic/OperatorKinds.def" | ||||
15054 | }; | ||||
15055 | |||||
15056 | bool CanBeUnaryOperator = OperatorUses[Op][0]; | ||||
15057 | bool CanBeBinaryOperator = OperatorUses[Op][1]; | ||||
15058 | bool MustBeMemberOperator = OperatorUses[Op][2]; | ||||
15059 | |||||
15060 | // C++ [over.oper]p8: | ||||
15061 | // [...] Operator functions cannot have more or fewer parameters | ||||
15062 | // than the number required for the corresponding operator, as | ||||
15063 | // described in the rest of this subclause. | ||||
15064 | unsigned NumParams = FnDecl->getNumParams() | ||||
15065 | + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); | ||||
15066 | if (Op != OO_Call && | ||||
15067 | ((NumParams == 1 && !CanBeUnaryOperator) || | ||||
15068 | (NumParams == 2 && !CanBeBinaryOperator) || | ||||
15069 | (NumParams < 1) || (NumParams > 2))) { | ||||
15070 | // We have the wrong number of parameters. | ||||
15071 | unsigned ErrorKind; | ||||
15072 | if (CanBeUnaryOperator && CanBeBinaryOperator) { | ||||
15073 | ErrorKind = 2; // 2 -> unary or binary. | ||||
15074 | } else if (CanBeUnaryOperator) { | ||||
15075 | ErrorKind = 0; // 0 -> unary | ||||
15076 | } else { | ||||
15077 | assert(CanBeBinaryOperator &&((CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!" ) ? static_cast<void> (0) : __assert_fail ("CanBeBinaryOperator && \"All non-call overloaded operators are unary or binary!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 15078, __PRETTY_FUNCTION__)) | ||||
15078 | "All non-call overloaded operators are unary or binary!")((CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!" ) ? static_cast<void> (0) : __assert_fail ("CanBeBinaryOperator && \"All non-call overloaded operators are unary or binary!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 15078, __PRETTY_FUNCTION__)); | ||||
15079 | ErrorKind = 1; // 1 -> binary | ||||
15080 | } | ||||
15081 | |||||
15082 | return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) | ||||
15083 | << FnDecl->getDeclName() << NumParams << ErrorKind; | ||||
15084 | } | ||||
15085 | |||||
15086 | // Overloaded operators other than operator() cannot be variadic. | ||||
15087 | if (Op != OO_Call && | ||||
15088 | FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { | ||||
15089 | return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) | ||||
15090 | << FnDecl->getDeclName(); | ||||
15091 | } | ||||
15092 | |||||
15093 | // Some operators must be non-static member functions. | ||||
15094 | if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { | ||||
15095 | return Diag(FnDecl->getLocation(), | ||||
15096 | diag::err_operator_overload_must_be_member) | ||||
15097 | << FnDecl->getDeclName(); | ||||
15098 | } | ||||
15099 | |||||
15100 | // C++ [over.inc]p1: | ||||
15101 | // The user-defined function called operator++ implements the | ||||
15102 | // prefix and postfix ++ operator. If this function is a member | ||||
15103 | // function with no parameters, or a non-member function with one | ||||
15104 | // parameter of class or enumeration type, it defines the prefix | ||||
15105 | // increment operator ++ for objects of that type. If the function | ||||
15106 | // is a member function with one parameter (which shall be of type | ||||
15107 | // int) or a non-member function with two parameters (the second | ||||
15108 | // of which shall be of type int), it defines the postfix | ||||
15109 | // increment operator ++ for objects of that type. | ||||
15110 | if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { | ||||
15111 | ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); | ||||
15112 | QualType ParamType = LastParam->getType(); | ||||
15113 | |||||
15114 | if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && | ||||
15115 | !ParamType->isDependentType()) | ||||
15116 | return Diag(LastParam->getLocation(), | ||||
15117 | diag::err_operator_overload_post_incdec_must_be_int) | ||||
15118 | << LastParam->getType() << (Op == OO_MinusMinus); | ||||
15119 | } | ||||
15120 | |||||
15121 | return false; | ||||
15122 | } | ||||
15123 | |||||
15124 | static bool | ||||
15125 | checkLiteralOperatorTemplateParameterList(Sema &SemaRef, | ||||
15126 | FunctionTemplateDecl *TpDecl) { | ||||
15127 | TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); | ||||
15128 | |||||
15129 | // Must have one or two template parameters. | ||||
15130 | if (TemplateParams->size() == 1) { | ||||
15131 | NonTypeTemplateParmDecl *PmDecl = | ||||
15132 | dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); | ||||
15133 | |||||
15134 | // The template parameter must be a char parameter pack. | ||||
15135 | if (PmDecl && PmDecl->isTemplateParameterPack() && | ||||
15136 | SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) | ||||
15137 | return false; | ||||
15138 | |||||
15139 | } else if (TemplateParams->size() == 2) { | ||||
15140 | TemplateTypeParmDecl *PmType = | ||||
15141 | dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); | ||||
15142 | NonTypeTemplateParmDecl *PmArgs = | ||||
15143 | dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); | ||||
15144 | |||||
15145 | // The second template parameter must be a parameter pack with the | ||||
15146 | // first template parameter as its type. | ||||
15147 | if (PmType && PmArgs && !PmType->isTemplateParameterPack() && | ||||
15148 | PmArgs->isTemplateParameterPack()) { | ||||
15149 | const TemplateTypeParmType *TArgs = | ||||
15150 | PmArgs->getType()->getAs<TemplateTypeParmType>(); | ||||
15151 | if (TArgs && TArgs->getDepth() == PmType->getDepth() && | ||||
15152 | TArgs->getIndex() == PmType->getIndex()) { | ||||
15153 | if (!SemaRef.inTemplateInstantiation()) | ||||
15154 | SemaRef.Diag(TpDecl->getLocation(), | ||||
15155 | diag::ext_string_literal_operator_template); | ||||
15156 | return false; | ||||
15157 | } | ||||
15158 | } | ||||
15159 | } | ||||
15160 | |||||
15161 | SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), | ||||
15162 | diag::err_literal_operator_template) | ||||
15163 | << TpDecl->getTemplateParameters()->getSourceRange(); | ||||
15164 | return true; | ||||
15165 | } | ||||
15166 | |||||
15167 | /// CheckLiteralOperatorDeclaration - Check whether the declaration | ||||
15168 | /// of this literal operator function is well-formed. If so, returns | ||||
15169 | /// false; otherwise, emits appropriate diagnostics and returns true. | ||||
15170 | bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { | ||||
15171 | if (isa<CXXMethodDecl>(FnDecl)) { | ||||
15172 | Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) | ||||
15173 | << FnDecl->getDeclName(); | ||||
15174 | return true; | ||||
15175 | } | ||||
15176 | |||||
15177 | if (FnDecl->isExternC()) { | ||||
15178 | Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); | ||||
15179 | if (const LinkageSpecDecl *LSD = | ||||
15180 | FnDecl->getDeclContext()->getExternCContext()) | ||||
15181 | Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); | ||||
15182 | return true; | ||||
15183 | } | ||||
15184 | |||||
15185 | // This might be the definition of a literal operator template. | ||||
15186 | FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); | ||||
15187 | |||||
15188 | // This might be a specialization of a literal operator template. | ||||
15189 | if (!TpDecl) | ||||
15190 | TpDecl = FnDecl->getPrimaryTemplate(); | ||||
15191 | |||||
15192 | // template <char...> type operator "" name() and | ||||
15193 | // template <class T, T...> type operator "" name() are the only valid | ||||
15194 | // template signatures, and the only valid signatures with no parameters. | ||||
15195 | if (TpDecl) { | ||||
15196 | if (FnDecl->param_size() != 0) { | ||||
15197 | Diag(FnDecl->getLocation(), | ||||
15198 | diag::err_literal_operator_template_with_params); | ||||
15199 | return true; | ||||
15200 | } | ||||
15201 | |||||
15202 | if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) | ||||
15203 | return true; | ||||
15204 | |||||
15205 | } else if (FnDecl->param_size() == 1) { | ||||
15206 | const ParmVarDecl *Param = FnDecl->getParamDecl(0); | ||||
15207 | |||||
15208 | QualType ParamType = Param->getType().getUnqualifiedType(); | ||||
15209 | |||||
15210 | // Only unsigned long long int, long double, any character type, and const | ||||
15211 | // char * are allowed as the only parameters. | ||||
15212 | if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || | ||||
15213 | ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || | ||||
15214 | Context.hasSameType(ParamType, Context.CharTy) || | ||||
15215 | Context.hasSameType(ParamType, Context.WideCharTy) || | ||||
15216 | Context.hasSameType(ParamType, Context.Char8Ty) || | ||||
15217 | Context.hasSameType(ParamType, Context.Char16Ty) || | ||||
15218 | Context.hasSameType(ParamType, Context.Char32Ty)) { | ||||
15219 | } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { | ||||
15220 | QualType InnerType = Ptr->getPointeeType(); | ||||
15221 | |||||
15222 | // Pointer parameter must be a const char *. | ||||
15223 | if (!(Context.hasSameType(InnerType.getUnqualifiedType(), | ||||
15224 | Context.CharTy) && | ||||
15225 | InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { | ||||
15226 | Diag(Param->getSourceRange().getBegin(), | ||||
15227 | diag::err_literal_operator_param) | ||||
15228 | << ParamType << "'const char *'" << Param->getSourceRange(); | ||||
15229 | return true; | ||||
15230 | } | ||||
15231 | |||||
15232 | } else if (ParamType->isRealFloatingType()) { | ||||
15233 | Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) | ||||
15234 | << ParamType << Context.LongDoubleTy << Param->getSourceRange(); | ||||
15235 | return true; | ||||
15236 | |||||
15237 | } else if (ParamType->isIntegerType()) { | ||||
15238 | Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) | ||||
15239 | << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); | ||||
15240 | return true; | ||||
15241 | |||||
15242 | } else { | ||||
15243 | Diag(Param->getSourceRange().getBegin(), | ||||
15244 | diag::err_literal_operator_invalid_param) | ||||
15245 | << ParamType << Param->getSourceRange(); | ||||
15246 | return true; | ||||
15247 | } | ||||
15248 | |||||
15249 | } else if (FnDecl->param_size() == 2) { | ||||
15250 | FunctionDecl::param_iterator Param = FnDecl->param_begin(); | ||||
15251 | |||||
15252 | // First, verify that the first parameter is correct. | ||||
15253 | |||||
15254 | QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); | ||||
15255 | |||||
15256 | // Two parameter function must have a pointer to const as a | ||||
15257 | // first parameter; let's strip those qualifiers. | ||||
15258 | const PointerType *PT = FirstParamType->getAs<PointerType>(); | ||||
15259 | |||||
15260 | if (!PT) { | ||||
15261 | Diag((*Param)->getSourceRange().getBegin(), | ||||
15262 | diag::err_literal_operator_param) | ||||
15263 | << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); | ||||
15264 | return true; | ||||
15265 | } | ||||
15266 | |||||
15267 | QualType PointeeType = PT->getPointeeType(); | ||||
15268 | // First parameter must be const | ||||
15269 | if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { | ||||
15270 | Diag((*Param)->getSourceRange().getBegin(), | ||||
15271 | diag::err_literal_operator_param) | ||||
15272 | << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); | ||||
15273 | return true; | ||||
15274 | } | ||||
15275 | |||||
15276 | QualType InnerType = PointeeType.getUnqualifiedType(); | ||||
15277 | // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and | ||||
15278 | // const char32_t* are allowed as the first parameter to a two-parameter | ||||
15279 | // function | ||||
15280 | if (!(Context.hasSameType(InnerType, Context.CharTy) || | ||||
15281 | Context.hasSameType(InnerType, Context.WideCharTy) || | ||||
15282 | Context.hasSameType(InnerType, Context.Char8Ty) || | ||||
15283 | Context.hasSameType(InnerType, Context.Char16Ty) || | ||||
15284 | Context.hasSameType(InnerType, Context.Char32Ty))) { | ||||
15285 | Diag((*Param)->getSourceRange().getBegin(), | ||||
15286 | diag::err_literal_operator_param) | ||||
15287 | << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); | ||||
15288 | return true; | ||||
15289 | } | ||||
15290 | |||||
15291 | // Move on to the second and final parameter. | ||||
15292 | ++Param; | ||||
15293 | |||||
15294 | // The second parameter must be a std::size_t. | ||||
15295 | QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); | ||||
15296 | if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { | ||||
15297 | Diag((*Param)->getSourceRange().getBegin(), | ||||
15298 | diag::err_literal_operator_param) | ||||
15299 | << SecondParamType << Context.getSizeType() | ||||
15300 | << (*Param)->getSourceRange(); | ||||
15301 | return true; | ||||
15302 | } | ||||
15303 | } else { | ||||
15304 | Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); | ||||
15305 | return true; | ||||
15306 | } | ||||
15307 | |||||
15308 | // Parameters are good. | ||||
15309 | |||||
15310 | // A parameter-declaration-clause containing a default argument is not | ||||
15311 | // equivalent to any of the permitted forms. | ||||
15312 | for (auto Param : FnDecl->parameters()) { | ||||
15313 | if (Param->hasDefaultArg()) { | ||||
15314 | Diag(Param->getDefaultArgRange().getBegin(), | ||||
15315 | diag::err_literal_operator_default_argument) | ||||
15316 | << Param->getDefaultArgRange(); | ||||
15317 | break; | ||||
15318 | } | ||||
15319 | } | ||||
15320 | |||||
15321 | StringRef LiteralName | ||||
15322 | = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); | ||||
15323 | if (LiteralName[0] != '_' && | ||||
15324 | !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { | ||||
15325 | // C++11 [usrlit.suffix]p1: | ||||
15326 | // Literal suffix identifiers that do not start with an underscore | ||||
15327 | // are reserved for future standardization. | ||||
15328 | Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) | ||||
15329 | << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); | ||||
15330 | } | ||||
15331 | |||||
15332 | return false; | ||||
15333 | } | ||||
15334 | |||||
15335 | /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ | ||||
15336 | /// linkage specification, including the language and (if present) | ||||
15337 | /// the '{'. ExternLoc is the location of the 'extern', Lang is the | ||||
15338 | /// language string literal. LBraceLoc, if valid, provides the location of | ||||
15339 | /// the '{' brace. Otherwise, this linkage specification does not | ||||
15340 | /// have any braces. | ||||
15341 | Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, | ||||
15342 | Expr *LangStr, | ||||
15343 | SourceLocation LBraceLoc) { | ||||
15344 | StringLiteral *Lit = cast<StringLiteral>(LangStr); | ||||
15345 | if (!Lit->isAscii()) { | ||||
15346 | Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) | ||||
15347 | << LangStr->getSourceRange(); | ||||
15348 | return nullptr; | ||||
15349 | } | ||||
15350 | |||||
15351 | StringRef Lang = Lit->getString(); | ||||
15352 | LinkageSpecDecl::LanguageIDs Language; | ||||
15353 | if (Lang == "C") | ||||
15354 | Language = LinkageSpecDecl::lang_c; | ||||
15355 | else if (Lang == "C++") | ||||
15356 | Language = LinkageSpecDecl::lang_cxx; | ||||
15357 | else { | ||||
15358 | Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) | ||||
15359 | << LangStr->getSourceRange(); | ||||
15360 | return nullptr; | ||||
15361 | } | ||||
15362 | |||||
15363 | // FIXME: Add all the various semantics of linkage specifications | ||||
15364 | |||||
15365 | LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, | ||||
15366 | LangStr->getExprLoc(), Language, | ||||
15367 | LBraceLoc.isValid()); | ||||
15368 | CurContext->addDecl(D); | ||||
15369 | PushDeclContext(S, D); | ||||
15370 | return D; | ||||
15371 | } | ||||
15372 | |||||
15373 | /// ActOnFinishLinkageSpecification - Complete the definition of | ||||
15374 | /// the C++ linkage specification LinkageSpec. If RBraceLoc is | ||||
15375 | /// valid, it's the position of the closing '}' brace in a linkage | ||||
15376 | /// specification that uses braces. | ||||
15377 | Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, | ||||
15378 | Decl *LinkageSpec, | ||||
15379 | SourceLocation RBraceLoc) { | ||||
15380 | if (RBraceLoc.isValid()) { | ||||
15381 | LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); | ||||
15382 | LSDecl->setRBraceLoc(RBraceLoc); | ||||
15383 | } | ||||
15384 | PopDeclContext(); | ||||
15385 | return LinkageSpec; | ||||
15386 | } | ||||
15387 | |||||
15388 | Decl *Sema::ActOnEmptyDeclaration(Scope *S, | ||||
15389 | const ParsedAttributesView &AttrList, | ||||
15390 | SourceLocation SemiLoc) { | ||||
15391 | Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); | ||||
15392 | // Attribute declarations appertain to empty declaration so we handle | ||||
15393 | // them here. | ||||
15394 | ProcessDeclAttributeList(S, ED, AttrList); | ||||
15395 | |||||
15396 | CurContext->addDecl(ED); | ||||
15397 | return ED; | ||||
15398 | } | ||||
15399 | |||||
15400 | /// Perform semantic analysis for the variable declaration that | ||||
15401 | /// occurs within a C++ catch clause, returning the newly-created | ||||
15402 | /// variable. | ||||
15403 | VarDecl *Sema::BuildExceptionDeclaration(Scope *S, | ||||
15404 | TypeSourceInfo *TInfo, | ||||
15405 | SourceLocation StartLoc, | ||||
15406 | SourceLocation Loc, | ||||
15407 | IdentifierInfo *Name) { | ||||
15408 | bool Invalid = false; | ||||
15409 | QualType ExDeclType = TInfo->getType(); | ||||
15410 | |||||
15411 | // Arrays and functions decay. | ||||
15412 | if (ExDeclType->isArrayType()) | ||||
15413 | ExDeclType = Context.getArrayDecayedType(ExDeclType); | ||||
15414 | else if (ExDeclType->isFunctionType()) | ||||
15415 | ExDeclType = Context.getPointerType(ExDeclType); | ||||
15416 | |||||
15417 | // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. | ||||
15418 | // The exception-declaration shall not denote a pointer or reference to an | ||||
15419 | // incomplete type, other than [cv] void*. | ||||
15420 | // N2844 forbids rvalue references. | ||||
15421 | if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { | ||||
15422 | Diag(Loc, diag::err_catch_rvalue_ref); | ||||
15423 | Invalid = true; | ||||
15424 | } | ||||
15425 | |||||
15426 | if (ExDeclType->isVariablyModifiedType()) { | ||||
15427 | Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; | ||||
15428 | Invalid = true; | ||||
15429 | } | ||||
15430 | |||||
15431 | QualType BaseType = ExDeclType; | ||||
15432 | int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference | ||||
15433 | unsigned DK = diag::err_catch_incomplete; | ||||
15434 | if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { | ||||
15435 | BaseType = Ptr->getPointeeType(); | ||||
15436 | Mode = 1; | ||||
15437 | DK = diag::err_catch_incomplete_ptr; | ||||
15438 | } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { | ||||
15439 | // For the purpose of error recovery, we treat rvalue refs like lvalue refs. | ||||
15440 | BaseType = Ref->getPointeeType(); | ||||
15441 | Mode = 2; | ||||
15442 | DK = diag::err_catch_incomplete_ref; | ||||
15443 | } | ||||
15444 | if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && | ||||
15445 | !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) | ||||
15446 | Invalid = true; | ||||
15447 | |||||
15448 | if (!Invalid && !ExDeclType->isDependentType() && | ||||
15449 | RequireNonAbstractType(Loc, ExDeclType, | ||||
15450 | diag::err_abstract_type_in_decl, | ||||
15451 | AbstractVariableType)) | ||||
15452 | Invalid = true; | ||||
15453 | |||||
15454 | // Only the non-fragile NeXT runtime currently supports C++ catches | ||||
15455 | // of ObjC types, and no runtime supports catching ObjC types by value. | ||||
15456 | if (!Invalid && getLangOpts().ObjC) { | ||||
15457 | QualType T = ExDeclType; | ||||
15458 | if (const ReferenceType *RT = T->getAs<ReferenceType>()) | ||||
15459 | T = RT->getPointeeType(); | ||||
15460 | |||||
15461 | if (T->isObjCObjectType()) { | ||||
15462 | Diag(Loc, diag::err_objc_object_catch); | ||||
15463 | Invalid = true; | ||||
15464 | } else if (T->isObjCObjectPointerType()) { | ||||
15465 | // FIXME: should this be a test for macosx-fragile specifically? | ||||
15466 | if (getLangOpts().ObjCRuntime.isFragile()) | ||||
15467 | Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); | ||||
15468 | } | ||||
15469 | } | ||||
15470 | |||||
15471 | VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, | ||||
15472 | ExDeclType, TInfo, SC_None); | ||||
15473 | ExDecl->setExceptionVariable(true); | ||||
15474 | |||||
15475 | // In ARC, infer 'retaining' for variables of retainable type. | ||||
15476 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) | ||||
15477 | Invalid = true; | ||||
15478 | |||||
15479 | if (!Invalid && !ExDeclType->isDependentType()) { | ||||
15480 | if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { | ||||
15481 | // Insulate this from anything else we might currently be parsing. | ||||
15482 | EnterExpressionEvaluationContext scope( | ||||
15483 | *this, ExpressionEvaluationContext::PotentiallyEvaluated); | ||||
15484 | |||||
15485 | // C++ [except.handle]p16: | ||||
15486 | // The object declared in an exception-declaration or, if the | ||||
15487 | // exception-declaration does not specify a name, a temporary (12.2) is | ||||
15488 | // copy-initialized (8.5) from the exception object. [...] | ||||
15489 | // The object is destroyed when the handler exits, after the destruction | ||||
15490 | // of any automatic objects initialized within the handler. | ||||
15491 | // | ||||
15492 | // We just pretend to initialize the object with itself, then make sure | ||||
15493 | // it can be destroyed later. | ||||
15494 | QualType initType = Context.getExceptionObjectType(ExDeclType); | ||||
15495 | |||||
15496 | InitializedEntity entity = | ||||
15497 | InitializedEntity::InitializeVariable(ExDecl); | ||||
15498 | InitializationKind initKind = | ||||
15499 | InitializationKind::CreateCopy(Loc, SourceLocation()); | ||||
15500 | |||||
15501 | Expr *opaqueValue = | ||||
15502 | new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); | ||||
15503 | InitializationSequence sequence(*this, entity, initKind, opaqueValue); | ||||
15504 | ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); | ||||
15505 | if (result.isInvalid()) | ||||
15506 | Invalid = true; | ||||
15507 | else { | ||||
15508 | // If the constructor used was non-trivial, set this as the | ||||
15509 | // "initializer". | ||||
15510 | CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); | ||||
15511 | if (!construct->getConstructor()->isTrivial()) { | ||||
15512 | Expr *init = MaybeCreateExprWithCleanups(construct); | ||||
15513 | ExDecl->setInit(init); | ||||
15514 | } | ||||
15515 | |||||
15516 | // And make sure it's destructable. | ||||
15517 | FinalizeVarWithDestructor(ExDecl, recordType); | ||||
15518 | } | ||||
15519 | } | ||||
15520 | } | ||||
15521 | |||||
15522 | if (Invalid) | ||||
15523 | ExDecl->setInvalidDecl(); | ||||
15524 | |||||
15525 | return ExDecl; | ||||
15526 | } | ||||
15527 | |||||
15528 | /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch | ||||
15529 | /// handler. | ||||
15530 | Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { | ||||
15531 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||
15532 | bool Invalid = D.isInvalidType(); | ||||
15533 | |||||
15534 | // Check for unexpanded parameter packs. | ||||
15535 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | ||||
15536 | UPPC_ExceptionType)) { | ||||
15537 | TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, | ||||
15538 | D.getIdentifierLoc()); | ||||
15539 | Invalid = true; | ||||
15540 | } | ||||
15541 | |||||
15542 | IdentifierInfo *II = D.getIdentifier(); | ||||
15543 | if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), | ||||
15544 | LookupOrdinaryName, | ||||
15545 | ForVisibleRedeclaration)) { | ||||
15546 | // The scope should be freshly made just for us. There is just no way | ||||
15547 | // it contains any previous declaration, except for function parameters in | ||||
15548 | // a function-try-block's catch statement. | ||||
15549 | assert(!S->isDeclScope(PrevDecl))((!S->isDeclScope(PrevDecl)) ? static_cast<void> (0) : __assert_fail ("!S->isDeclScope(PrevDecl)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 15549, __PRETTY_FUNCTION__)); | ||||
15550 | if (isDeclInScope(PrevDecl, CurContext, S)) { | ||||
15551 | Diag(D.getIdentifierLoc(), diag::err_redefinition) | ||||
15552 | << D.getIdentifier(); | ||||
15553 | Diag(PrevDecl->getLocation(), diag::note_previous_definition); | ||||
15554 | Invalid = true; | ||||
15555 | } else if (PrevDecl->isTemplateParameter()) | ||||
15556 | // Maybe we will complain about the shadowed template parameter. | ||||
15557 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | ||||
15558 | } | ||||
15559 | |||||
15560 | if (D.getCXXScopeSpec().isSet() && !Invalid) { | ||||
15561 | Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) | ||||
15562 | << D.getCXXScopeSpec().getRange(); | ||||
15563 | Invalid = true; | ||||
15564 | } | ||||
15565 | |||||
15566 | VarDecl *ExDecl = BuildExceptionDeclaration( | ||||
15567 | S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); | ||||
15568 | if (Invalid) | ||||
15569 | ExDecl->setInvalidDecl(); | ||||
15570 | |||||
15571 | // Add the exception declaration into this scope. | ||||
15572 | if (II) | ||||
15573 | PushOnScopeChains(ExDecl, S); | ||||
15574 | else | ||||
15575 | CurContext->addDecl(ExDecl); | ||||
15576 | |||||
15577 | ProcessDeclAttributes(S, ExDecl, D); | ||||
15578 | return ExDecl; | ||||
15579 | } | ||||
15580 | |||||
15581 | Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, | ||||
15582 | Expr *AssertExpr, | ||||
15583 | Expr *AssertMessageExpr, | ||||
15584 | SourceLocation RParenLoc) { | ||||
15585 | StringLiteral *AssertMessage = | ||||
15586 | AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; | ||||
15587 | |||||
15588 | if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) | ||||
15589 | return nullptr; | ||||
15590 | |||||
15591 | return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, | ||||
15592 | AssertMessage, RParenLoc, false); | ||||
15593 | } | ||||
15594 | |||||
15595 | Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, | ||||
15596 | Expr *AssertExpr, | ||||
15597 | StringLiteral *AssertMessage, | ||||
15598 | SourceLocation RParenLoc, | ||||
15599 | bool Failed) { | ||||
15600 | assert(AssertExpr != nullptr && "Expected non-null condition")((AssertExpr != nullptr && "Expected non-null condition" ) ? static_cast<void> (0) : __assert_fail ("AssertExpr != nullptr && \"Expected non-null condition\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 15600, __PRETTY_FUNCTION__)); | ||||
15601 | if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && | ||||
15602 | !Failed) { | ||||
15603 | // In a static_assert-declaration, the constant-expression shall be a | ||||
15604 | // constant expression that can be contextually converted to bool. | ||||
15605 | ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); | ||||
15606 | if (Converted.isInvalid()) | ||||
15607 | Failed = true; | ||||
15608 | |||||
15609 | ExprResult FullAssertExpr = | ||||
15610 | ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, | ||||
15611 | /*DiscardedValue*/ false, | ||||
15612 | /*IsConstexpr*/ true); | ||||
15613 | if (FullAssertExpr.isInvalid()) | ||||
15614 | Failed = true; | ||||
15615 | else | ||||
15616 | AssertExpr = FullAssertExpr.get(); | ||||
15617 | |||||
15618 | llvm::APSInt Cond; | ||||
15619 | if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond, | ||||
15620 | diag::err_static_assert_expression_is_not_constant, | ||||
15621 | /*AllowFold=*/false).isInvalid()) | ||||
15622 | Failed = true; | ||||
15623 | |||||
15624 | if (!Failed && !Cond) { | ||||
15625 | SmallString<256> MsgBuffer; | ||||
15626 | llvm::raw_svector_ostream Msg(MsgBuffer); | ||||
15627 | if (AssertMessage) | ||||
15628 | AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); | ||||
15629 | |||||
15630 | Expr *InnerCond = nullptr; | ||||
15631 | std::string InnerCondDescription; | ||||
15632 | std::tie(InnerCond, InnerCondDescription) = | ||||
15633 | findFailedBooleanCondition(Converted.get()); | ||||
15634 | if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { | ||||
15635 | // Drill down into concept specialization expressions to see why they | ||||
15636 | // weren't satisfied. | ||||
15637 | Diag(StaticAssertLoc, diag::err_static_assert_failed) | ||||
15638 | << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); | ||||
15639 | ConstraintSatisfaction Satisfaction; | ||||
15640 | if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) | ||||
15641 | DiagnoseUnsatisfiedConstraint(Satisfaction); | ||||
15642 | } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) | ||||
15643 | && !isa<IntegerLiteral>(InnerCond)) { | ||||
15644 | Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) | ||||
15645 | << InnerCondDescription << !AssertMessage | ||||
15646 | << Msg.str() << InnerCond->getSourceRange(); | ||||
15647 | } else { | ||||
15648 | Diag(StaticAssertLoc, diag::err_static_assert_failed) | ||||
15649 | << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); | ||||
15650 | } | ||||
15651 | Failed = true; | ||||
15652 | } | ||||
15653 | } else { | ||||
15654 | ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, | ||||
15655 | /*DiscardedValue*/false, | ||||
15656 | /*IsConstexpr*/true); | ||||
15657 | if (FullAssertExpr.isInvalid()) | ||||
15658 | Failed = true; | ||||
15659 | else | ||||
15660 | AssertExpr = FullAssertExpr.get(); | ||||
15661 | } | ||||
15662 | |||||
15663 | Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, | ||||
15664 | AssertExpr, AssertMessage, RParenLoc, | ||||
15665 | Failed); | ||||
15666 | |||||
15667 | CurContext->addDecl(Decl); | ||||
15668 | return Decl; | ||||
15669 | } | ||||
15670 | |||||
15671 | /// Perform semantic analysis of the given friend type declaration. | ||||
15672 | /// | ||||
15673 | /// \returns A friend declaration that. | ||||
15674 | FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, | ||||
15675 | SourceLocation FriendLoc, | ||||
15676 | TypeSourceInfo *TSInfo) { | ||||
15677 | assert(TSInfo && "NULL TypeSourceInfo for friend type declaration")((TSInfo && "NULL TypeSourceInfo for friend type declaration" ) ? static_cast<void> (0) : __assert_fail ("TSInfo && \"NULL TypeSourceInfo for friend type declaration\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 15677, __PRETTY_FUNCTION__)); | ||||
15678 | |||||
15679 | QualType T = TSInfo->getType(); | ||||
15680 | SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); | ||||
15681 | |||||
15682 | // C++03 [class.friend]p2: | ||||
15683 | // An elaborated-type-specifier shall be used in a friend declaration | ||||
15684 | // for a class.* | ||||
15685 | // | ||||
15686 | // * The class-key of the elaborated-type-specifier is required. | ||||
15687 | if (!CodeSynthesisContexts.empty()) { | ||||
15688 | // Do not complain about the form of friend template types during any kind | ||||
15689 | // of code synthesis. For template instantiation, we will have complained | ||||
15690 | // when the template was defined. | ||||
15691 | } else { | ||||
15692 | if (!T->isElaboratedTypeSpecifier()) { | ||||
15693 | // If we evaluated the type to a record type, suggest putting | ||||
15694 | // a tag in front. | ||||
15695 | if (const RecordType *RT = T->getAs<RecordType>()) { | ||||
15696 | RecordDecl *RD = RT->getDecl(); | ||||
15697 | |||||
15698 | SmallString<16> InsertionText(" "); | ||||
15699 | InsertionText += RD->getKindName(); | ||||
15700 | |||||
15701 | Diag(TypeRange.getBegin(), | ||||
15702 | getLangOpts().CPlusPlus11 ? | ||||
15703 | diag::warn_cxx98_compat_unelaborated_friend_type : | ||||
15704 | diag::ext_unelaborated_friend_type) | ||||
15705 | << (unsigned) RD->getTagKind() | ||||
15706 | << T | ||||
15707 | << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), | ||||
15708 | InsertionText); | ||||
15709 | } else { | ||||
15710 | Diag(FriendLoc, | ||||
15711 | getLangOpts().CPlusPlus11 ? | ||||
15712 | diag::warn_cxx98_compat_nonclass_type_friend : | ||||
15713 | diag::ext_nonclass_type_friend) | ||||
15714 | << T | ||||
15715 | << TypeRange; | ||||
15716 | } | ||||
15717 | } else if (T->getAs<EnumType>()) { | ||||
15718 | Diag(FriendLoc, | ||||
15719 | getLangOpts().CPlusPlus11 ? | ||||
15720 | diag::warn_cxx98_compat_enum_friend : | ||||
15721 | diag::ext_enum_friend) | ||||
15722 | << T | ||||
15723 | << TypeRange; | ||||
15724 | } | ||||
15725 | |||||
15726 | // C++11 [class.friend]p3: | ||||
15727 | // A friend declaration that does not declare a function shall have one | ||||
15728 | // of the following forms: | ||||
15729 | // friend elaborated-type-specifier ; | ||||
15730 | // friend simple-type-specifier ; | ||||
15731 | // friend typename-specifier ; | ||||
15732 | if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) | ||||
15733 | Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; | ||||
15734 | } | ||||
15735 | |||||
15736 | // If the type specifier in a friend declaration designates a (possibly | ||||
15737 | // cv-qualified) class type, that class is declared as a friend; otherwise, | ||||
15738 | // the friend declaration is ignored. | ||||
15739 | return FriendDecl::Create(Context, CurContext, | ||||
15740 | TSInfo->getTypeLoc().getBeginLoc(), TSInfo, | ||||
15741 | FriendLoc); | ||||
15742 | } | ||||
15743 | |||||
15744 | /// Handle a friend tag declaration where the scope specifier was | ||||
15745 | /// templated. | ||||
15746 | Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, | ||||
15747 | unsigned TagSpec, SourceLocation TagLoc, | ||||
15748 | CXXScopeSpec &SS, IdentifierInfo *Name, | ||||
15749 | SourceLocation NameLoc, | ||||
15750 | const ParsedAttributesView &Attr, | ||||
15751 | MultiTemplateParamsArg TempParamLists) { | ||||
15752 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); | ||||
15753 | |||||
15754 | bool IsMemberSpecialization = false; | ||||
15755 | bool Invalid = false; | ||||
15756 | |||||
15757 | if (TemplateParameterList *TemplateParams = | ||||
15758 | MatchTemplateParametersToScopeSpecifier( | ||||
15759 | TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, | ||||
15760 | IsMemberSpecialization, Invalid)) { | ||||
15761 | if (TemplateParams->size() > 0) { | ||||
15762 | // This is a declaration of a class template. | ||||
15763 | if (Invalid) | ||||
15764 | return nullptr; | ||||
15765 | |||||
15766 | return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, | ||||
15767 | NameLoc, Attr, TemplateParams, AS_public, | ||||
15768 | /*ModulePrivateLoc=*/SourceLocation(), | ||||
15769 | FriendLoc, TempParamLists.size() - 1, | ||||
15770 | TempParamLists.data()).get(); | ||||
15771 | } else { | ||||
15772 | // The "template<>" header is extraneous. | ||||
15773 | Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) | ||||
15774 | << TypeWithKeyword::getTagTypeKindName(Kind) << Name; | ||||
15775 | IsMemberSpecialization = true; | ||||
15776 | } | ||||
15777 | } | ||||
15778 | |||||
15779 | if (Invalid) return nullptr; | ||||
15780 | |||||
15781 | bool isAllExplicitSpecializations = true; | ||||
15782 | for (unsigned I = TempParamLists.size(); I-- > 0; ) { | ||||
15783 | if (TempParamLists[I]->size()) { | ||||
15784 | isAllExplicitSpecializations = false; | ||||
15785 | break; | ||||
15786 | } | ||||
15787 | } | ||||
15788 | |||||
15789 | // FIXME: don't ignore attributes. | ||||
15790 | |||||
15791 | // If it's explicit specializations all the way down, just forget | ||||
15792 | // about the template header and build an appropriate non-templated | ||||
15793 | // friend. TODO: for source fidelity, remember the headers. | ||||
15794 | if (isAllExplicitSpecializations) { | ||||
15795 | if (SS.isEmpty()) { | ||||
15796 | bool Owned = false; | ||||
15797 | bool IsDependent = false; | ||||
15798 | return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, | ||||
15799 | Attr, AS_public, | ||||
15800 | /*ModulePrivateLoc=*/SourceLocation(), | ||||
15801 | MultiTemplateParamsArg(), Owned, IsDependent, | ||||
15802 | /*ScopedEnumKWLoc=*/SourceLocation(), | ||||
15803 | /*ScopedEnumUsesClassTag=*/false, | ||||
15804 | /*UnderlyingType=*/TypeResult(), | ||||
15805 | /*IsTypeSpecifier=*/false, | ||||
15806 | /*IsTemplateParamOrArg=*/false); | ||||
15807 | } | ||||
15808 | |||||
15809 | NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); | ||||
15810 | ElaboratedTypeKeyword Keyword | ||||
15811 | = TypeWithKeyword::getKeywordForTagTypeKind(Kind); | ||||
15812 | QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, | ||||
15813 | *Name, NameLoc); | ||||
15814 | if (T.isNull()) | ||||
15815 | return nullptr; | ||||
15816 | |||||
15817 | TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); | ||||
15818 | if (isa<DependentNameType>(T)) { | ||||
15819 | DependentNameTypeLoc TL = | ||||
15820 | TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); | ||||
15821 | TL.setElaboratedKeywordLoc(TagLoc); | ||||
15822 | TL.setQualifierLoc(QualifierLoc); | ||||
15823 | TL.setNameLoc(NameLoc); | ||||
15824 | } else { | ||||
15825 | ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); | ||||
15826 | TL.setElaboratedKeywordLoc(TagLoc); | ||||
15827 | TL.setQualifierLoc(QualifierLoc); | ||||
15828 | TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); | ||||
15829 | } | ||||
15830 | |||||
15831 | FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, | ||||
15832 | TSI, FriendLoc, TempParamLists); | ||||
15833 | Friend->setAccess(AS_public); | ||||
15834 | CurContext->addDecl(Friend); | ||||
15835 | return Friend; | ||||
15836 | } | ||||
15837 | |||||
15838 | assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?")((SS.isNotEmpty() && "valid templated tag with no SS and no direct?" ) ? static_cast<void> (0) : __assert_fail ("SS.isNotEmpty() && \"valid templated tag with no SS and no direct?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 15838, __PRETTY_FUNCTION__)); | ||||
15839 | |||||
15840 | |||||
15841 | |||||
15842 | // Handle the case of a templated-scope friend class. e.g. | ||||
15843 | // template <class T> class A<T>::B; | ||||
15844 | // FIXME: we don't support these right now. | ||||
15845 | Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) | ||||
15846 | << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); | ||||
15847 | ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); | ||||
15848 | QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); | ||||
15849 | TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); | ||||
15850 | DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); | ||||
15851 | TL.setElaboratedKeywordLoc(TagLoc); | ||||
15852 | TL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||
15853 | TL.setNameLoc(NameLoc); | ||||
15854 | |||||
15855 | FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, | ||||
15856 | TSI, FriendLoc, TempParamLists); | ||||
15857 | Friend->setAccess(AS_public); | ||||
15858 | Friend->setUnsupportedFriend(true); | ||||
15859 | CurContext->addDecl(Friend); | ||||
15860 | return Friend; | ||||
15861 | } | ||||
15862 | |||||
15863 | /// Handle a friend type declaration. This works in tandem with | ||||
15864 | /// ActOnTag. | ||||
15865 | /// | ||||
15866 | /// Notes on friend class templates: | ||||
15867 | /// | ||||
15868 | /// We generally treat friend class declarations as if they were | ||||
15869 | /// declaring a class. So, for example, the elaborated type specifier | ||||
15870 | /// in a friend declaration is required to obey the restrictions of a | ||||
15871 | /// class-head (i.e. no typedefs in the scope chain), template | ||||
15872 | /// parameters are required to match up with simple template-ids, &c. | ||||
15873 | /// However, unlike when declaring a template specialization, it's | ||||
15874 | /// okay to refer to a template specialization without an empty | ||||
15875 | /// template parameter declaration, e.g. | ||||
15876 | /// friend class A<T>::B<unsigned>; | ||||
15877 | /// We permit this as a special case; if there are any template | ||||
15878 | /// parameters present at all, require proper matching, i.e. | ||||
15879 | /// template <> template \<class T> friend class A<int>::B; | ||||
15880 | Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, | ||||
15881 | MultiTemplateParamsArg TempParams) { | ||||
15882 | SourceLocation Loc = DS.getBeginLoc(); | ||||
15883 | |||||
15884 | assert(DS.isFriendSpecified())((DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail ("DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 15884, __PRETTY_FUNCTION__)); | ||||
15885 | assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) ? static_cast <void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_unspecified" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 15885, __PRETTY_FUNCTION__)); | ||||
15886 | |||||
15887 | // C++ [class.friend]p3: | ||||
15888 | // A friend declaration that does not declare a function shall have one of | ||||
15889 | // the following forms: | ||||
15890 | // friend elaborated-type-specifier ; | ||||
15891 | // friend simple-type-specifier ; | ||||
15892 | // friend typename-specifier ; | ||||
15893 | // | ||||
15894 | // Any declaration with a type qualifier does not have that form. (It's | ||||
15895 | // legal to specify a qualified type as a friend, you just can't write the | ||||
15896 | // keywords.) | ||||
15897 | if (DS.getTypeQualifiers()) { | ||||
15898 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | ||||
15899 | Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; | ||||
15900 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | ||||
15901 | Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; | ||||
15902 | if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) | ||||
15903 | Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; | ||||
15904 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | ||||
15905 | Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; | ||||
15906 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | ||||
15907 | Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; | ||||
15908 | } | ||||
15909 | |||||
15910 | // Try to convert the decl specifier to a type. This works for | ||||
15911 | // friend templates because ActOnTag never produces a ClassTemplateDecl | ||||
15912 | // for a TUK_Friend. | ||||
15913 | Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); | ||||
15914 | TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); | ||||
15915 | QualType T = TSI->getType(); | ||||
15916 | if (TheDeclarator.isInvalidType()) | ||||
15917 | return nullptr; | ||||
15918 | |||||
15919 | if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) | ||||
15920 | return nullptr; | ||||
15921 | |||||
15922 | // This is definitely an error in C++98. It's probably meant to | ||||
15923 | // be forbidden in C++0x, too, but the specification is just | ||||
15924 | // poorly written. | ||||
15925 | // | ||||
15926 | // The problem is with declarations like the following: | ||||
15927 | // template <T> friend A<T>::foo; | ||||
15928 | // where deciding whether a class C is a friend or not now hinges | ||||
15929 | // on whether there exists an instantiation of A that causes | ||||
15930 | // 'foo' to equal C. There are restrictions on class-heads | ||||
15931 | // (which we declare (by fiat) elaborated friend declarations to | ||||
15932 | // be) that makes this tractable. | ||||
15933 | // | ||||
15934 | // FIXME: handle "template <> friend class A<T>;", which | ||||
15935 | // is possibly well-formed? Who even knows? | ||||
15936 | if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { | ||||
15937 | Diag(Loc, diag::err_tagless_friend_type_template) | ||||
15938 | << DS.getSourceRange(); | ||||
15939 | return nullptr; | ||||
15940 | } | ||||
15941 | |||||
15942 | // C++98 [class.friend]p1: A friend of a class is a function | ||||
15943 | // or class that is not a member of the class . . . | ||||
15944 | // This is fixed in DR77, which just barely didn't make the C++03 | ||||
15945 | // deadline. It's also a very silly restriction that seriously | ||||
15946 | // affects inner classes and which nobody else seems to implement; | ||||
15947 | // thus we never diagnose it, not even in -pedantic. | ||||
15948 | // | ||||
15949 | // But note that we could warn about it: it's always useless to | ||||
15950 | // friend one of your own members (it's not, however, worthless to | ||||
15951 | // friend a member of an arbitrary specialization of your template). | ||||
15952 | |||||
15953 | Decl *D; | ||||
15954 | if (!TempParams.empty()) | ||||
15955 | D = FriendTemplateDecl::Create(Context, CurContext, Loc, | ||||
15956 | TempParams, | ||||
15957 | TSI, | ||||
15958 | DS.getFriendSpecLoc()); | ||||
15959 | else | ||||
15960 | D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); | ||||
15961 | |||||
15962 | if (!D) | ||||
15963 | return nullptr; | ||||
15964 | |||||
15965 | D->setAccess(AS_public); | ||||
15966 | CurContext->addDecl(D); | ||||
15967 | |||||
15968 | return D; | ||||
15969 | } | ||||
15970 | |||||
15971 | NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, | ||||
15972 | MultiTemplateParamsArg TemplateParams) { | ||||
15973 | const DeclSpec &DS = D.getDeclSpec(); | ||||
15974 | |||||
15975 | assert(DS.isFriendSpecified())((DS.isFriendSpecified()) ? static_cast<void> (0) : __assert_fail ("DS.isFriendSpecified()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 15975, __PRETTY_FUNCTION__)); | ||||
15976 | assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) ? static_cast <void> (0) : __assert_fail ("DS.getStorageClassSpec() == DeclSpec::SCS_unspecified" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 15976, __PRETTY_FUNCTION__)); | ||||
15977 | |||||
15978 | SourceLocation Loc = D.getIdentifierLoc(); | ||||
15979 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||
15980 | |||||
15981 | // C++ [class.friend]p1 | ||||
15982 | // A friend of a class is a function or class.... | ||||
15983 | // Note that this sees through typedefs, which is intended. | ||||
15984 | // It *doesn't* see through dependent types, which is correct | ||||
15985 | // according to [temp.arg.type]p3: | ||||
15986 | // If a declaration acquires a function type through a | ||||
15987 | // type dependent on a template-parameter and this causes | ||||
15988 | // a declaration that does not use the syntactic form of a | ||||
15989 | // function declarator to have a function type, the program | ||||
15990 | // is ill-formed. | ||||
15991 | if (!TInfo->getType()->isFunctionType()) { | ||||
15992 | Diag(Loc, diag::err_unexpected_friend); | ||||
15993 | |||||
15994 | // It might be worthwhile to try to recover by creating an | ||||
15995 | // appropriate declaration. | ||||
15996 | return nullptr; | ||||
15997 | } | ||||
15998 | |||||
15999 | // C++ [namespace.memdef]p3 | ||||
16000 | // - If a friend declaration in a non-local class first declares a | ||||
16001 | // class or function, the friend class or function is a member | ||||
16002 | // of the innermost enclosing namespace. | ||||
16003 | // - The name of the friend is not found by simple name lookup | ||||
16004 | // until a matching declaration is provided in that namespace | ||||
16005 | // scope (either before or after the class declaration granting | ||||
16006 | // friendship). | ||||
16007 | // - If a friend function is called, its name may be found by the | ||||
16008 | // name lookup that considers functions from namespaces and | ||||
16009 | // classes associated with the types of the function arguments. | ||||
16010 | // - When looking for a prior declaration of a class or a function | ||||
16011 | // declared as a friend, scopes outside the innermost enclosing | ||||
16012 | // namespace scope are not considered. | ||||
16013 | |||||
16014 | CXXScopeSpec &SS = D.getCXXScopeSpec(); | ||||
16015 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | ||||
16016 | assert(NameInfo.getName())((NameInfo.getName()) ? static_cast<void> (0) : __assert_fail ("NameInfo.getName()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 16016, __PRETTY_FUNCTION__)); | ||||
16017 | |||||
16018 | // Check for unexpanded parameter packs. | ||||
16019 | if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || | ||||
16020 | DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || | ||||
16021 | DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) | ||||
16022 | return nullptr; | ||||
16023 | |||||
16024 | // The context we found the declaration in, or in which we should | ||||
16025 | // create the declaration. | ||||
16026 | DeclContext *DC; | ||||
16027 | Scope *DCScope = S; | ||||
16028 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||
16029 | ForExternalRedeclaration); | ||||
16030 | |||||
16031 | // There are five cases here. | ||||
16032 | // - There's no scope specifier and we're in a local class. Only look | ||||
16033 | // for functions declared in the immediately-enclosing block scope. | ||||
16034 | // We recover from invalid scope qualifiers as if they just weren't there. | ||||
16035 | FunctionDecl *FunctionContainingLocalClass = nullptr; | ||||
16036 | if ((SS.isInvalid() || !SS.isSet()) && | ||||
16037 | (FunctionContainingLocalClass = | ||||
16038 | cast<CXXRecordDecl>(CurContext)->isLocalClass())) { | ||||
16039 | // C++11 [class.friend]p11: | ||||
16040 | // If a friend declaration appears in a local class and the name | ||||
16041 | // specified is an unqualified name, a prior declaration is | ||||
16042 | // looked up without considering scopes that are outside the | ||||
16043 | // innermost enclosing non-class scope. For a friend function | ||||
16044 | // declaration, if there is no prior declaration, the program is | ||||
16045 | // ill-formed. | ||||
16046 | |||||
16047 | // Find the innermost enclosing non-class scope. This is the block | ||||
16048 | // scope containing the local class definition (or for a nested class, | ||||
16049 | // the outer local class). | ||||
16050 | DCScope = S->getFnParent(); | ||||
16051 | |||||
16052 | // Look up the function name in the scope. | ||||
16053 | Previous.clear(LookupLocalFriendName); | ||||
16054 | LookupName(Previous, S, /*AllowBuiltinCreation*/false); | ||||
16055 | |||||
16056 | if (!Previous.empty()) { | ||||
16057 | // All possible previous declarations must have the same context: | ||||
16058 | // either they were declared at block scope or they are members of | ||||
16059 | // one of the enclosing local classes. | ||||
16060 | DC = Previous.getRepresentativeDecl()->getDeclContext(); | ||||
16061 | } else { | ||||
16062 | // This is ill-formed, but provide the context that we would have | ||||
16063 | // declared the function in, if we were permitted to, for error recovery. | ||||
16064 | DC = FunctionContainingLocalClass; | ||||
16065 | } | ||||
16066 | adjustContextForLocalExternDecl(DC); | ||||
16067 | |||||
16068 | // C++ [class.friend]p6: | ||||
16069 | // A function can be defined in a friend declaration of a class if and | ||||
16070 | // only if the class is a non-local class (9.8), the function name is | ||||
16071 | // unqualified, and the function has namespace scope. | ||||
16072 | if (D.isFunctionDefinition()) { | ||||
16073 | Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); | ||||
16074 | } | ||||
16075 | |||||
16076 | // - There's no scope specifier, in which case we just go to the | ||||
16077 | // appropriate scope and look for a function or function template | ||||
16078 | // there as appropriate. | ||||
16079 | } else if (SS.isInvalid() || !SS.isSet()) { | ||||
16080 | // C++11 [namespace.memdef]p3: | ||||
16081 | // If the name in a friend declaration is neither qualified nor | ||||
16082 | // a template-id and the declaration is a function or an | ||||
16083 | // elaborated-type-specifier, the lookup to determine whether | ||||
16084 | // the entity has been previously declared shall not consider | ||||
16085 | // any scopes outside the innermost enclosing namespace. | ||||
16086 | bool isTemplateId = | ||||
16087 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; | ||||
16088 | |||||
16089 | // Find the appropriate context according to the above. | ||||
16090 | DC = CurContext; | ||||
16091 | |||||
16092 | // Skip class contexts. If someone can cite chapter and verse | ||||
16093 | // for this behavior, that would be nice --- it's what GCC and | ||||
16094 | // EDG do, and it seems like a reasonable intent, but the spec | ||||
16095 | // really only says that checks for unqualified existing | ||||
16096 | // declarations should stop at the nearest enclosing namespace, | ||||
16097 | // not that they should only consider the nearest enclosing | ||||
16098 | // namespace. | ||||
16099 | while (DC->isRecord()) | ||||
16100 | DC = DC->getParent(); | ||||
16101 | |||||
16102 | DeclContext *LookupDC = DC; | ||||
16103 | while (LookupDC->isTransparentContext()) | ||||
16104 | LookupDC = LookupDC->getParent(); | ||||
16105 | |||||
16106 | while (true) { | ||||
16107 | LookupQualifiedName(Previous, LookupDC); | ||||
16108 | |||||
16109 | if (!Previous.empty()) { | ||||
16110 | DC = LookupDC; | ||||
16111 | break; | ||||
16112 | } | ||||
16113 | |||||
16114 | if (isTemplateId) { | ||||
16115 | if (isa<TranslationUnitDecl>(LookupDC)) break; | ||||
16116 | } else { | ||||
16117 | if (LookupDC->isFileContext()) break; | ||||
16118 | } | ||||
16119 | LookupDC = LookupDC->getParent(); | ||||
16120 | } | ||||
16121 | |||||
16122 | DCScope = getScopeForDeclContext(S, DC); | ||||
16123 | |||||
16124 | // - There's a non-dependent scope specifier, in which case we | ||||
16125 | // compute it and do a previous lookup there for a function | ||||
16126 | // or function template. | ||||
16127 | } else if (!SS.getScopeRep()->isDependent()) { | ||||
16128 | DC = computeDeclContext(SS); | ||||
16129 | if (!DC) return nullptr; | ||||
16130 | |||||
16131 | if (RequireCompleteDeclContext(SS, DC)) return nullptr; | ||||
16132 | |||||
16133 | LookupQualifiedName(Previous, DC); | ||||
16134 | |||||
16135 | // C++ [class.friend]p1: A friend of a class is a function or | ||||
16136 | // class that is not a member of the class . . . | ||||
16137 | if (DC->Equals(CurContext)) | ||||
16138 | Diag(DS.getFriendSpecLoc(), | ||||
16139 | getLangOpts().CPlusPlus11 ? | ||||
16140 | diag::warn_cxx98_compat_friend_is_member : | ||||
16141 | diag::err_friend_is_member); | ||||
16142 | |||||
16143 | if (D.isFunctionDefinition()) { | ||||
16144 | // C++ [class.friend]p6: | ||||
16145 | // A function can be defined in a friend declaration of a class if and | ||||
16146 | // only if the class is a non-local class (9.8), the function name is | ||||
16147 | // unqualified, and the function has namespace scope. | ||||
16148 | // | ||||
16149 | // FIXME: We should only do this if the scope specifier names the | ||||
16150 | // innermost enclosing namespace; otherwise the fixit changes the | ||||
16151 | // meaning of the code. | ||||
16152 | SemaDiagnosticBuilder DB | ||||
16153 | = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); | ||||
16154 | |||||
16155 | DB << SS.getScopeRep(); | ||||
16156 | if (DC->isFileContext()) | ||||
16157 | DB << FixItHint::CreateRemoval(SS.getRange()); | ||||
16158 | SS.clear(); | ||||
16159 | } | ||||
16160 | |||||
16161 | // - There's a scope specifier that does not match any template | ||||
16162 | // parameter lists, in which case we use some arbitrary context, | ||||
16163 | // create a method or method template, and wait for instantiation. | ||||
16164 | // - There's a scope specifier that does match some template | ||||
16165 | // parameter lists, which we don't handle right now. | ||||
16166 | } else { | ||||
16167 | if (D.isFunctionDefinition()) { | ||||
16168 | // C++ [class.friend]p6: | ||||
16169 | // A function can be defined in a friend declaration of a class if and | ||||
16170 | // only if the class is a non-local class (9.8), the function name is | ||||
16171 | // unqualified, and the function has namespace scope. | ||||
16172 | Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) | ||||
16173 | << SS.getScopeRep(); | ||||
16174 | } | ||||
16175 | |||||
16176 | DC = CurContext; | ||||
16177 | assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?")((isa<CXXRecordDecl>(DC) && "friend declaration not in class?" ) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(DC) && \"friend declaration not in class?\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 16177, __PRETTY_FUNCTION__)); | ||||
16178 | } | ||||
16179 | |||||
16180 | if (!DC->isRecord()) { | ||||
16181 | int DiagArg = -1; | ||||
16182 | switch (D.getName().getKind()) { | ||||
16183 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | ||||
16184 | case UnqualifiedIdKind::IK_ConstructorName: | ||||
16185 | DiagArg = 0; | ||||
16186 | break; | ||||
16187 | case UnqualifiedIdKind::IK_DestructorName: | ||||
16188 | DiagArg = 1; | ||||
16189 | break; | ||||
16190 | case UnqualifiedIdKind::IK_ConversionFunctionId: | ||||
16191 | DiagArg = 2; | ||||
16192 | break; | ||||
16193 | case UnqualifiedIdKind::IK_DeductionGuideName: | ||||
16194 | DiagArg = 3; | ||||
16195 | break; | ||||
16196 | case UnqualifiedIdKind::IK_Identifier: | ||||
16197 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | ||||
16198 | case UnqualifiedIdKind::IK_LiteralOperatorId: | ||||
16199 | case UnqualifiedIdKind::IK_OperatorFunctionId: | ||||
16200 | case UnqualifiedIdKind::IK_TemplateId: | ||||
16201 | break; | ||||
16202 | } | ||||
16203 | // This implies that it has to be an operator or function. | ||||
16204 | if (DiagArg >= 0) { | ||||
16205 | Diag(Loc, diag::err_introducing_special_friend) << DiagArg; | ||||
16206 | return nullptr; | ||||
16207 | } | ||||
16208 | } | ||||
16209 | |||||
16210 | // FIXME: This is an egregious hack to cope with cases where the scope stack | ||||
16211 | // does not contain the declaration context, i.e., in an out-of-line | ||||
16212 | // definition of a class. | ||||
16213 | Scope FakeDCScope(S, Scope::DeclScope, Diags); | ||||
16214 | if (!DCScope) { | ||||
16215 | FakeDCScope.setEntity(DC); | ||||
16216 | DCScope = &FakeDCScope; | ||||
16217 | } | ||||
16218 | |||||
16219 | bool AddToScope = true; | ||||
16220 | NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, | ||||
16221 | TemplateParams, AddToScope); | ||||
16222 | if (!ND) return nullptr; | ||||
16223 | |||||
16224 | assert(ND->getLexicalDeclContext() == CurContext)((ND->getLexicalDeclContext() == CurContext) ? static_cast <void> (0) : __assert_fail ("ND->getLexicalDeclContext() == CurContext" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 16224, __PRETTY_FUNCTION__)); | ||||
16225 | |||||
16226 | // If we performed typo correction, we might have added a scope specifier | ||||
16227 | // and changed the decl context. | ||||
16228 | DC = ND->getDeclContext(); | ||||
16229 | |||||
16230 | // Add the function declaration to the appropriate lookup tables, | ||||
16231 | // adjusting the redeclarations list as necessary. We don't | ||||
16232 | // want to do this yet if the friending class is dependent. | ||||
16233 | // | ||||
16234 | // Also update the scope-based lookup if the target context's | ||||
16235 | // lookup context is in lexical scope. | ||||
16236 | if (!CurContext->isDependentContext()) { | ||||
16237 | DC = DC->getRedeclContext(); | ||||
16238 | DC->makeDeclVisibleInContext(ND); | ||||
16239 | if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) | ||||
16240 | PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); | ||||
16241 | } | ||||
16242 | |||||
16243 | FriendDecl *FrD = FriendDecl::Create(Context, CurContext, | ||||
16244 | D.getIdentifierLoc(), ND, | ||||
16245 | DS.getFriendSpecLoc()); | ||||
16246 | FrD->setAccess(AS_public); | ||||
16247 | CurContext->addDecl(FrD); | ||||
16248 | |||||
16249 | if (ND->isInvalidDecl()) { | ||||
16250 | FrD->setInvalidDecl(); | ||||
16251 | } else { | ||||
16252 | if (DC->isRecord()) CheckFriendAccess(ND); | ||||
16253 | |||||
16254 | FunctionDecl *FD; | ||||
16255 | if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) | ||||
16256 | FD = FTD->getTemplatedDecl(); | ||||
16257 | else | ||||
16258 | FD = cast<FunctionDecl>(ND); | ||||
16259 | |||||
16260 | // C++11 [dcl.fct.default]p4: If a friend declaration specifies a | ||||
16261 | // default argument expression, that declaration shall be a definition | ||||
16262 | // and shall be the only declaration of the function or function | ||||
16263 | // template in the translation unit. | ||||
16264 | if (functionDeclHasDefaultArgument(FD)) { | ||||
16265 | // We can't look at FD->getPreviousDecl() because it may not have been set | ||||
16266 | // if we're in a dependent context. If the function is known to be a | ||||
16267 | // redeclaration, we will have narrowed Previous down to the right decl. | ||||
16268 | if (D.isRedeclaration()) { | ||||
16269 | Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); | ||||
16270 | Diag(Previous.getRepresentativeDecl()->getLocation(), | ||||
16271 | diag::note_previous_declaration); | ||||
16272 | } else if (!D.isFunctionDefinition()) | ||||
16273 | Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); | ||||
16274 | } | ||||
16275 | |||||
16276 | // Mark templated-scope function declarations as unsupported. | ||||
16277 | if (FD->getNumTemplateParameterLists() && SS.isValid()) { | ||||
16278 | Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) | ||||
16279 | << SS.getScopeRep() << SS.getRange() | ||||
16280 | << cast<CXXRecordDecl>(CurContext); | ||||
16281 | FrD->setUnsupportedFriend(true); | ||||
16282 | } | ||||
16283 | } | ||||
16284 | |||||
16285 | return ND; | ||||
16286 | } | ||||
16287 | |||||
16288 | void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { | ||||
16289 | AdjustDeclIfTemplate(Dcl); | ||||
16290 | |||||
16291 | FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); | ||||
16292 | if (!Fn) { | ||||
16293 | Diag(DelLoc, diag::err_deleted_non_function); | ||||
16294 | return; | ||||
16295 | } | ||||
16296 | |||||
16297 | // Deleted function does not have a body. | ||||
16298 | Fn->setWillHaveBody(false); | ||||
16299 | |||||
16300 | if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { | ||||
16301 | // Don't consider the implicit declaration we generate for explicit | ||||
16302 | // specializations. FIXME: Do not generate these implicit declarations. | ||||
16303 | if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || | ||||
16304 | Prev->getPreviousDecl()) && | ||||
16305 | !Prev->isDefined()) { | ||||
16306 | Diag(DelLoc, diag::err_deleted_decl_not_first); | ||||
16307 | Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), | ||||
16308 | Prev->isImplicit() ? diag::note_previous_implicit_declaration | ||||
16309 | : diag::note_previous_declaration); | ||||
16310 | } | ||||
16311 | // If the declaration wasn't the first, we delete the function anyway for | ||||
16312 | // recovery. | ||||
16313 | Fn = Fn->getCanonicalDecl(); | ||||
16314 | } | ||||
16315 | |||||
16316 | // dllimport/dllexport cannot be deleted. | ||||
16317 | if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { | ||||
16318 | Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; | ||||
16319 | Fn->setInvalidDecl(); | ||||
16320 | } | ||||
16321 | |||||
16322 | if (Fn->isDeleted()) | ||||
16323 | return; | ||||
16324 | |||||
16325 | // C++11 [basic.start.main]p3: | ||||
16326 | // A program that defines main as deleted [...] is ill-formed. | ||||
16327 | if (Fn->isMain()) | ||||
16328 | Diag(DelLoc, diag::err_deleted_main); | ||||
16329 | |||||
16330 | // C++11 [dcl.fct.def.delete]p4: | ||||
16331 | // A deleted function is implicitly inline. | ||||
16332 | Fn->setImplicitlyInline(); | ||||
16333 | Fn->setDeletedAsWritten(); | ||||
16334 | |||||
16335 | // See if we're deleting a function which is already known to override a | ||||
16336 | // non-deleted virtual function. | ||||
16337 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { | ||||
16338 | bool IssuedDiagnostic = false; | ||||
16339 | for (const CXXMethodDecl *O : MD->overridden_methods()) { | ||||
16340 | if (!(*MD->begin_overridden_methods())->isDeleted()) { | ||||
16341 | if (!IssuedDiagnostic) { | ||||
16342 | Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); | ||||
16343 | IssuedDiagnostic = true; | ||||
16344 | } | ||||
16345 | Diag(O->getLocation(), diag::note_overridden_virtual_function); | ||||
16346 | } | ||||
16347 | } | ||||
16348 | // If this function was implicitly deleted because it was defaulted, | ||||
16349 | // explain why it was deleted. | ||||
16350 | if (IssuedDiagnostic && MD->isDefaulted()) | ||||
16351 | DiagnoseDeletedDefaultedFunction(MD); | ||||
16352 | } | ||||
16353 | } | ||||
16354 | |||||
16355 | void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { | ||||
16356 | if (!Dcl || Dcl->isInvalidDecl()) | ||||
16357 | return; | ||||
16358 | |||||
16359 | auto *FD = dyn_cast<FunctionDecl>(Dcl); | ||||
16360 | if (!FD) { | ||||
16361 | if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { | ||||
16362 | if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { | ||||
16363 | Diag(DefaultLoc, diag::err_defaulted_comparison_template); | ||||
16364 | return; | ||||
16365 | } | ||||
16366 | } | ||||
16367 | |||||
16368 | Diag(DefaultLoc, diag::err_default_special_members) | ||||
16369 | << getLangOpts().CPlusPlus2a; | ||||
16370 | return; | ||||
16371 | } | ||||
16372 | |||||
16373 | // Reject if this can't possibly be a defaultable function. | ||||
16374 | DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); | ||||
16375 | if (!DefKind && | ||||
16376 | // A dependent function that doesn't locally look defaultable can | ||||
16377 | // still instantiate to a defaultable function if it's a constructor | ||||
16378 | // or assignment operator. | ||||
16379 | (!FD->isDependentContext() || | ||||
16380 | (!isa<CXXConstructorDecl>(FD) && | ||||
16381 | FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { | ||||
16382 | Diag(DefaultLoc, diag::err_default_special_members) | ||||
16383 | << getLangOpts().CPlusPlus2a; | ||||
16384 | return; | ||||
16385 | } | ||||
16386 | |||||
16387 | if (DefKind.isComparison() && | ||||
16388 | !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { | ||||
16389 | Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) | ||||
16390 | << (int)DefKind.asComparison(); | ||||
16391 | return; | ||||
16392 | } | ||||
16393 | |||||
16394 | // Issue compatibility warning. We already warned if the operator is | ||||
16395 | // 'operator<=>' when parsing the '<=>' token. | ||||
16396 | if (DefKind.isComparison() && | ||||
16397 | DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { | ||||
16398 | Diag(DefaultLoc, getLangOpts().CPlusPlus2a | ||||
16399 | ? diag::warn_cxx17_compat_defaulted_comparison | ||||
16400 | : diag::ext_defaulted_comparison); | ||||
16401 | } | ||||
16402 | |||||
16403 | FD->setDefaulted(); | ||||
16404 | FD->setExplicitlyDefaulted(); | ||||
16405 | |||||
16406 | // Defer checking functions that are defaulted in a dependent context. | ||||
16407 | if (FD->isDependentContext()) | ||||
16408 | return; | ||||
16409 | |||||
16410 | // Unset that we will have a body for this function. We might not, | ||||
16411 | // if it turns out to be trivial, and we don't need this marking now | ||||
16412 | // that we've marked it as defaulted. | ||||
16413 | FD->setWillHaveBody(false); | ||||
16414 | |||||
16415 | // If this definition appears within the record, do the checking when | ||||
16416 | // the record is complete. This is always the case for a defaulted | ||||
16417 | // comparison. | ||||
16418 | if (DefKind.isComparison()) | ||||
16419 | return; | ||||
16420 | auto *MD = cast<CXXMethodDecl>(FD); | ||||
16421 | |||||
16422 | const FunctionDecl *Primary = FD; | ||||
16423 | if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) | ||||
16424 | // Ask the template instantiation pattern that actually had the | ||||
16425 | // '= default' on it. | ||||
16426 | Primary = Pattern; | ||||
16427 | |||||
16428 | // If the method was defaulted on its first declaration, we will have | ||||
16429 | // already performed the checking in CheckCompletedCXXClass. Such a | ||||
16430 | // declaration doesn't trigger an implicit definition. | ||||
16431 | if (Primary->getCanonicalDecl()->isDefaulted()) | ||||
16432 | return; | ||||
16433 | |||||
16434 | if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) | ||||
16435 | MD->setInvalidDecl(); | ||||
16436 | else | ||||
16437 | DefineImplicitSpecialMember(*this, MD, DefaultLoc); | ||||
16438 | } | ||||
16439 | |||||
16440 | static void SearchForReturnInStmt(Sema &Self, Stmt *S) { | ||||
16441 | for (Stmt *SubStmt : S->children()) { | ||||
16442 | if (!SubStmt) | ||||
16443 | continue; | ||||
16444 | if (isa<ReturnStmt>(SubStmt)) | ||||
16445 | Self.Diag(SubStmt->getBeginLoc(), | ||||
16446 | diag::err_return_in_constructor_handler); | ||||
16447 | if (!isa<Expr>(SubStmt)) | ||||
16448 | SearchForReturnInStmt(Self, SubStmt); | ||||
16449 | } | ||||
16450 | } | ||||
16451 | |||||
16452 | void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { | ||||
16453 | for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { | ||||
16454 | CXXCatchStmt *Handler = TryBlock->getHandler(I); | ||||
16455 | SearchForReturnInStmt(*this, Handler); | ||||
16456 | } | ||||
16457 | } | ||||
16458 | |||||
16459 | bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, | ||||
16460 | const CXXMethodDecl *Old) { | ||||
16461 | const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); | ||||
16462 | const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); | ||||
16463 | |||||
16464 | if (OldFT->hasExtParameterInfos()) { | ||||
16465 | for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) | ||||
16466 | // A parameter of the overriding method should be annotated with noescape | ||||
16467 | // if the corresponding parameter of the overridden method is annotated. | ||||
16468 | if (OldFT->getExtParameterInfo(I).isNoEscape() && | ||||
16469 | !NewFT->getExtParameterInfo(I).isNoEscape()) { | ||||
16470 | Diag(New->getParamDecl(I)->getLocation(), | ||||
16471 | diag::warn_overriding_method_missing_noescape); | ||||
16472 | Diag(Old->getParamDecl(I)->getLocation(), | ||||
16473 | diag::note_overridden_marked_noescape); | ||||
16474 | } | ||||
16475 | } | ||||
16476 | |||||
16477 | // Virtual overrides must have the same code_seg. | ||||
16478 | const auto *OldCSA = Old->getAttr<CodeSegAttr>(); | ||||
16479 | const auto *NewCSA = New->getAttr<CodeSegAttr>(); | ||||
16480 | if ((NewCSA || OldCSA) && | ||||
16481 | (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { | ||||
16482 | Diag(New->getLocation(), diag::err_mismatched_code_seg_override); | ||||
16483 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||
16484 | return true; | ||||
16485 | } | ||||
16486 | |||||
16487 | CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); | ||||
16488 | |||||
16489 | // If the calling conventions match, everything is fine | ||||
16490 | if (NewCC == OldCC) | ||||
16491 | return false; | ||||
16492 | |||||
16493 | // If the calling conventions mismatch because the new function is static, | ||||
16494 | // suppress the calling convention mismatch error; the error about static | ||||
16495 | // function override (err_static_overrides_virtual from | ||||
16496 | // Sema::CheckFunctionDeclaration) is more clear. | ||||
16497 | if (New->getStorageClass() == SC_Static) | ||||
16498 | return false; | ||||
16499 | |||||
16500 | Diag(New->getLocation(), | ||||
16501 | diag::err_conflicting_overriding_cc_attributes) | ||||
16502 | << New->getDeclName() << New->getType() << Old->getType(); | ||||
16503 | Diag(Old->getLocation(), diag::note_overridden_virtual_function); | ||||
16504 | return true; | ||||
16505 | } | ||||
16506 | |||||
16507 | bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, | ||||
16508 | const CXXMethodDecl *Old) { | ||||
16509 | QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); | ||||
16510 | QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); | ||||
16511 | |||||
16512 | if (Context.hasSameType(NewTy, OldTy) || | ||||
16513 | NewTy->isDependentType() || OldTy->isDependentType()) | ||||
16514 | return false; | ||||
16515 | |||||
16516 | // Check if the return types are covariant | ||||
16517 | QualType NewClassTy, OldClassTy; | ||||
16518 | |||||
16519 | /// Both types must be pointers or references to classes. | ||||
16520 | if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { | ||||
16521 | if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { | ||||
16522 | NewClassTy = NewPT->getPointeeType(); | ||||
16523 | OldClassTy = OldPT->getPointeeType(); | ||||
16524 | } | ||||
16525 | } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { | ||||
16526 | if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { | ||||
16527 | if (NewRT->getTypeClass() == OldRT->getTypeClass()) { | ||||
16528 | NewClassTy = NewRT->getPointeeType(); | ||||
16529 | OldClassTy = OldRT->getPointeeType(); | ||||
16530 | } | ||||
16531 | } | ||||
16532 | } | ||||
16533 | |||||
16534 | // The return types aren't either both pointers or references to a class type. | ||||
16535 | if (NewClassTy.isNull()) { | ||||
16536 | Diag(New->getLocation(), | ||||
16537 | diag::err_different_return_type_for_overriding_virtual_function) | ||||
16538 | << New->getDeclName() << NewTy << OldTy | ||||
16539 | << New->getReturnTypeSourceRange(); | ||||
16540 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) | ||||
16541 | << Old->getReturnTypeSourceRange(); | ||||
16542 | |||||
16543 | return true; | ||||
16544 | } | ||||
16545 | |||||
16546 | if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { | ||||
16547 | // C++14 [class.virtual]p8: | ||||
16548 | // If the class type in the covariant return type of D::f differs from | ||||
16549 | // that of B::f, the class type in the return type of D::f shall be | ||||
16550 | // complete at the point of declaration of D::f or shall be the class | ||||
16551 | // type D. | ||||
16552 | if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { | ||||
16553 | if (!RT->isBeingDefined() && | ||||
16554 | RequireCompleteType(New->getLocation(), NewClassTy, | ||||
16555 | diag::err_covariant_return_incomplete, | ||||
16556 | New->getDeclName())) | ||||
16557 | return true; | ||||
16558 | } | ||||
16559 | |||||
16560 | // Check if the new class derives from the old class. | ||||
16561 | if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { | ||||
16562 | Diag(New->getLocation(), diag::err_covariant_return_not_derived) | ||||
16563 | << New->getDeclName() << NewTy << OldTy | ||||
16564 | << New->getReturnTypeSourceRange(); | ||||
16565 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) | ||||
16566 | << Old->getReturnTypeSourceRange(); | ||||
16567 | return true; | ||||
16568 | } | ||||
16569 | |||||
16570 | // Check if we the conversion from derived to base is valid. | ||||
16571 | if (CheckDerivedToBaseConversion( | ||||
16572 | NewClassTy, OldClassTy, | ||||
16573 | diag::err_covariant_return_inaccessible_base, | ||||
16574 | diag::err_covariant_return_ambiguous_derived_to_base_conv, | ||||
16575 | New->getLocation(), New->getReturnTypeSourceRange(), | ||||
16576 | New->getDeclName(), nullptr)) { | ||||
16577 | // FIXME: this note won't trigger for delayed access control | ||||
16578 | // diagnostics, and it's impossible to get an undelayed error | ||||
16579 | // here from access control during the original parse because | ||||
16580 | // the ParsingDeclSpec/ParsingDeclarator are still in scope. | ||||
16581 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) | ||||
16582 | << Old->getReturnTypeSourceRange(); | ||||
16583 | return true; | ||||
16584 | } | ||||
16585 | } | ||||
16586 | |||||
16587 | // The qualifiers of the return types must be the same. | ||||
16588 | if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { | ||||
16589 | Diag(New->getLocation(), | ||||
16590 | diag::err_covariant_return_type_different_qualifications) | ||||
16591 | << New->getDeclName() << NewTy << OldTy | ||||
16592 | << New->getReturnTypeSourceRange(); | ||||
16593 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) | ||||
16594 | << Old->getReturnTypeSourceRange(); | ||||
16595 | return true; | ||||
16596 | } | ||||
16597 | |||||
16598 | |||||
16599 | // The new class type must have the same or less qualifiers as the old type. | ||||
16600 | if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { | ||||
16601 | Diag(New->getLocation(), | ||||
16602 | diag::err_covariant_return_type_class_type_more_qualified) | ||||
16603 | << New->getDeclName() << NewTy << OldTy | ||||
16604 | << New->getReturnTypeSourceRange(); | ||||
16605 | Diag(Old->getLocation(), diag::note_overridden_virtual_function) | ||||
16606 | << Old->getReturnTypeSourceRange(); | ||||
16607 | return true; | ||||
16608 | } | ||||
16609 | |||||
16610 | return false; | ||||
16611 | } | ||||
16612 | |||||
16613 | /// Mark the given method pure. | ||||
16614 | /// | ||||
16615 | /// \param Method the method to be marked pure. | ||||
16616 | /// | ||||
16617 | /// \param InitRange the source range that covers the "0" initializer. | ||||
16618 | bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { | ||||
16619 | SourceLocation EndLoc = InitRange.getEnd(); | ||||
16620 | if (EndLoc.isValid()) | ||||
16621 | Method->setRangeEnd(EndLoc); | ||||
16622 | |||||
16623 | if (Method->isVirtual() || Method->getParent()->isDependentContext()) { | ||||
16624 | Method->setPure(); | ||||
16625 | return false; | ||||
16626 | } | ||||
16627 | |||||
16628 | if (!Method->isInvalidDecl()) | ||||
16629 | Diag(Method->getLocation(), diag::err_non_virtual_pure) | ||||
16630 | << Method->getDeclName() << InitRange; | ||||
16631 | return true; | ||||
16632 | } | ||||
16633 | |||||
16634 | void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { | ||||
16635 | if (D->getFriendObjectKind()) | ||||
16636 | Diag(D->getLocation(), diag::err_pure_friend); | ||||
16637 | else if (auto *M = dyn_cast<CXXMethodDecl>(D)) | ||||
16638 | CheckPureMethod(M, ZeroLoc); | ||||
16639 | else | ||||
16640 | Diag(D->getLocation(), diag::err_illegal_initializer); | ||||
16641 | } | ||||
16642 | |||||
16643 | /// Determine whether the given declaration is a global variable or | ||||
16644 | /// static data member. | ||||
16645 | static bool isNonlocalVariable(const Decl *D) { | ||||
16646 | if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) | ||||
16647 | return Var->hasGlobalStorage(); | ||||
16648 | |||||
16649 | return false; | ||||
16650 | } | ||||
16651 | |||||
16652 | /// Invoked when we are about to parse an initializer for the declaration | ||||
16653 | /// 'Dcl'. | ||||
16654 | /// | ||||
16655 | /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a | ||||
16656 | /// static data member of class X, names should be looked up in the scope of | ||||
16657 | /// class X. If the declaration had a scope specifier, a scope will have | ||||
16658 | /// been created and passed in for this purpose. Otherwise, S will be null. | ||||
16659 | void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { | ||||
16660 | // If there is no declaration, there was an error parsing it. | ||||
16661 | if (!D || D->isInvalidDecl()) | ||||
16662 | return; | ||||
16663 | |||||
16664 | // We will always have a nested name specifier here, but this declaration | ||||
16665 | // might not be out of line if the specifier names the current namespace: | ||||
16666 | // extern int n; | ||||
16667 | // int ::n = 0; | ||||
16668 | if (S && D->isOutOfLine()) | ||||
16669 | EnterDeclaratorContext(S, D->getDeclContext()); | ||||
16670 | |||||
16671 | // If we are parsing the initializer for a static data member, push a | ||||
16672 | // new expression evaluation context that is associated with this static | ||||
16673 | // data member. | ||||
16674 | if (isNonlocalVariable(D)) | ||||
16675 | PushExpressionEvaluationContext( | ||||
16676 | ExpressionEvaluationContext::PotentiallyEvaluated, D); | ||||
16677 | } | ||||
16678 | |||||
16679 | /// Invoked after we are finished parsing an initializer for the declaration D. | ||||
16680 | void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { | ||||
16681 | // If there is no declaration, there was an error parsing it. | ||||
16682 | if (!D || D->isInvalidDecl()) | ||||
16683 | return; | ||||
16684 | |||||
16685 | if (isNonlocalVariable(D)) | ||||
16686 | PopExpressionEvaluationContext(); | ||||
16687 | |||||
16688 | if (S && D->isOutOfLine()) | ||||
16689 | ExitDeclaratorContext(S); | ||||
16690 | } | ||||
16691 | |||||
16692 | /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a | ||||
16693 | /// C++ if/switch/while/for statement. | ||||
16694 | /// e.g: "if (int x = f()) {...}" | ||||
16695 | DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { | ||||
16696 | // C++ 6.4p2: | ||||
16697 | // The declarator shall not specify a function or an array. | ||||
16698 | // The type-specifier-seq shall not contain typedef and shall not declare a | ||||
16699 | // new class or enumeration. | ||||
16700 | assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&((D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class of condition decl." ) ? static_cast<void> (0) : __assert_fail ("D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class of condition decl.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 16701, __PRETTY_FUNCTION__)) | ||||
16701 | "Parser allowed 'typedef' as storage class of condition decl.")((D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class of condition decl." ) ? static_cast<void> (0) : __assert_fail ("D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class of condition decl.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 16701, __PRETTY_FUNCTION__)); | ||||
16702 | |||||
16703 | Decl *Dcl = ActOnDeclarator(S, D); | ||||
16704 | if (!Dcl) | ||||
16705 | return true; | ||||
16706 | |||||
16707 | if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. | ||||
16708 | Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) | ||||
16709 | << D.getSourceRange(); | ||||
16710 | return true; | ||||
16711 | } | ||||
16712 | |||||
16713 | return Dcl; | ||||
16714 | } | ||||
16715 | |||||
16716 | void Sema::LoadExternalVTableUses() { | ||||
16717 | if (!ExternalSource) | ||||
16718 | return; | ||||
16719 | |||||
16720 | SmallVector<ExternalVTableUse, 4> VTables; | ||||
16721 | ExternalSource->ReadUsedVTables(VTables); | ||||
16722 | SmallVector<VTableUse, 4> NewUses; | ||||
16723 | for (unsigned I = 0, N = VTables.size(); I != N; ++I) { | ||||
16724 | llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos | ||||
16725 | = VTablesUsed.find(VTables[I].Record); | ||||
16726 | // Even if a definition wasn't required before, it may be required now. | ||||
16727 | if (Pos != VTablesUsed.end()) { | ||||
16728 | if (!Pos->second && VTables[I].DefinitionRequired) | ||||
16729 | Pos->second = true; | ||||
16730 | continue; | ||||
16731 | } | ||||
16732 | |||||
16733 | VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; | ||||
16734 | NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); | ||||
16735 | } | ||||
16736 | |||||
16737 | VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); | ||||
16738 | } | ||||
16739 | |||||
16740 | void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, | ||||
16741 | bool DefinitionRequired) { | ||||
16742 | // Ignore any vtable uses in unevaluated operands or for classes that do | ||||
16743 | // not have a vtable. | ||||
16744 | if (!Class->isDynamicClass() || Class->isDependentContext() || | ||||
16745 | CurContext->isDependentContext() || isUnevaluatedContext()) | ||||
16746 | return; | ||||
16747 | // Do not mark as used if compiling for the device outside of the target | ||||
16748 | // region. | ||||
16749 | if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice && | ||||
16750 | !isInOpenMPDeclareTargetContext() && | ||||
16751 | !isInOpenMPTargetExecutionDirective()) { | ||||
16752 | if (!DefinitionRequired) | ||||
16753 | MarkVirtualMembersReferenced(Loc, Class); | ||||
16754 | return; | ||||
16755 | } | ||||
16756 | |||||
16757 | // Try to insert this class into the map. | ||||
16758 | LoadExternalVTableUses(); | ||||
16759 | Class = Class->getCanonicalDecl(); | ||||
16760 | std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> | ||||
16761 | Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); | ||||
16762 | if (!Pos.second) { | ||||
16763 | // If we already had an entry, check to see if we are promoting this vtable | ||||
16764 | // to require a definition. If so, we need to reappend to the VTableUses | ||||
16765 | // list, since we may have already processed the first entry. | ||||
16766 | if (DefinitionRequired && !Pos.first->second) { | ||||
16767 | Pos.first->second = true; | ||||
16768 | } else { | ||||
16769 | // Otherwise, we can early exit. | ||||
16770 | return; | ||||
16771 | } | ||||
16772 | } else { | ||||
16773 | // The Microsoft ABI requires that we perform the destructor body | ||||
16774 | // checks (i.e. operator delete() lookup) when the vtable is marked used, as | ||||
16775 | // the deleting destructor is emitted with the vtable, not with the | ||||
16776 | // destructor definition as in the Itanium ABI. | ||||
16777 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { | ||||
16778 | CXXDestructorDecl *DD = Class->getDestructor(); | ||||
16779 | if (DD && DD->isVirtual() && !DD->isDeleted()) { | ||||
16780 | if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { | ||||
16781 | // If this is an out-of-line declaration, marking it referenced will | ||||
16782 | // not do anything. Manually call CheckDestructor to look up operator | ||||
16783 | // delete(). | ||||
16784 | ContextRAII SavedContext(*this, DD); | ||||
16785 | CheckDestructor(DD); | ||||
16786 | } else { | ||||
16787 | MarkFunctionReferenced(Loc, Class->getDestructor()); | ||||
16788 | } | ||||
16789 | } | ||||
16790 | } | ||||
16791 | } | ||||
16792 | |||||
16793 | // Local classes need to have their virtual members marked | ||||
16794 | // immediately. For all other classes, we mark their virtual members | ||||
16795 | // at the end of the translation unit. | ||||
16796 | if (Class->isLocalClass()) | ||||
16797 | MarkVirtualMembersReferenced(Loc, Class); | ||||
16798 | else | ||||
16799 | VTableUses.push_back(std::make_pair(Class, Loc)); | ||||
16800 | } | ||||
16801 | |||||
16802 | bool Sema::DefineUsedVTables() { | ||||
16803 | LoadExternalVTableUses(); | ||||
16804 | if (VTableUses.empty()) | ||||
16805 | return false; | ||||
16806 | |||||
16807 | // Note: The VTableUses vector could grow as a result of marking | ||||
16808 | // the members of a class as "used", so we check the size each | ||||
16809 | // time through the loop and prefer indices (which are stable) to | ||||
16810 | // iterators (which are not). | ||||
16811 | bool DefinedAnything = false; | ||||
16812 | for (unsigned I = 0; I != VTableUses.size(); ++I) { | ||||
16813 | CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); | ||||
16814 | if (!Class) | ||||
16815 | continue; | ||||
16816 | TemplateSpecializationKind ClassTSK = | ||||
16817 | Class->getTemplateSpecializationKind(); | ||||
16818 | |||||
16819 | SourceLocation Loc = VTableUses[I].second; | ||||
16820 | |||||
16821 | bool DefineVTable = true; | ||||
16822 | |||||
16823 | // If this class has a key function, but that key function is | ||||
16824 | // defined in another translation unit, we don't need to emit the | ||||
16825 | // vtable even though we're using it. | ||||
16826 | const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); | ||||
16827 | if (KeyFunction && !KeyFunction->hasBody()) { | ||||
16828 | // The key function is in another translation unit. | ||||
16829 | DefineVTable = false; | ||||
16830 | TemplateSpecializationKind TSK = | ||||
16831 | KeyFunction->getTemplateSpecializationKind(); | ||||
16832 | assert(TSK != TSK_ExplicitInstantiationDefinition &&((TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && "Instantiations don't have key functions" ) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 16834, __PRETTY_FUNCTION__)) | ||||
16833 | TSK != TSK_ImplicitInstantiation &&((TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && "Instantiations don't have key functions" ) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 16834, __PRETTY_FUNCTION__)) | ||||
16834 | "Instantiations don't have key functions")((TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && "Instantiations don't have key functions" ) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_ExplicitInstantiationDefinition && TSK != TSK_ImplicitInstantiation && \"Instantiations don't have key functions\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 16834, __PRETTY_FUNCTION__)); | ||||
16835 | (void)TSK; | ||||
16836 | } else if (!KeyFunction) { | ||||
16837 | // If we have a class with no key function that is the subject | ||||
16838 | // of an explicit instantiation declaration, suppress the | ||||
16839 | // vtable; it will live with the explicit instantiation | ||||
16840 | // definition. | ||||
16841 | bool IsExplicitInstantiationDeclaration = | ||||
16842 | ClassTSK == TSK_ExplicitInstantiationDeclaration; | ||||
16843 | for (auto R : Class->redecls()) { | ||||
16844 | TemplateSpecializationKind TSK | ||||
16845 | = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); | ||||
16846 | if (TSK == TSK_ExplicitInstantiationDeclaration) | ||||
16847 | IsExplicitInstantiationDeclaration = true; | ||||
16848 | else if (TSK == TSK_ExplicitInstantiationDefinition) { | ||||
16849 | IsExplicitInstantiationDeclaration = false; | ||||
16850 | break; | ||||
16851 | } | ||||
16852 | } | ||||
16853 | |||||
16854 | if (IsExplicitInstantiationDeclaration) | ||||
16855 | DefineVTable = false; | ||||
16856 | } | ||||
16857 | |||||
16858 | // The exception specifications for all virtual members may be needed even | ||||
16859 | // if we are not providing an authoritative form of the vtable in this TU. | ||||
16860 | // We may choose to emit it available_externally anyway. | ||||
16861 | if (!DefineVTable) { | ||||
16862 | MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); | ||||
16863 | continue; | ||||
16864 | } | ||||
16865 | |||||
16866 | // Mark all of the virtual members of this class as referenced, so | ||||
16867 | // that we can build a vtable. Then, tell the AST consumer that a | ||||
16868 | // vtable for this class is required. | ||||
16869 | DefinedAnything = true; | ||||
16870 | MarkVirtualMembersReferenced(Loc, Class); | ||||
16871 | CXXRecordDecl *Canonical = Class->getCanonicalDecl(); | ||||
16872 | if (VTablesUsed[Canonical]) | ||||
16873 | Consumer.HandleVTable(Class); | ||||
16874 | |||||
16875 | // Warn if we're emitting a weak vtable. The vtable will be weak if there is | ||||
16876 | // no key function or the key function is inlined. Don't warn in C++ ABIs | ||||
16877 | // that lack key functions, since the user won't be able to make one. | ||||
16878 | if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && | ||||
16879 | Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { | ||||
16880 | const FunctionDecl *KeyFunctionDef = nullptr; | ||||
16881 | if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && | ||||
16882 | KeyFunctionDef->isInlined())) { | ||||
16883 | Diag(Class->getLocation(), | ||||
16884 | ClassTSK == TSK_ExplicitInstantiationDefinition | ||||
16885 | ? diag::warn_weak_template_vtable | ||||
16886 | : diag::warn_weak_vtable) | ||||
16887 | << Class; | ||||
16888 | } | ||||
16889 | } | ||||
16890 | } | ||||
16891 | VTableUses.clear(); | ||||
16892 | |||||
16893 | return DefinedAnything; | ||||
16894 | } | ||||
16895 | |||||
16896 | void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, | ||||
16897 | const CXXRecordDecl *RD) { | ||||
16898 | for (const auto *I : RD->methods()) | ||||
16899 | if (I->isVirtual() && !I->isPure()) | ||||
16900 | ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); | ||||
16901 | } | ||||
16902 | |||||
16903 | void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, | ||||
16904 | const CXXRecordDecl *RD, | ||||
16905 | bool ConstexprOnly) { | ||||
16906 | // Mark all functions which will appear in RD's vtable as used. | ||||
16907 | CXXFinalOverriderMap FinalOverriders; | ||||
16908 | RD->getFinalOverriders(FinalOverriders); | ||||
16909 | for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), | ||||
16910 | E = FinalOverriders.end(); | ||||
16911 | I != E; ++I) { | ||||
16912 | for (OverridingMethods::const_iterator OI = I->second.begin(), | ||||
16913 | OE = I->second.end(); | ||||
16914 | OI != OE; ++OI) { | ||||
16915 | assert(OI->second.size() > 0 && "no final overrider")((OI->second.size() > 0 && "no final overrider" ) ? static_cast<void> (0) : __assert_fail ("OI->second.size() > 0 && \"no final overrider\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 16915, __PRETTY_FUNCTION__)); | ||||
16916 | CXXMethodDecl *Overrider = OI->second.front().Method; | ||||
16917 | |||||
16918 | // C++ [basic.def.odr]p2: | ||||
16919 | // [...] A virtual member function is used if it is not pure. [...] | ||||
16920 | if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) | ||||
16921 | MarkFunctionReferenced(Loc, Overrider); | ||||
16922 | } | ||||
16923 | } | ||||
16924 | |||||
16925 | // Only classes that have virtual bases need a VTT. | ||||
16926 | if (RD->getNumVBases() == 0) | ||||
16927 | return; | ||||
16928 | |||||
16929 | for (const auto &I : RD->bases()) { | ||||
16930 | const auto *Base = | ||||
16931 | cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); | ||||
16932 | if (Base->getNumVBases() == 0) | ||||
16933 | continue; | ||||
16934 | MarkVirtualMembersReferenced(Loc, Base); | ||||
16935 | } | ||||
16936 | } | ||||
16937 | |||||
16938 | /// SetIvarInitializers - This routine builds initialization ASTs for the | ||||
16939 | /// Objective-C implementation whose ivars need be initialized. | ||||
16940 | void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { | ||||
16941 | if (!getLangOpts().CPlusPlus) | ||||
16942 | return; | ||||
16943 | if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { | ||||
16944 | SmallVector<ObjCIvarDecl*, 8> ivars; | ||||
16945 | CollectIvarsToConstructOrDestruct(OID, ivars); | ||||
16946 | if (ivars.empty()) | ||||
16947 | return; | ||||
16948 | SmallVector<CXXCtorInitializer*, 32> AllToInit; | ||||
16949 | for (unsigned i = 0; i < ivars.size(); i++) { | ||||
16950 | FieldDecl *Field = ivars[i]; | ||||
16951 | if (Field->isInvalidDecl()) | ||||
16952 | continue; | ||||
16953 | |||||
16954 | CXXCtorInitializer *Member; | ||||
16955 | InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); | ||||
16956 | InitializationKind InitKind = | ||||
16957 | InitializationKind::CreateDefault(ObjCImplementation->getLocation()); | ||||
16958 | |||||
16959 | InitializationSequence InitSeq(*this, InitEntity, InitKind, None); | ||||
16960 | ExprResult MemberInit = | ||||
16961 | InitSeq.Perform(*this, InitEntity, InitKind, None); | ||||
16962 | MemberInit = MaybeCreateExprWithCleanups(MemberInit); | ||||
16963 | // Note, MemberInit could actually come back empty if no initialization | ||||
16964 | // is required (e.g., because it would call a trivial default constructor) | ||||
16965 | if (!MemberInit.get() || MemberInit.isInvalid()) | ||||
16966 | continue; | ||||
16967 | |||||
16968 | Member = | ||||
16969 | new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), | ||||
16970 | SourceLocation(), | ||||
16971 | MemberInit.getAs<Expr>(), | ||||
16972 | SourceLocation()); | ||||
16973 | AllToInit.push_back(Member); | ||||
16974 | |||||
16975 | // Be sure that the destructor is accessible and is marked as referenced. | ||||
16976 | if (const RecordType *RecordTy = | ||||
16977 | Context.getBaseElementType(Field->getType()) | ||||
16978 | ->getAs<RecordType>()) { | ||||
16979 | CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); | ||||
16980 | if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { | ||||
16981 | MarkFunctionReferenced(Field->getLocation(), Destructor); | ||||
16982 | CheckDestructorAccess(Field->getLocation(), Destructor, | ||||
16983 | PDiag(diag::err_access_dtor_ivar) | ||||
16984 | << Context.getBaseElementType(Field->getType())); | ||||
16985 | } | ||||
16986 | } | ||||
16987 | } | ||||
16988 | ObjCImplementation->setIvarInitializers(Context, | ||||
16989 | AllToInit.data(), AllToInit.size()); | ||||
16990 | } | ||||
16991 | } | ||||
16992 | |||||
16993 | static | ||||
16994 | void DelegatingCycleHelper(CXXConstructorDecl* Ctor, | ||||
16995 | llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, | ||||
16996 | llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, | ||||
16997 | llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, | ||||
16998 | Sema &S) { | ||||
16999 | if (Ctor->isInvalidDecl()) | ||||
17000 | return; | ||||
17001 | |||||
17002 | CXXConstructorDecl *Target = Ctor->getTargetConstructor(); | ||||
17003 | |||||
17004 | // Target may not be determinable yet, for instance if this is a dependent | ||||
17005 | // call in an uninstantiated template. | ||||
17006 | if (Target) { | ||||
17007 | const FunctionDecl *FNTarget = nullptr; | ||||
17008 | (void)Target->hasBody(FNTarget); | ||||
17009 | Target = const_cast<CXXConstructorDecl*>( | ||||
17010 | cast_or_null<CXXConstructorDecl>(FNTarget)); | ||||
17011 | } | ||||
17012 | |||||
17013 | CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), | ||||
17014 | // Avoid dereferencing a null pointer here. | ||||
17015 | *TCanonical = Target? Target->getCanonicalDecl() : nullptr; | ||||
17016 | |||||
17017 | if (!Current.insert(Canonical).second) | ||||
17018 | return; | ||||
17019 | |||||
17020 | // We know that beyond here, we aren't chaining into a cycle. | ||||
17021 | if (!Target || !Target->isDelegatingConstructor() || | ||||
17022 | Target->isInvalidDecl() || Valid.count(TCanonical)) { | ||||
17023 | Valid.insert(Current.begin(), Current.end()); | ||||
17024 | Current.clear(); | ||||
17025 | // We've hit a cycle. | ||||
17026 | } else if (TCanonical == Canonical || Invalid.count(TCanonical) || | ||||
17027 | Current.count(TCanonical)) { | ||||
17028 | // If we haven't diagnosed this cycle yet, do so now. | ||||
17029 | if (!Invalid.count(TCanonical)) { | ||||
17030 | S.Diag((*Ctor->init_begin())->getSourceLocation(), | ||||
17031 | diag::warn_delegating_ctor_cycle) | ||||
17032 | << Ctor; | ||||
17033 | |||||
17034 | // Don't add a note for a function delegating directly to itself. | ||||
17035 | if (TCanonical != Canonical) | ||||
17036 | S.Diag(Target->getLocation(), diag::note_it_delegates_to); | ||||
17037 | |||||
17038 | CXXConstructorDecl *C = Target; | ||||
17039 | while (C->getCanonicalDecl() != Canonical) { | ||||
17040 | const FunctionDecl *FNTarget = nullptr; | ||||
17041 | (void)C->getTargetConstructor()->hasBody(FNTarget); | ||||
17042 | assert(FNTarget && "Ctor cycle through bodiless function")((FNTarget && "Ctor cycle through bodiless function") ? static_cast<void> (0) : __assert_fail ("FNTarget && \"Ctor cycle through bodiless function\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 17042, __PRETTY_FUNCTION__)); | ||||
17043 | |||||
17044 | C = const_cast<CXXConstructorDecl*>( | ||||
17045 | cast<CXXConstructorDecl>(FNTarget)); | ||||
17046 | S.Diag(C->getLocation(), diag::note_which_delegates_to); | ||||
17047 | } | ||||
17048 | } | ||||
17049 | |||||
17050 | Invalid.insert(Current.begin(), Current.end()); | ||||
17051 | Current.clear(); | ||||
17052 | } else { | ||||
17053 | DelegatingCycleHelper(Target, Valid, Invalid, Current, S); | ||||
17054 | } | ||||
17055 | } | ||||
17056 | |||||
17057 | |||||
17058 | void Sema::CheckDelegatingCtorCycles() { | ||||
17059 | llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; | ||||
17060 | |||||
17061 | for (DelegatingCtorDeclsType::iterator | ||||
17062 | I = DelegatingCtorDecls.begin(ExternalSource), | ||||
17063 | E = DelegatingCtorDecls.end(); | ||||
17064 | I != E; ++I) | ||||
17065 | DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); | ||||
17066 | |||||
17067 | for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) | ||||
17068 | (*CI)->setInvalidDecl(); | ||||
17069 | } | ||||
17070 | |||||
17071 | namespace { | ||||
17072 | /// AST visitor that finds references to the 'this' expression. | ||||
17073 | class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { | ||||
17074 | Sema &S; | ||||
17075 | |||||
17076 | public: | ||||
17077 | explicit FindCXXThisExpr(Sema &S) : S(S) { } | ||||
17078 | |||||
17079 | bool VisitCXXThisExpr(CXXThisExpr *E) { | ||||
17080 | S.Diag(E->getLocation(), diag::err_this_static_member_func) | ||||
17081 | << E->isImplicit(); | ||||
17082 | return false; | ||||
17083 | } | ||||
17084 | }; | ||||
17085 | } | ||||
17086 | |||||
17087 | bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { | ||||
17088 | TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); | ||||
17089 | if (!TSInfo) | ||||
17090 | return false; | ||||
17091 | |||||
17092 | TypeLoc TL = TSInfo->getTypeLoc(); | ||||
17093 | FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); | ||||
17094 | if (!ProtoTL) | ||||
17095 | return false; | ||||
17096 | |||||
17097 | // C++11 [expr.prim.general]p3: | ||||
17098 | // [The expression this] shall not appear before the optional | ||||
17099 | // cv-qualifier-seq and it shall not appear within the declaration of a | ||||
17100 | // static member function (although its type and value category are defined | ||||
17101 | // within a static member function as they are within a non-static member | ||||
17102 | // function). [ Note: this is because declaration matching does not occur | ||||
17103 | // until the complete declarator is known. - end note ] | ||||
17104 | const FunctionProtoType *Proto = ProtoTL.getTypePtr(); | ||||
17105 | FindCXXThisExpr Finder(*this); | ||||
17106 | |||||
17107 | // If the return type came after the cv-qualifier-seq, check it now. | ||||
17108 | if (Proto->hasTrailingReturn() && | ||||
17109 | !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) | ||||
17110 | return true; | ||||
17111 | |||||
17112 | // Check the exception specification. | ||||
17113 | if (checkThisInStaticMemberFunctionExceptionSpec(Method)) | ||||
17114 | return true; | ||||
17115 | |||||
17116 | // Check the trailing requires clause | ||||
17117 | if (Expr *E = Method->getTrailingRequiresClause()) | ||||
17118 | if (!Finder.TraverseStmt(E)) | ||||
17119 | return true; | ||||
17120 | |||||
17121 | return checkThisInStaticMemberFunctionAttributes(Method); | ||||
17122 | } | ||||
17123 | |||||
17124 | bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { | ||||
17125 | TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); | ||||
17126 | if (!TSInfo) | ||||
17127 | return false; | ||||
17128 | |||||
17129 | TypeLoc TL = TSInfo->getTypeLoc(); | ||||
17130 | FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); | ||||
17131 | if (!ProtoTL) | ||||
17132 | return false; | ||||
17133 | |||||
17134 | const FunctionProtoType *Proto = ProtoTL.getTypePtr(); | ||||
17135 | FindCXXThisExpr Finder(*this); | ||||
17136 | |||||
17137 | switch (Proto->getExceptionSpecType()) { | ||||
17138 | case EST_Unparsed: | ||||
17139 | case EST_Uninstantiated: | ||||
17140 | case EST_Unevaluated: | ||||
17141 | case EST_BasicNoexcept: | ||||
17142 | case EST_NoThrow: | ||||
17143 | case EST_DynamicNone: | ||||
17144 | case EST_MSAny: | ||||
17145 | case EST_None: | ||||
17146 | break; | ||||
17147 | |||||
17148 | case EST_DependentNoexcept: | ||||
17149 | case EST_NoexceptFalse: | ||||
17150 | case EST_NoexceptTrue: | ||||
17151 | if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) | ||||
17152 | return true; | ||||
17153 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||
17154 | |||||
17155 | case EST_Dynamic: | ||||
17156 | for (const auto &E : Proto->exceptions()) { | ||||
17157 | if (!Finder.TraverseType(E)) | ||||
17158 | return true; | ||||
17159 | } | ||||
17160 | break; | ||||
17161 | } | ||||
17162 | |||||
17163 | return false; | ||||
17164 | } | ||||
17165 | |||||
17166 | bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { | ||||
17167 | FindCXXThisExpr Finder(*this); | ||||
17168 | |||||
17169 | // Check attributes. | ||||
17170 | for (const auto *A : Method->attrs()) { | ||||
17171 | // FIXME: This should be emitted by tblgen. | ||||
17172 | Expr *Arg = nullptr; | ||||
17173 | ArrayRef<Expr *> Args; | ||||
17174 | if (const auto *G = dyn_cast<GuardedByAttr>(A)) | ||||
17175 | Arg = G->getArg(); | ||||
17176 | else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) | ||||
17177 | Arg = G->getArg(); | ||||
17178 | else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) | ||||
17179 | Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); | ||||
17180 | else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) | ||||
17181 | Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); | ||||
17182 | else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { | ||||
17183 | Arg = ETLF->getSuccessValue(); | ||||
17184 | Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); | ||||
17185 | } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { | ||||
17186 | Arg = STLF->getSuccessValue(); | ||||
17187 | Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); | ||||
17188 | } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) | ||||
17189 | Arg = LR->getArg(); | ||||
17190 | else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) | ||||
17191 | Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); | ||||
17192 | else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) | ||||
17193 | Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); | ||||
17194 | else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) | ||||
17195 | Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); | ||||
17196 | else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) | ||||
17197 | Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); | ||||
17198 | else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) | ||||
17199 | Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); | ||||
17200 | |||||
17201 | if (Arg && !Finder.TraverseStmt(Arg)) | ||||
17202 | return true; | ||||
17203 | |||||
17204 | for (unsigned I = 0, N = Args.size(); I != N; ++I) { | ||||
17205 | if (!Finder.TraverseStmt(Args[I])) | ||||
17206 | return true; | ||||
17207 | } | ||||
17208 | } | ||||
17209 | |||||
17210 | return false; | ||||
17211 | } | ||||
17212 | |||||
17213 | void Sema::checkExceptionSpecification( | ||||
17214 | bool IsTopLevel, ExceptionSpecificationType EST, | ||||
17215 | ArrayRef<ParsedType> DynamicExceptions, | ||||
17216 | ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, | ||||
17217 | SmallVectorImpl<QualType> &Exceptions, | ||||
17218 | FunctionProtoType::ExceptionSpecInfo &ESI) { | ||||
17219 | Exceptions.clear(); | ||||
17220 | ESI.Type = EST; | ||||
17221 | if (EST == EST_Dynamic) { | ||||
17222 | Exceptions.reserve(DynamicExceptions.size()); | ||||
17223 | for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { | ||||
17224 | // FIXME: Preserve type source info. | ||||
17225 | QualType ET = GetTypeFromParser(DynamicExceptions[ei]); | ||||
17226 | |||||
17227 | if (IsTopLevel) { | ||||
17228 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; | ||||
17229 | collectUnexpandedParameterPacks(ET, Unexpanded); | ||||
17230 | if (!Unexpanded.empty()) { | ||||
17231 | DiagnoseUnexpandedParameterPacks( | ||||
17232 | DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, | ||||
17233 | Unexpanded); | ||||
17234 | continue; | ||||
17235 | } | ||||
17236 | } | ||||
17237 | |||||
17238 | // Check that the type is valid for an exception spec, and | ||||
17239 | // drop it if not. | ||||
17240 | if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) | ||||
17241 | Exceptions.push_back(ET); | ||||
17242 | } | ||||
17243 | ESI.Exceptions = Exceptions; | ||||
17244 | return; | ||||
17245 | } | ||||
17246 | |||||
17247 | if (isComputedNoexcept(EST)) { | ||||
17248 | assert((NoexceptExpr->isTypeDependent() ||(((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType ()->getCanonicalTypeUnqualified() == Context.BoolTy) && "Parser should have made sure that the expression is boolean" ) ? static_cast<void> (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 17251, __PRETTY_FUNCTION__)) | ||||
17249 | NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==(((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType ()->getCanonicalTypeUnqualified() == Context.BoolTy) && "Parser should have made sure that the expression is boolean" ) ? static_cast<void> (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 17251, __PRETTY_FUNCTION__)) | ||||
17250 | Context.BoolTy) &&(((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType ()->getCanonicalTypeUnqualified() == Context.BoolTy) && "Parser should have made sure that the expression is boolean" ) ? static_cast<void> (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 17251, __PRETTY_FUNCTION__)) | ||||
17251 | "Parser should have made sure that the expression is boolean")(((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType ()->getCanonicalTypeUnqualified() == Context.BoolTy) && "Parser should have made sure that the expression is boolean" ) ? static_cast<void> (0) : __assert_fail ("(NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == Context.BoolTy) && \"Parser should have made sure that the expression is boolean\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/Sema/SemaDeclCXX.cpp" , 17251, __PRETTY_FUNCTION__)); | ||||
17252 | if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { | ||||
17253 | ESI.Type = EST_BasicNoexcept; | ||||
17254 | return; | ||||
17255 | } | ||||
17256 | |||||
17257 | ESI.NoexceptExpr = NoexceptExpr; | ||||
17258 | return; | ||||
17259 | } | ||||
17260 | } | ||||
17261 | |||||
17262 | void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, | ||||
17263 | ExceptionSpecificationType EST, | ||||
17264 | SourceRange SpecificationRange, | ||||
17265 | ArrayRef<ParsedType> DynamicExceptions, | ||||
17266 | ArrayRef<SourceRange> DynamicExceptionRanges, | ||||
17267 | Expr *NoexceptExpr) { | ||||
17268 | if (!MethodD) | ||||
17269 | return; | ||||
17270 | |||||
17271 | // Dig out the method we're referring to. | ||||
17272 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) | ||||
17273 | MethodD = FunTmpl->getTemplatedDecl(); | ||||
17274 | |||||
17275 | CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); | ||||
17276 | if (!Method) | ||||
17277 | return; | ||||
17278 | |||||
17279 | // Check the exception specification. | ||||
17280 | llvm::SmallVector<QualType, 4> Exceptions; | ||||
17281 | FunctionProtoType::ExceptionSpecInfo ESI; | ||||
17282 | checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, | ||||
17283 | DynamicExceptionRanges, NoexceptExpr, Exceptions, | ||||
17284 | ESI); | ||||
17285 | |||||
17286 | // Update the exception specification on the function type. | ||||
17287 | Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); | ||||
17288 | |||||
17289 | if (Method->isStatic()) | ||||
17290 | checkThisInStaticMemberFunctionExceptionSpec(Method); | ||||
17291 | |||||
17292 | if (Method->isVirtual()) { | ||||
17293 | // Check overrides, which we previously had to delay. | ||||
17294 | for (const CXXMethodDecl *O : Method->overridden_methods()) | ||||
17295 | CheckOverridingFunctionExceptionSpec(Method, O); | ||||
17296 | } | ||||
17297 | } | ||||
17298 | |||||
17299 | /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. | ||||
17300 | /// | ||||
17301 | MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, | ||||
17302 | SourceLocation DeclStart, Declarator &D, | ||||
17303 | Expr *BitWidth, | ||||
17304 | InClassInitStyle InitStyle, | ||||
17305 | AccessSpecifier AS, | ||||
17306 | const ParsedAttr &MSPropertyAttr) { | ||||
17307 | IdentifierInfo *II = D.getIdentifier(); | ||||
17308 | if (!II) { | ||||
17309 | Diag(DeclStart, diag::err_anonymous_property); | ||||
17310 | return nullptr; | ||||
17311 | } | ||||
17312 | SourceLocation Loc = D.getIdentifierLoc(); | ||||
17313 | |||||
17314 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||
17315 | QualType T = TInfo->getType(); | ||||
17316 | if (getLangOpts().CPlusPlus) { | ||||
17317 | CheckExtraCXXDefaultArguments(D); | ||||
17318 | |||||
17319 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | ||||
17320 | UPPC_DataMemberType)) { | ||||
17321 | D.setInvalidType(); | ||||
17322 | T = Context.IntTy; | ||||
17323 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc); | ||||
17324 | } | ||||
17325 | } | ||||
17326 | |||||
17327 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | ||||
17328 | |||||
17329 | if (D.getDeclSpec().isInlineSpecified()) | ||||
17330 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | ||||
17331 | << getLangOpts().CPlusPlus17; | ||||
17332 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | ||||
17333 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||
17334 | diag::err_invalid_thread) | ||||
17335 | << DeclSpec::getSpecifierName(TSCS); | ||||
17336 | |||||
17337 | // Check to see if this name was declared as a member previously | ||||
17338 | NamedDecl *PrevDecl = nullptr; | ||||
17339 | LookupResult Previous(*this, II, Loc, LookupMemberName, | ||||
17340 | ForVisibleRedeclaration); | ||||
17341 | LookupName(Previous, S); | ||||
17342 | switch (Previous.getResultKind()) { | ||||
17343 | case LookupResult::Found: | ||||
17344 | case LookupResult::FoundUnresolvedValue: | ||||
17345 | PrevDecl = Previous.getAsSingle<NamedDecl>(); | ||||
17346 | break; | ||||
17347 | |||||
17348 | case LookupResult::FoundOverloaded: | ||||
17349 | PrevDecl = Previous.getRepresentativeDecl(); | ||||
17350 | break; | ||||
17351 | |||||
17352 | case LookupResult::NotFound: | ||||
17353 | case LookupResult::NotFoundInCurrentInstantiation: | ||||
17354 | case LookupResult::Ambiguous: | ||||
17355 | break; | ||||
17356 | } | ||||
17357 | |||||
17358 | if (PrevDecl && PrevDecl->isTemplateParameter()) { | ||||
17359 | // Maybe we will complain about the shadowed template parameter. | ||||
17360 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | ||||
17361 | // Just pretend that we didn't see the previous declaration. | ||||
17362 | PrevDecl = nullptr; | ||||
17363 | } | ||||
17364 | |||||
17365 | if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) | ||||
17366 | PrevDecl = nullptr; | ||||
17367 | |||||
17368 | SourceLocation TSSL = D.getBeginLoc(); | ||||
17369 | MSPropertyDecl *NewPD = | ||||
17370 | MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, | ||||
17371 | MSPropertyAttr.getPropertyDataGetter(), | ||||
17372 | MSPropertyAttr.getPropertyDataSetter()); | ||||
17373 | ProcessDeclAttributes(TUScope, NewPD, D); | ||||
17374 | NewPD->setAccess(AS); | ||||
17375 | |||||
17376 | if (NewPD->isInvalidDecl()) | ||||
17377 | Record->setInvalidDecl(); | ||||
17378 | |||||
17379 | if (D.getDeclSpec().isModulePrivateSpecified()) | ||||
17380 | NewPD->setModulePrivate(); | ||||
17381 | |||||
17382 | if (NewPD->isInvalidDecl() && PrevDecl) { | ||||
17383 | // Don't introduce NewFD into scope; there's already something | ||||
17384 | // with the same name in the same scope. | ||||
17385 | } else if (II) { | ||||
17386 | PushOnScopeChains(NewPD, S); | ||||
17387 | } else | ||||
17388 | Record->addDecl(NewPD); | ||||
17389 | |||||
17390 | return NewPD; | ||||
17391 | } |
1 | //===--- DeclSpec.h - Parsed declaration specifiers -------------*- C++ -*-===// |
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 | /// \file |
10 | /// This file defines the classes used to store parsed information about |
11 | /// declaration-specifiers and declarators. |
12 | /// |
13 | /// \verbatim |
14 | /// static const int volatile x, *y, *(*(*z)[10])(const void *x); |
15 | /// ------------------------- - -- --------------------------- |
16 | /// declaration-specifiers \ | / |
17 | /// declarators |
18 | /// \endverbatim |
19 | /// |
20 | //===----------------------------------------------------------------------===// |
21 | |
22 | #ifndef LLVM_CLANG_SEMA_DECLSPEC_H |
23 | #define LLVM_CLANG_SEMA_DECLSPEC_H |
24 | |
25 | #include "clang/AST/DeclCXX.h" |
26 | #include "clang/AST/NestedNameSpecifier.h" |
27 | #include "clang/Basic/ExceptionSpecificationType.h" |
28 | #include "clang/Basic/Lambda.h" |
29 | #include "clang/Basic/OperatorKinds.h" |
30 | #include "clang/Basic/Specifiers.h" |
31 | #include "clang/Lex/Token.h" |
32 | #include "clang/Sema/Ownership.h" |
33 | #include "clang/Sema/ParsedAttr.h" |
34 | #include "llvm/ADT/SmallVector.h" |
35 | #include "llvm/Support/Compiler.h" |
36 | #include "llvm/Support/ErrorHandling.h" |
37 | |
38 | namespace clang { |
39 | class ASTContext; |
40 | class CXXRecordDecl; |
41 | class TypeLoc; |
42 | class LangOptions; |
43 | class IdentifierInfo; |
44 | class NamespaceAliasDecl; |
45 | class NamespaceDecl; |
46 | class ObjCDeclSpec; |
47 | class Sema; |
48 | class Declarator; |
49 | struct TemplateIdAnnotation; |
50 | |
51 | /// Represents a C++ nested-name-specifier or a global scope specifier. |
52 | /// |
53 | /// These can be in 3 states: |
54 | /// 1) Not present, identified by isEmpty() |
55 | /// 2) Present, identified by isNotEmpty() |
56 | /// 2.a) Valid, identified by isValid() |
57 | /// 2.b) Invalid, identified by isInvalid(). |
58 | /// |
59 | /// isSet() is deprecated because it mostly corresponded to "valid" but was |
60 | /// often used as if it meant "present". |
61 | /// |
62 | /// The actual scope is described by getScopeRep(). |
63 | class CXXScopeSpec { |
64 | SourceRange Range; |
65 | NestedNameSpecifierLocBuilder Builder; |
66 | |
67 | public: |
68 | SourceRange getRange() const { return Range; } |
69 | void setRange(SourceRange R) { Range = R; } |
70 | void setBeginLoc(SourceLocation Loc) { Range.setBegin(Loc); } |
71 | void setEndLoc(SourceLocation Loc) { Range.setEnd(Loc); } |
72 | SourceLocation getBeginLoc() const { return Range.getBegin(); } |
73 | SourceLocation getEndLoc() const { return Range.getEnd(); } |
74 | |
75 | /// Retrieve the representation of the nested-name-specifier. |
76 | NestedNameSpecifier *getScopeRep() const { |
77 | return Builder.getRepresentation(); |
78 | } |
79 | |
80 | /// Extend the current nested-name-specifier by another |
81 | /// nested-name-specifier component of the form 'type::'. |
82 | /// |
83 | /// \param Context The AST context in which this nested-name-specifier |
84 | /// resides. |
85 | /// |
86 | /// \param TemplateKWLoc The location of the 'template' keyword, if present. |
87 | /// |
88 | /// \param TL The TypeLoc that describes the type preceding the '::'. |
89 | /// |
90 | /// \param ColonColonLoc The location of the trailing '::'. |
91 | void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL, |
92 | SourceLocation ColonColonLoc); |
93 | |
94 | /// Extend the current nested-name-specifier by another |
95 | /// nested-name-specifier component of the form 'identifier::'. |
96 | /// |
97 | /// \param Context The AST context in which this nested-name-specifier |
98 | /// resides. |
99 | /// |
100 | /// \param Identifier The identifier. |
101 | /// |
102 | /// \param IdentifierLoc The location of the identifier. |
103 | /// |
104 | /// \param ColonColonLoc The location of the trailing '::'. |
105 | void Extend(ASTContext &Context, IdentifierInfo *Identifier, |
106 | SourceLocation IdentifierLoc, SourceLocation ColonColonLoc); |
107 | |
108 | /// Extend the current nested-name-specifier by another |
109 | /// nested-name-specifier component of the form 'namespace::'. |
110 | /// |
111 | /// \param Context The AST context in which this nested-name-specifier |
112 | /// resides. |
113 | /// |
114 | /// \param Namespace The namespace. |
115 | /// |
116 | /// \param NamespaceLoc The location of the namespace name. |
117 | /// |
118 | /// \param ColonColonLoc The location of the trailing '::'. |
119 | void Extend(ASTContext &Context, NamespaceDecl *Namespace, |
120 | SourceLocation NamespaceLoc, SourceLocation ColonColonLoc); |
121 | |
122 | /// Extend the current nested-name-specifier by another |
123 | /// nested-name-specifier component of the form 'namespace-alias::'. |
124 | /// |
125 | /// \param Context The AST context in which this nested-name-specifier |
126 | /// resides. |
127 | /// |
128 | /// \param Alias The namespace alias. |
129 | /// |
130 | /// \param AliasLoc The location of the namespace alias |
131 | /// name. |
132 | /// |
133 | /// \param ColonColonLoc The location of the trailing '::'. |
134 | void Extend(ASTContext &Context, NamespaceAliasDecl *Alias, |
135 | SourceLocation AliasLoc, SourceLocation ColonColonLoc); |
136 | |
137 | /// Turn this (empty) nested-name-specifier into the global |
138 | /// nested-name-specifier '::'. |
139 | void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc); |
140 | |
141 | /// Turns this (empty) nested-name-specifier into '__super' |
142 | /// nested-name-specifier. |
143 | /// |
144 | /// \param Context The AST context in which this nested-name-specifier |
145 | /// resides. |
146 | /// |
147 | /// \param RD The declaration of the class in which nested-name-specifier |
148 | /// appeared. |
149 | /// |
150 | /// \param SuperLoc The location of the '__super' keyword. |
151 | /// name. |
152 | /// |
153 | /// \param ColonColonLoc The location of the trailing '::'. |
154 | void MakeSuper(ASTContext &Context, CXXRecordDecl *RD, |
155 | SourceLocation SuperLoc, SourceLocation ColonColonLoc); |
156 | |
157 | /// Make a new nested-name-specifier from incomplete source-location |
158 | /// information. |
159 | /// |
160 | /// FIXME: This routine should be used very, very rarely, in cases where we |
161 | /// need to synthesize a nested-name-specifier. Most code should instead use |
162 | /// \c Adopt() with a proper \c NestedNameSpecifierLoc. |
163 | void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, |
164 | SourceRange R); |
165 | |
166 | /// Adopt an existing nested-name-specifier (with source-range |
167 | /// information). |
168 | void Adopt(NestedNameSpecifierLoc Other); |
169 | |
170 | /// Retrieve a nested-name-specifier with location information, copied |
171 | /// into the given AST context. |
172 | /// |
173 | /// \param Context The context into which this nested-name-specifier will be |
174 | /// copied. |
175 | NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const; |
176 | |
177 | /// Retrieve the location of the name in the last qualifier |
178 | /// in this nested name specifier. |
179 | /// |
180 | /// For example, the location of \c bar |
181 | /// in |
182 | /// \verbatim |
183 | /// \::foo::bar<0>:: |
184 | /// ^~~ |
185 | /// \endverbatim |
186 | SourceLocation getLastQualifierNameLoc() const; |
187 | |
188 | /// No scope specifier. |
189 | bool isEmpty() const { return !Range.isValid(); } |
190 | /// A scope specifier is present, but may be valid or invalid. |
191 | bool isNotEmpty() const { return !isEmpty(); } |
192 | |
193 | /// An error occurred during parsing of the scope specifier. |
194 | bool isInvalid() const { return isNotEmpty() && getScopeRep() == nullptr; } |
195 | /// A scope specifier is present, and it refers to a real scope. |
196 | bool isValid() const { return isNotEmpty() && getScopeRep() != nullptr; } |
197 | |
198 | /// Indicate that this nested-name-specifier is invalid. |
199 | void SetInvalid(SourceRange R) { |
200 | assert(R.isValid() && "Must have a valid source range")((R.isValid() && "Must have a valid source range") ? static_cast <void> (0) : __assert_fail ("R.isValid() && \"Must have a valid source range\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 200, __PRETTY_FUNCTION__)); |
201 | if (Range.getBegin().isInvalid()) |
202 | Range.setBegin(R.getBegin()); |
203 | Range.setEnd(R.getEnd()); |
204 | Builder.Clear(); |
205 | } |
206 | |
207 | /// Deprecated. Some call sites intend isNotEmpty() while others intend |
208 | /// isValid(). |
209 | bool isSet() const { return getScopeRep() != nullptr; } |
210 | |
211 | void clear() { |
212 | Range = SourceRange(); |
213 | Builder.Clear(); |
214 | } |
215 | |
216 | /// Retrieve the data associated with the source-location information. |
217 | char *location_data() const { return Builder.getBuffer().first; } |
218 | |
219 | /// Retrieve the size of the data associated with source-location |
220 | /// information. |
221 | unsigned location_size() const { return Builder.getBuffer().second; } |
222 | }; |
223 | |
224 | /// Captures information about "declaration specifiers". |
225 | /// |
226 | /// "Declaration specifiers" encompasses storage-class-specifiers, |
227 | /// type-specifiers, type-qualifiers, and function-specifiers. |
228 | class DeclSpec { |
229 | public: |
230 | /// storage-class-specifier |
231 | /// \note The order of these enumerators is important for diagnostics. |
232 | enum SCS { |
233 | SCS_unspecified = 0, |
234 | SCS_typedef, |
235 | SCS_extern, |
236 | SCS_static, |
237 | SCS_auto, |
238 | SCS_register, |
239 | SCS_private_extern, |
240 | SCS_mutable |
241 | }; |
242 | |
243 | // Import thread storage class specifier enumeration and constants. |
244 | // These can be combined with SCS_extern and SCS_static. |
245 | typedef ThreadStorageClassSpecifier TSCS; |
246 | static const TSCS TSCS_unspecified = clang::TSCS_unspecified; |
247 | static const TSCS TSCS___thread = clang::TSCS___thread; |
248 | static const TSCS TSCS_thread_local = clang::TSCS_thread_local; |
249 | static const TSCS TSCS__Thread_local = clang::TSCS__Thread_local; |
250 | |
251 | // Import type specifier width enumeration and constants. |
252 | typedef TypeSpecifierWidth TSW; |
253 | static const TSW TSW_unspecified = clang::TSW_unspecified; |
254 | static const TSW TSW_short = clang::TSW_short; |
255 | static const TSW TSW_long = clang::TSW_long; |
256 | static const TSW TSW_longlong = clang::TSW_longlong; |
257 | |
258 | enum TSC { |
259 | TSC_unspecified, |
260 | TSC_imaginary, |
261 | TSC_complex |
262 | }; |
263 | |
264 | // Import type specifier sign enumeration and constants. |
265 | typedef TypeSpecifierSign TSS; |
266 | static const TSS TSS_unspecified = clang::TSS_unspecified; |
267 | static const TSS TSS_signed = clang::TSS_signed; |
268 | static const TSS TSS_unsigned = clang::TSS_unsigned; |
269 | |
270 | // Import type specifier type enumeration and constants. |
271 | typedef TypeSpecifierType TST; |
272 | static const TST TST_unspecified = clang::TST_unspecified; |
273 | static const TST TST_void = clang::TST_void; |
274 | static const TST TST_char = clang::TST_char; |
275 | static const TST TST_wchar = clang::TST_wchar; |
276 | static const TST TST_char8 = clang::TST_char8; |
277 | static const TST TST_char16 = clang::TST_char16; |
278 | static const TST TST_char32 = clang::TST_char32; |
279 | static const TST TST_int = clang::TST_int; |
280 | static const TST TST_int128 = clang::TST_int128; |
281 | static const TST TST_half = clang::TST_half; |
282 | static const TST TST_float = clang::TST_float; |
283 | static const TST TST_double = clang::TST_double; |
284 | static const TST TST_float16 = clang::TST_Float16; |
285 | static const TST TST_accum = clang::TST_Accum; |
286 | static const TST TST_fract = clang::TST_Fract; |
287 | static const TST TST_float128 = clang::TST_float128; |
288 | static const TST TST_bool = clang::TST_bool; |
289 | static const TST TST_decimal32 = clang::TST_decimal32; |
290 | static const TST TST_decimal64 = clang::TST_decimal64; |
291 | static const TST TST_decimal128 = clang::TST_decimal128; |
292 | static const TST TST_enum = clang::TST_enum; |
293 | static const TST TST_union = clang::TST_union; |
294 | static const TST TST_struct = clang::TST_struct; |
295 | static const TST TST_interface = clang::TST_interface; |
296 | static const TST TST_class = clang::TST_class; |
297 | static const TST TST_typename = clang::TST_typename; |
298 | static const TST TST_typeofType = clang::TST_typeofType; |
299 | static const TST TST_typeofExpr = clang::TST_typeofExpr; |
300 | static const TST TST_decltype = clang::TST_decltype; |
301 | static const TST TST_decltype_auto = clang::TST_decltype_auto; |
302 | static const TST TST_underlyingType = clang::TST_underlyingType; |
303 | static const TST TST_auto = clang::TST_auto; |
304 | static const TST TST_auto_type = clang::TST_auto_type; |
305 | static const TST TST_unknown_anytype = clang::TST_unknown_anytype; |
306 | static const TST TST_atomic = clang::TST_atomic; |
307 | #define GENERIC_IMAGE_TYPE(ImgType, Id) \ |
308 | static const TST TST_##ImgType##_t = clang::TST_##ImgType##_t; |
309 | #include "clang/Basic/OpenCLImageTypes.def" |
310 | static const TST TST_error = clang::TST_error; |
311 | |
312 | // type-qualifiers |
313 | enum TQ { // NOTE: These flags must be kept in sync with Qualifiers::TQ. |
314 | TQ_unspecified = 0, |
315 | TQ_const = 1, |
316 | TQ_restrict = 2, |
317 | TQ_volatile = 4, |
318 | TQ_unaligned = 8, |
319 | // This has no corresponding Qualifiers::TQ value, because it's not treated |
320 | // as a qualifier in our type system. |
321 | TQ_atomic = 16 |
322 | }; |
323 | |
324 | /// ParsedSpecifiers - Flags to query which specifiers were applied. This is |
325 | /// returned by getParsedSpecifiers. |
326 | enum ParsedSpecifiers { |
327 | PQ_None = 0, |
328 | PQ_StorageClassSpecifier = 1, |
329 | PQ_TypeSpecifier = 2, |
330 | PQ_TypeQualifier = 4, |
331 | PQ_FunctionSpecifier = 8 |
332 | // FIXME: Attributes should be included here. |
333 | }; |
334 | |
335 | private: |
336 | // storage-class-specifier |
337 | /*SCS*/unsigned StorageClassSpec : 3; |
338 | /*TSCS*/unsigned ThreadStorageClassSpec : 2; |
339 | unsigned SCS_extern_in_linkage_spec : 1; |
340 | |
341 | // type-specifier |
342 | /*TSW*/unsigned TypeSpecWidth : 2; |
343 | /*TSC*/unsigned TypeSpecComplex : 2; |
344 | /*TSS*/unsigned TypeSpecSign : 2; |
345 | /*TST*/unsigned TypeSpecType : 6; |
346 | unsigned TypeAltiVecVector : 1; |
347 | unsigned TypeAltiVecPixel : 1; |
348 | unsigned TypeAltiVecBool : 1; |
349 | unsigned TypeSpecOwned : 1; |
350 | unsigned TypeSpecPipe : 1; |
351 | unsigned TypeSpecSat : 1; |
352 | |
353 | // type-qualifiers |
354 | unsigned TypeQualifiers : 5; // Bitwise OR of TQ. |
355 | |
356 | // function-specifier |
357 | unsigned FS_inline_specified : 1; |
358 | unsigned FS_forceinline_specified: 1; |
359 | unsigned FS_virtual_specified : 1; |
360 | unsigned FS_noreturn_specified : 1; |
361 | |
362 | // friend-specifier |
363 | unsigned Friend_specified : 1; |
364 | |
365 | // constexpr-specifier |
366 | unsigned ConstexprSpecifier : 2; |
367 | |
368 | union { |
369 | UnionParsedType TypeRep; |
370 | Decl *DeclRep; |
371 | Expr *ExprRep; |
372 | }; |
373 | |
374 | /// ExplicitSpecifier - Store information about explicit spicifer. |
375 | ExplicitSpecifier FS_explicit_specifier; |
376 | |
377 | // attributes. |
378 | ParsedAttributes Attrs; |
379 | |
380 | // Scope specifier for the type spec, if applicable. |
381 | CXXScopeSpec TypeScope; |
382 | |
383 | // SourceLocation info. These are null if the item wasn't specified or if |
384 | // the setting was synthesized. |
385 | SourceRange Range; |
386 | |
387 | SourceLocation StorageClassSpecLoc, ThreadStorageClassSpecLoc; |
388 | SourceRange TSWRange; |
389 | SourceLocation TSCLoc, TSSLoc, TSTLoc, AltiVecLoc, TSSatLoc; |
390 | /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union, |
391 | /// typename, then this is the location of the named type (if present); |
392 | /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and |
393 | /// TSTNameLoc provides source range info for tag types. |
394 | SourceLocation TSTNameLoc; |
395 | SourceRange TypeofParensRange; |
396 | SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc, TQ_atomicLoc, |
397 | TQ_unalignedLoc; |
398 | SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc, FS_noreturnLoc; |
399 | SourceLocation FS_explicitCloseParenLoc; |
400 | SourceLocation FS_forceinlineLoc; |
401 | SourceLocation FriendLoc, ModulePrivateLoc, ConstexprLoc; |
402 | SourceLocation TQ_pipeLoc; |
403 | |
404 | WrittenBuiltinSpecs writtenBS; |
405 | void SaveWrittenBuiltinSpecs(); |
406 | |
407 | ObjCDeclSpec *ObjCQualifiers; |
408 | |
409 | static bool isTypeRep(TST T) { |
410 | return (T == TST_typename || T == TST_typeofType || |
411 | T == TST_underlyingType || T == TST_atomic); |
412 | } |
413 | static bool isExprRep(TST T) { |
414 | return (T == TST_typeofExpr || T == TST_decltype); |
415 | } |
416 | |
417 | DeclSpec(const DeclSpec &) = delete; |
418 | void operator=(const DeclSpec &) = delete; |
419 | public: |
420 | static bool isDeclRep(TST T) { |
421 | return (T == TST_enum || T == TST_struct || |
422 | T == TST_interface || T == TST_union || |
423 | T == TST_class); |
424 | } |
425 | |
426 | DeclSpec(AttributeFactory &attrFactory) |
427 | : StorageClassSpec(SCS_unspecified), |
428 | ThreadStorageClassSpec(TSCS_unspecified), |
429 | SCS_extern_in_linkage_spec(false), TypeSpecWidth(TSW_unspecified), |
430 | TypeSpecComplex(TSC_unspecified), TypeSpecSign(TSS_unspecified), |
431 | TypeSpecType(TST_unspecified), TypeAltiVecVector(false), |
432 | TypeAltiVecPixel(false), TypeAltiVecBool(false), TypeSpecOwned(false), |
433 | TypeSpecPipe(false), TypeSpecSat(false), TypeQualifiers(TQ_unspecified), |
434 | FS_inline_specified(false), FS_forceinline_specified(false), |
435 | FS_virtual_specified(false), FS_noreturn_specified(false), |
436 | Friend_specified(false), ConstexprSpecifier(CSK_unspecified), |
437 | FS_explicit_specifier(), Attrs(attrFactory), writtenBS(), |
438 | ObjCQualifiers(nullptr) {} |
439 | |
440 | // storage-class-specifier |
441 | SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; } |
442 | TSCS getThreadStorageClassSpec() const { |
443 | return (TSCS)ThreadStorageClassSpec; |
444 | } |
445 | bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; } |
446 | void setExternInLinkageSpec(bool Value) { |
447 | SCS_extern_in_linkage_spec = Value; |
448 | } |
449 | |
450 | SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; } |
451 | SourceLocation getThreadStorageClassSpecLoc() const { |
452 | return ThreadStorageClassSpecLoc; |
453 | } |
454 | |
455 | void ClearStorageClassSpecs() { |
456 | StorageClassSpec = DeclSpec::SCS_unspecified; |
457 | ThreadStorageClassSpec = DeclSpec::TSCS_unspecified; |
458 | SCS_extern_in_linkage_spec = false; |
459 | StorageClassSpecLoc = SourceLocation(); |
460 | ThreadStorageClassSpecLoc = SourceLocation(); |
461 | } |
462 | |
463 | void ClearTypeSpecType() { |
464 | TypeSpecType = DeclSpec::TST_unspecified; |
465 | TypeSpecOwned = false; |
466 | TSTLoc = SourceLocation(); |
467 | } |
468 | |
469 | // type-specifier |
470 | TSW getTypeSpecWidth() const { return (TSW)TypeSpecWidth; } |
471 | TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; } |
472 | TSS getTypeSpecSign() const { return (TSS)TypeSpecSign; } |
473 | TST getTypeSpecType() const { return (TST)TypeSpecType; } |
474 | bool isTypeAltiVecVector() const { return TypeAltiVecVector; } |
475 | bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; } |
476 | bool isTypeAltiVecBool() const { return TypeAltiVecBool; } |
477 | bool isTypeSpecOwned() const { return TypeSpecOwned; } |
478 | bool isTypeRep() const { return isTypeRep((TST) TypeSpecType); } |
479 | bool isTypeSpecPipe() const { return TypeSpecPipe; } |
480 | bool isTypeSpecSat() const { return TypeSpecSat; } |
481 | |
482 | ParsedType getRepAsType() const { |
483 | assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type")((isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type" ) ? static_cast<void> (0) : __assert_fail ("isTypeRep((TST) TypeSpecType) && \"DeclSpec does not store a type\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 483, __PRETTY_FUNCTION__)); |
484 | return TypeRep; |
485 | } |
486 | Decl *getRepAsDecl() const { |
487 | assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl")((isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl" ) ? static_cast<void> (0) : __assert_fail ("isDeclRep((TST) TypeSpecType) && \"DeclSpec does not store a decl\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 487, __PRETTY_FUNCTION__)); |
488 | return DeclRep; |
489 | } |
490 | Expr *getRepAsExpr() const { |
491 | assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr")((isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr" ) ? static_cast<void> (0) : __assert_fail ("isExprRep((TST) TypeSpecType) && \"DeclSpec does not store an expr\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 491, __PRETTY_FUNCTION__)); |
492 | return ExprRep; |
493 | } |
494 | CXXScopeSpec &getTypeSpecScope() { return TypeScope; } |
495 | const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; } |
496 | |
497 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; } |
498 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); } |
499 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); } |
500 | |
501 | SourceLocation getTypeSpecWidthLoc() const { return TSWRange.getBegin(); } |
502 | SourceRange getTypeSpecWidthRange() const { return TSWRange; } |
503 | SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; } |
504 | SourceLocation getTypeSpecSignLoc() const { return TSSLoc; } |
505 | SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; } |
506 | SourceLocation getAltiVecLoc() const { return AltiVecLoc; } |
507 | SourceLocation getTypeSpecSatLoc() const { return TSSatLoc; } |
508 | |
509 | SourceLocation getTypeSpecTypeNameLoc() const { |
510 | assert(isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename)((isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename ) ? static_cast<void> (0) : __assert_fail ("isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 510, __PRETTY_FUNCTION__)); |
511 | return TSTNameLoc; |
512 | } |
513 | |
514 | SourceRange getTypeofParensRange() const { return TypeofParensRange; } |
515 | void setTypeofParensRange(SourceRange range) { TypeofParensRange = range; } |
516 | |
517 | bool hasAutoTypeSpec() const { |
518 | return (TypeSpecType == TST_auto || TypeSpecType == TST_auto_type || |
519 | TypeSpecType == TST_decltype_auto); |
520 | } |
521 | |
522 | bool hasTagDefinition() const; |
523 | |
524 | /// Turn a type-specifier-type into a string like "_Bool" or "union". |
525 | static const char *getSpecifierName(DeclSpec::TST T, |
526 | const PrintingPolicy &Policy); |
527 | static const char *getSpecifierName(DeclSpec::TQ Q); |
528 | static const char *getSpecifierName(DeclSpec::TSS S); |
529 | static const char *getSpecifierName(DeclSpec::TSC C); |
530 | static const char *getSpecifierName(DeclSpec::TSW W); |
531 | static const char *getSpecifierName(DeclSpec::SCS S); |
532 | static const char *getSpecifierName(DeclSpec::TSCS S); |
533 | static const char *getSpecifierName(ConstexprSpecKind C); |
534 | |
535 | // type-qualifiers |
536 | |
537 | /// getTypeQualifiers - Return a set of TQs. |
538 | unsigned getTypeQualifiers() const { return TypeQualifiers; } |
539 | SourceLocation getConstSpecLoc() const { return TQ_constLoc; } |
540 | SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; } |
541 | SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; } |
542 | SourceLocation getAtomicSpecLoc() const { return TQ_atomicLoc; } |
543 | SourceLocation getUnalignedSpecLoc() const { return TQ_unalignedLoc; } |
544 | SourceLocation getPipeLoc() const { return TQ_pipeLoc; } |
545 | |
546 | /// Clear out all of the type qualifiers. |
547 | void ClearTypeQualifiers() { |
548 | TypeQualifiers = 0; |
549 | TQ_constLoc = SourceLocation(); |
550 | TQ_restrictLoc = SourceLocation(); |
551 | TQ_volatileLoc = SourceLocation(); |
552 | TQ_atomicLoc = SourceLocation(); |
553 | TQ_unalignedLoc = SourceLocation(); |
554 | TQ_pipeLoc = SourceLocation(); |
555 | } |
556 | |
557 | // function-specifier |
558 | bool isInlineSpecified() const { |
559 | return FS_inline_specified | FS_forceinline_specified; |
560 | } |
561 | SourceLocation getInlineSpecLoc() const { |
562 | return FS_inline_specified ? FS_inlineLoc : FS_forceinlineLoc; |
563 | } |
564 | |
565 | ExplicitSpecifier getExplicitSpecifier() const { |
566 | return FS_explicit_specifier; |
567 | } |
568 | |
569 | bool isVirtualSpecified() const { return FS_virtual_specified; } |
570 | SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; } |
571 | |
572 | bool hasExplicitSpecifier() const { |
573 | return FS_explicit_specifier.isSpecified(); |
574 | } |
575 | SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; } |
576 | SourceRange getExplicitSpecRange() const { |
577 | return FS_explicit_specifier.getExpr() |
578 | ? SourceRange(FS_explicitLoc, FS_explicitCloseParenLoc) |
579 | : SourceRange(FS_explicitLoc); |
580 | } |
581 | |
582 | bool isNoreturnSpecified() const { return FS_noreturn_specified; } |
583 | SourceLocation getNoreturnSpecLoc() const { return FS_noreturnLoc; } |
584 | |
585 | void ClearFunctionSpecs() { |
586 | FS_inline_specified = false; |
587 | FS_inlineLoc = SourceLocation(); |
588 | FS_forceinline_specified = false; |
589 | FS_forceinlineLoc = SourceLocation(); |
590 | FS_virtual_specified = false; |
591 | FS_virtualLoc = SourceLocation(); |
592 | FS_explicit_specifier = ExplicitSpecifier(); |
593 | FS_explicitLoc = SourceLocation(); |
594 | FS_explicitCloseParenLoc = SourceLocation(); |
595 | FS_noreturn_specified = false; |
596 | FS_noreturnLoc = SourceLocation(); |
597 | } |
598 | |
599 | /// This method calls the passed in handler on each CVRU qual being |
600 | /// set. |
601 | /// Handle - a handler to be invoked. |
602 | void forEachCVRUQualifier( |
603 | llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle); |
604 | |
605 | /// This method calls the passed in handler on each qual being |
606 | /// set. |
607 | /// Handle - a handler to be invoked. |
608 | void forEachQualifier( |
609 | llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle); |
610 | |
611 | /// Return true if any type-specifier has been found. |
612 | bool hasTypeSpecifier() const { |
613 | return getTypeSpecType() != DeclSpec::TST_unspecified || |
614 | getTypeSpecWidth() != DeclSpec::TSW_unspecified || |
615 | getTypeSpecComplex() != DeclSpec::TSC_unspecified || |
616 | getTypeSpecSign() != DeclSpec::TSS_unspecified; |
617 | } |
618 | |
619 | /// Return a bitmask of which flavors of specifiers this |
620 | /// DeclSpec includes. |
621 | unsigned getParsedSpecifiers() const; |
622 | |
623 | /// isEmpty - Return true if this declaration specifier is completely empty: |
624 | /// no tokens were parsed in the production of it. |
625 | bool isEmpty() const { |
626 | return getParsedSpecifiers() == DeclSpec::PQ_None; |
627 | } |
628 | |
629 | void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); } |
630 | void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); } |
631 | |
632 | /// These methods set the specified attribute of the DeclSpec and |
633 | /// return false if there was no error. If an error occurs (for |
634 | /// example, if we tried to set "auto" on a spec with "extern" |
635 | /// already set), they return true and set PrevSpec and DiagID |
636 | /// such that |
637 | /// Diag(Loc, DiagID) << PrevSpec; |
638 | /// will yield a useful result. |
639 | /// |
640 | /// TODO: use a more general approach that still allows these |
641 | /// diagnostics to be ignored when desired. |
642 | bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, |
643 | const char *&PrevSpec, unsigned &DiagID, |
644 | const PrintingPolicy &Policy); |
645 | bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc, |
646 | const char *&PrevSpec, unsigned &DiagID); |
647 | bool SetTypeSpecWidth(TSW W, SourceLocation Loc, const char *&PrevSpec, |
648 | unsigned &DiagID, const PrintingPolicy &Policy); |
649 | bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec, |
650 | unsigned &DiagID); |
651 | bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec, |
652 | unsigned &DiagID); |
653 | bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, |
654 | unsigned &DiagID, const PrintingPolicy &Policy); |
655 | bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, |
656 | unsigned &DiagID, ParsedType Rep, |
657 | const PrintingPolicy &Policy); |
658 | bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, |
659 | unsigned &DiagID, Decl *Rep, bool Owned, |
660 | const PrintingPolicy &Policy); |
661 | bool SetTypeSpecType(TST T, SourceLocation TagKwLoc, |
662 | SourceLocation TagNameLoc, const char *&PrevSpec, |
663 | unsigned &DiagID, ParsedType Rep, |
664 | const PrintingPolicy &Policy); |
665 | bool SetTypeSpecType(TST T, SourceLocation TagKwLoc, |
666 | SourceLocation TagNameLoc, const char *&PrevSpec, |
667 | unsigned &DiagID, Decl *Rep, bool Owned, |
668 | const PrintingPolicy &Policy); |
669 | |
670 | bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, |
671 | unsigned &DiagID, Expr *Rep, |
672 | const PrintingPolicy &policy); |
673 | bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc, |
674 | const char *&PrevSpec, unsigned &DiagID, |
675 | const PrintingPolicy &Policy); |
676 | bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc, |
677 | const char *&PrevSpec, unsigned &DiagID, |
678 | const PrintingPolicy &Policy); |
679 | bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc, |
680 | const char *&PrevSpec, unsigned &DiagID, |
681 | const PrintingPolicy &Policy); |
682 | bool SetTypePipe(bool isPipe, SourceLocation Loc, |
683 | const char *&PrevSpec, unsigned &DiagID, |
684 | const PrintingPolicy &Policy); |
685 | bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec, |
686 | unsigned &DiagID); |
687 | bool SetTypeSpecError(); |
688 | void UpdateDeclRep(Decl *Rep) { |
689 | assert(isDeclRep((TST) TypeSpecType))((isDeclRep((TST) TypeSpecType)) ? static_cast<void> (0 ) : __assert_fail ("isDeclRep((TST) TypeSpecType)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 689, __PRETTY_FUNCTION__)); |
690 | DeclRep = Rep; |
691 | } |
692 | void UpdateTypeRep(ParsedType Rep) { |
693 | assert(isTypeRep((TST) TypeSpecType))((isTypeRep((TST) TypeSpecType)) ? static_cast<void> (0 ) : __assert_fail ("isTypeRep((TST) TypeSpecType)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 693, __PRETTY_FUNCTION__)); |
694 | TypeRep = Rep; |
695 | } |
696 | void UpdateExprRep(Expr *Rep) { |
697 | assert(isExprRep((TST) TypeSpecType))((isExprRep((TST) TypeSpecType)) ? static_cast<void> (0 ) : __assert_fail ("isExprRep((TST) TypeSpecType)", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 697, __PRETTY_FUNCTION__)); |
698 | ExprRep = Rep; |
699 | } |
700 | |
701 | bool SetTypeQual(TQ T, SourceLocation Loc); |
702 | |
703 | bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec, |
704 | unsigned &DiagID, const LangOptions &Lang); |
705 | |
706 | bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec, |
707 | unsigned &DiagID); |
708 | bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec, |
709 | unsigned &DiagID); |
710 | bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec, |
711 | unsigned &DiagID); |
712 | bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec, |
713 | unsigned &DiagID, ExplicitSpecifier ExplicitSpec, |
714 | SourceLocation CloseParenLoc); |
715 | bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec, |
716 | unsigned &DiagID); |
717 | |
718 | bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec, |
719 | unsigned &DiagID); |
720 | bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec, |
721 | unsigned &DiagID); |
722 | bool SetConstexprSpec(ConstexprSpecKind ConstexprKind, SourceLocation Loc, |
723 | const char *&PrevSpec, unsigned &DiagID); |
724 | |
725 | bool isFriendSpecified() const { return Friend_specified; } |
726 | SourceLocation getFriendSpecLoc() const { return FriendLoc; } |
727 | |
728 | bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); } |
729 | SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; } |
730 | |
731 | ConstexprSpecKind getConstexprSpecifier() const { |
732 | return ConstexprSpecKind(ConstexprSpecifier); |
733 | } |
734 | |
735 | SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; } |
736 | bool hasConstexprSpecifier() const { |
737 | return ConstexprSpecifier != CSK_unspecified; |
738 | } |
739 | |
740 | void ClearConstexprSpec() { |
741 | ConstexprSpecifier = CSK_unspecified; |
742 | ConstexprLoc = SourceLocation(); |
743 | } |
744 | |
745 | AttributePool &getAttributePool() const { |
746 | return Attrs.getPool(); |
747 | } |
748 | |
749 | /// Concatenates two attribute lists. |
750 | /// |
751 | /// The GCC attribute syntax allows for the following: |
752 | /// |
753 | /// \code |
754 | /// short __attribute__(( unused, deprecated )) |
755 | /// int __attribute__(( may_alias, aligned(16) )) var; |
756 | /// \endcode |
757 | /// |
758 | /// This declares 4 attributes using 2 lists. The following syntax is |
759 | /// also allowed and equivalent to the previous declaration. |
760 | /// |
761 | /// \code |
762 | /// short __attribute__((unused)) __attribute__((deprecated)) |
763 | /// int __attribute__((may_alias)) __attribute__((aligned(16))) var; |
764 | /// \endcode |
765 | /// |
766 | void addAttributes(ParsedAttributesView &AL) { |
767 | Attrs.addAll(AL.begin(), AL.end()); |
768 | } |
769 | |
770 | bool hasAttributes() const { return !Attrs.empty(); } |
771 | |
772 | ParsedAttributes &getAttributes() { return Attrs; } |
773 | const ParsedAttributes &getAttributes() const { return Attrs; } |
774 | |
775 | void takeAttributesFrom(ParsedAttributes &attrs) { |
776 | Attrs.takeAllFrom(attrs); |
777 | } |
778 | |
779 | /// Finish - This does final analysis of the declspec, issuing diagnostics for |
780 | /// things like "_Imaginary" (lacking an FP type). After calling this method, |
781 | /// DeclSpec is guaranteed self-consistent, even if an error occurred. |
782 | void Finish(Sema &S, const PrintingPolicy &Policy); |
783 | |
784 | const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const { |
785 | return writtenBS; |
786 | } |
787 | |
788 | ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; } |
789 | void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; } |
790 | |
791 | /// Checks if this DeclSpec can stand alone, without a Declarator. |
792 | /// |
793 | /// Only tag declspecs can stand alone. |
794 | bool isMissingDeclaratorOk(); |
795 | }; |
796 | |
797 | /// Captures information about "declaration specifiers" specific to |
798 | /// Objective-C. |
799 | class ObjCDeclSpec { |
800 | public: |
801 | /// ObjCDeclQualifier - Qualifier used on types in method |
802 | /// declarations. Not all combinations are sensible. Parameters |
803 | /// can be one of { in, out, inout } with one of { bycopy, byref }. |
804 | /// Returns can either be { oneway } or not. |
805 | /// |
806 | /// This should be kept in sync with Decl::ObjCDeclQualifier. |
807 | enum ObjCDeclQualifier { |
808 | DQ_None = 0x0, |
809 | DQ_In = 0x1, |
810 | DQ_Inout = 0x2, |
811 | DQ_Out = 0x4, |
812 | DQ_Bycopy = 0x8, |
813 | DQ_Byref = 0x10, |
814 | DQ_Oneway = 0x20, |
815 | DQ_CSNullability = 0x40 |
816 | }; |
817 | |
818 | /// PropertyAttributeKind - list of property attributes. |
819 | /// Keep this list in sync with LLVM's Dwarf.h ApplePropertyAttributes. |
820 | enum ObjCPropertyAttributeKind { |
821 | DQ_PR_noattr = 0x0, |
822 | DQ_PR_readonly = 0x01, |
823 | DQ_PR_getter = 0x02, |
824 | DQ_PR_assign = 0x04, |
825 | DQ_PR_readwrite = 0x08, |
826 | DQ_PR_retain = 0x10, |
827 | DQ_PR_copy = 0x20, |
828 | DQ_PR_nonatomic = 0x40, |
829 | DQ_PR_setter = 0x80, |
830 | DQ_PR_atomic = 0x100, |
831 | DQ_PR_weak = 0x200, |
832 | DQ_PR_strong = 0x400, |
833 | DQ_PR_unsafe_unretained = 0x800, |
834 | DQ_PR_nullability = 0x1000, |
835 | DQ_PR_null_resettable = 0x2000, |
836 | DQ_PR_class = 0x4000, |
837 | DQ_PR_direct = 0x8000, |
838 | }; |
839 | |
840 | ObjCDeclSpec() |
841 | : objcDeclQualifier(DQ_None), PropertyAttributes(DQ_PR_noattr), |
842 | Nullability(0), GetterName(nullptr), SetterName(nullptr) { } |
843 | |
844 | ObjCDeclQualifier getObjCDeclQualifier() const { |
845 | return (ObjCDeclQualifier)objcDeclQualifier; |
846 | } |
847 | void setObjCDeclQualifier(ObjCDeclQualifier DQVal) { |
848 | objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal); |
849 | } |
850 | void clearObjCDeclQualifier(ObjCDeclQualifier DQVal) { |
851 | objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier & ~DQVal); |
852 | } |
853 | |
854 | ObjCPropertyAttributeKind getPropertyAttributes() const { |
855 | return ObjCPropertyAttributeKind(PropertyAttributes); |
856 | } |
857 | void setPropertyAttributes(ObjCPropertyAttributeKind PRVal) { |
858 | PropertyAttributes = |
859 | (ObjCPropertyAttributeKind)(PropertyAttributes | PRVal); |
860 | } |
861 | |
862 | NullabilityKind getNullability() const { |
863 | assert(((getObjCDeclQualifier() & DQ_CSNullability) ||((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes () & DQ_PR_nullability)) && "Objective-C declspec doesn't have nullability" ) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Objective-C declspec doesn't have nullability\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 865, __PRETTY_FUNCTION__)) |
864 | (getPropertyAttributes() & DQ_PR_nullability)) &&((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes () & DQ_PR_nullability)) && "Objective-C declspec doesn't have nullability" ) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Objective-C declspec doesn't have nullability\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 865, __PRETTY_FUNCTION__)) |
865 | "Objective-C declspec doesn't have nullability")((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes () & DQ_PR_nullability)) && "Objective-C declspec doesn't have nullability" ) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Objective-C declspec doesn't have nullability\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 865, __PRETTY_FUNCTION__)); |
866 | return static_cast<NullabilityKind>(Nullability); |
867 | } |
868 | |
869 | SourceLocation getNullabilityLoc() const { |
870 | assert(((getObjCDeclQualifier() & DQ_CSNullability) ||((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes () & DQ_PR_nullability)) && "Objective-C declspec doesn't have nullability" ) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Objective-C declspec doesn't have nullability\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 872, __PRETTY_FUNCTION__)) |
871 | (getPropertyAttributes() & DQ_PR_nullability)) &&((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes () & DQ_PR_nullability)) && "Objective-C declspec doesn't have nullability" ) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Objective-C declspec doesn't have nullability\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 872, __PRETTY_FUNCTION__)) |
872 | "Objective-C declspec doesn't have nullability")((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes () & DQ_PR_nullability)) && "Objective-C declspec doesn't have nullability" ) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Objective-C declspec doesn't have nullability\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 872, __PRETTY_FUNCTION__)); |
873 | return NullabilityLoc; |
874 | } |
875 | |
876 | void setNullability(SourceLocation loc, NullabilityKind kind) { |
877 | assert(((getObjCDeclQualifier() & DQ_CSNullability) ||((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes () & DQ_PR_nullability)) && "Set the nullability declspec or property attribute first" ) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Set the nullability declspec or property attribute first\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 879, __PRETTY_FUNCTION__)) |
878 | (getPropertyAttributes() & DQ_PR_nullability)) &&((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes () & DQ_PR_nullability)) && "Set the nullability declspec or property attribute first" ) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Set the nullability declspec or property attribute first\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 879, __PRETTY_FUNCTION__)) |
879 | "Set the nullability declspec or property attribute first")((((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes () & DQ_PR_nullability)) && "Set the nullability declspec or property attribute first" ) ? static_cast<void> (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & DQ_PR_nullability)) && \"Set the nullability declspec or property attribute first\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 879, __PRETTY_FUNCTION__)); |
880 | Nullability = static_cast<unsigned>(kind); |
881 | NullabilityLoc = loc; |
882 | } |
883 | |
884 | const IdentifierInfo *getGetterName() const { return GetterName; } |
885 | IdentifierInfo *getGetterName() { return GetterName; } |
886 | SourceLocation getGetterNameLoc() const { return GetterNameLoc; } |
887 | void setGetterName(IdentifierInfo *name, SourceLocation loc) { |
888 | GetterName = name; |
889 | GetterNameLoc = loc; |
890 | } |
891 | |
892 | const IdentifierInfo *getSetterName() const { return SetterName; } |
893 | IdentifierInfo *getSetterName() { return SetterName; } |
894 | SourceLocation getSetterNameLoc() const { return SetterNameLoc; } |
895 | void setSetterName(IdentifierInfo *name, SourceLocation loc) { |
896 | SetterName = name; |
897 | SetterNameLoc = loc; |
898 | } |
899 | |
900 | private: |
901 | // FIXME: These two are unrelated and mutually exclusive. So perhaps |
902 | // we can put them in a union to reflect their mutual exclusivity |
903 | // (space saving is negligible). |
904 | unsigned objcDeclQualifier : 7; |
905 | |
906 | // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttributeKind |
907 | unsigned PropertyAttributes : 16; |
908 | |
909 | unsigned Nullability : 2; |
910 | |
911 | SourceLocation NullabilityLoc; |
912 | |
913 | IdentifierInfo *GetterName; // getter name or NULL if no getter |
914 | IdentifierInfo *SetterName; // setter name or NULL if no setter |
915 | SourceLocation GetterNameLoc; // location of the getter attribute's value |
916 | SourceLocation SetterNameLoc; // location of the setter attribute's value |
917 | |
918 | }; |
919 | |
920 | /// Describes the kind of unqualified-id parsed. |
921 | enum class UnqualifiedIdKind { |
922 | /// An identifier. |
923 | IK_Identifier, |
924 | /// An overloaded operator name, e.g., operator+. |
925 | IK_OperatorFunctionId, |
926 | /// A conversion function name, e.g., operator int. |
927 | IK_ConversionFunctionId, |
928 | /// A user-defined literal name, e.g., operator "" _i. |
929 | IK_LiteralOperatorId, |
930 | /// A constructor name. |
931 | IK_ConstructorName, |
932 | /// A constructor named via a template-id. |
933 | IK_ConstructorTemplateId, |
934 | /// A destructor name. |
935 | IK_DestructorName, |
936 | /// A template-id, e.g., f<int>. |
937 | IK_TemplateId, |
938 | /// An implicit 'self' parameter |
939 | IK_ImplicitSelfParam, |
940 | /// A deduction-guide name (a template-name) |
941 | IK_DeductionGuideName |
942 | }; |
943 | |
944 | /// Represents a C++ unqualified-id that has been parsed. |
945 | class UnqualifiedId { |
946 | private: |
947 | UnqualifiedId(const UnqualifiedId &Other) = delete; |
948 | const UnqualifiedId &operator=(const UnqualifiedId &) = delete; |
949 | |
950 | public: |
951 | /// Describes the kind of unqualified-id parsed. |
952 | UnqualifiedIdKind Kind; |
953 | |
954 | struct OFI { |
955 | /// The kind of overloaded operator. |
956 | OverloadedOperatorKind Operator; |
957 | |
958 | /// The source locations of the individual tokens that name |
959 | /// the operator, e.g., the "new", "[", and "]" tokens in |
960 | /// operator new []. |
961 | /// |
962 | /// Different operators have different numbers of tokens in their name, |
963 | /// up to three. Any remaining source locations in this array will be |
964 | /// set to an invalid value for operators with fewer than three tokens. |
965 | unsigned SymbolLocations[3]; |
966 | }; |
967 | |
968 | /// Anonymous union that holds extra data associated with the |
969 | /// parsed unqualified-id. |
970 | union { |
971 | /// When Kind == IK_Identifier, the parsed identifier, or when |
972 | /// Kind == IK_UserLiteralId, the identifier suffix. |
973 | IdentifierInfo *Identifier; |
974 | |
975 | /// When Kind == IK_OperatorFunctionId, the overloaded operator |
976 | /// that we parsed. |
977 | struct OFI OperatorFunctionId; |
978 | |
979 | /// When Kind == IK_ConversionFunctionId, the type that the |
980 | /// conversion function names. |
981 | UnionParsedType ConversionFunctionId; |
982 | |
983 | /// When Kind == IK_ConstructorName, the class-name of the type |
984 | /// whose constructor is being referenced. |
985 | UnionParsedType ConstructorName; |
986 | |
987 | /// When Kind == IK_DestructorName, the type referred to by the |
988 | /// class-name. |
989 | UnionParsedType DestructorName; |
990 | |
991 | /// When Kind == IK_DeductionGuideName, the parsed template-name. |
992 | UnionParsedTemplateTy TemplateName; |
993 | |
994 | /// When Kind == IK_TemplateId or IK_ConstructorTemplateId, |
995 | /// the template-id annotation that contains the template name and |
996 | /// template arguments. |
997 | TemplateIdAnnotation *TemplateId; |
998 | }; |
999 | |
1000 | /// The location of the first token that describes this unqualified-id, |
1001 | /// which will be the location of the identifier, "operator" keyword, |
1002 | /// tilde (for a destructor), or the template name of a template-id. |
1003 | SourceLocation StartLocation; |
1004 | |
1005 | /// The location of the last token that describes this unqualified-id. |
1006 | SourceLocation EndLocation; |
1007 | |
1008 | UnqualifiedId() |
1009 | : Kind(UnqualifiedIdKind::IK_Identifier), Identifier(nullptr) {} |
1010 | |
1011 | /// Clear out this unqualified-id, setting it to default (invalid) |
1012 | /// state. |
1013 | void clear() { |
1014 | Kind = UnqualifiedIdKind::IK_Identifier; |
1015 | Identifier = nullptr; |
1016 | StartLocation = SourceLocation(); |
1017 | EndLocation = SourceLocation(); |
1018 | } |
1019 | |
1020 | /// Determine whether this unqualified-id refers to a valid name. |
1021 | bool isValid() const { return StartLocation.isValid(); } |
1022 | |
1023 | /// Determine whether this unqualified-id refers to an invalid name. |
1024 | bool isInvalid() const { return !isValid(); } |
1025 | |
1026 | /// Determine what kind of name we have. |
1027 | UnqualifiedIdKind getKind() const { return Kind; } |
1028 | void setKind(UnqualifiedIdKind kind) { Kind = kind; } |
1029 | |
1030 | /// Specify that this unqualified-id was parsed as an identifier. |
1031 | /// |
1032 | /// \param Id the parsed identifier. |
1033 | /// \param IdLoc the location of the parsed identifier. |
1034 | void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) { |
1035 | Kind = UnqualifiedIdKind::IK_Identifier; |
1036 | Identifier = const_cast<IdentifierInfo *>(Id); |
1037 | StartLocation = EndLocation = IdLoc; |
1038 | } |
1039 | |
1040 | /// Specify that this unqualified-id was parsed as an |
1041 | /// operator-function-id. |
1042 | /// |
1043 | /// \param OperatorLoc the location of the 'operator' keyword. |
1044 | /// |
1045 | /// \param Op the overloaded operator. |
1046 | /// |
1047 | /// \param SymbolLocations the locations of the individual operator symbols |
1048 | /// in the operator. |
1049 | void setOperatorFunctionId(SourceLocation OperatorLoc, |
1050 | OverloadedOperatorKind Op, |
1051 | SourceLocation SymbolLocations[3]); |
1052 | |
1053 | /// Specify that this unqualified-id was parsed as a |
1054 | /// conversion-function-id. |
1055 | /// |
1056 | /// \param OperatorLoc the location of the 'operator' keyword. |
1057 | /// |
1058 | /// \param Ty the type to which this conversion function is converting. |
1059 | /// |
1060 | /// \param EndLoc the location of the last token that makes up the type name. |
1061 | void setConversionFunctionId(SourceLocation OperatorLoc, |
1062 | ParsedType Ty, |
1063 | SourceLocation EndLoc) { |
1064 | Kind = UnqualifiedIdKind::IK_ConversionFunctionId; |
1065 | StartLocation = OperatorLoc; |
1066 | EndLocation = EndLoc; |
1067 | ConversionFunctionId = Ty; |
1068 | } |
1069 | |
1070 | /// Specific that this unqualified-id was parsed as a |
1071 | /// literal-operator-id. |
1072 | /// |
1073 | /// \param Id the parsed identifier. |
1074 | /// |
1075 | /// \param OpLoc the location of the 'operator' keyword. |
1076 | /// |
1077 | /// \param IdLoc the location of the identifier. |
1078 | void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc, |
1079 | SourceLocation IdLoc) { |
1080 | Kind = UnqualifiedIdKind::IK_LiteralOperatorId; |
1081 | Identifier = const_cast<IdentifierInfo *>(Id); |
1082 | StartLocation = OpLoc; |
1083 | EndLocation = IdLoc; |
1084 | } |
1085 | |
1086 | /// Specify that this unqualified-id was parsed as a constructor name. |
1087 | /// |
1088 | /// \param ClassType the class type referred to by the constructor name. |
1089 | /// |
1090 | /// \param ClassNameLoc the location of the class name. |
1091 | /// |
1092 | /// \param EndLoc the location of the last token that makes up the type name. |
1093 | void setConstructorName(ParsedType ClassType, |
1094 | SourceLocation ClassNameLoc, |
1095 | SourceLocation EndLoc) { |
1096 | Kind = UnqualifiedIdKind::IK_ConstructorName; |
1097 | StartLocation = ClassNameLoc; |
1098 | EndLocation = EndLoc; |
1099 | ConstructorName = ClassType; |
1100 | } |
1101 | |
1102 | /// Specify that this unqualified-id was parsed as a |
1103 | /// template-id that names a constructor. |
1104 | /// |
1105 | /// \param TemplateId the template-id annotation that describes the parsed |
1106 | /// template-id. This UnqualifiedId instance will take ownership of the |
1107 | /// \p TemplateId and will free it on destruction. |
1108 | void setConstructorTemplateId(TemplateIdAnnotation *TemplateId); |
1109 | |
1110 | /// Specify that this unqualified-id was parsed as a destructor name. |
1111 | /// |
1112 | /// \param TildeLoc the location of the '~' that introduces the destructor |
1113 | /// name. |
1114 | /// |
1115 | /// \param ClassType the name of the class referred to by the destructor name. |
1116 | void setDestructorName(SourceLocation TildeLoc, |
1117 | ParsedType ClassType, |
1118 | SourceLocation EndLoc) { |
1119 | Kind = UnqualifiedIdKind::IK_DestructorName; |
1120 | StartLocation = TildeLoc; |
1121 | EndLocation = EndLoc; |
1122 | DestructorName = ClassType; |
1123 | } |
1124 | |
1125 | /// Specify that this unqualified-id was parsed as a template-id. |
1126 | /// |
1127 | /// \param TemplateId the template-id annotation that describes the parsed |
1128 | /// template-id. This UnqualifiedId instance will take ownership of the |
1129 | /// \p TemplateId and will free it on destruction. |
1130 | void setTemplateId(TemplateIdAnnotation *TemplateId); |
1131 | |
1132 | /// Specify that this unqualified-id was parsed as a template-name for |
1133 | /// a deduction-guide. |
1134 | /// |
1135 | /// \param Template The parsed template-name. |
1136 | /// \param TemplateLoc The location of the parsed template-name. |
1137 | void setDeductionGuideName(ParsedTemplateTy Template, |
1138 | SourceLocation TemplateLoc) { |
1139 | Kind = UnqualifiedIdKind::IK_DeductionGuideName; |
1140 | TemplateName = Template; |
1141 | StartLocation = EndLocation = TemplateLoc; |
1142 | } |
1143 | |
1144 | /// Return the source range that covers this unqualified-id. |
1145 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { |
1146 | return SourceRange(StartLocation, EndLocation); |
1147 | } |
1148 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return StartLocation; } |
1149 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return EndLocation; } |
1150 | }; |
1151 | |
1152 | /// A set of tokens that has been cached for later parsing. |
1153 | typedef SmallVector<Token, 4> CachedTokens; |
1154 | |
1155 | /// One instance of this struct is used for each type in a |
1156 | /// declarator that is parsed. |
1157 | /// |
1158 | /// This is intended to be a small value object. |
1159 | struct DeclaratorChunk { |
1160 | enum { |
1161 | Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren, Pipe |
1162 | } Kind; |
1163 | |
1164 | /// Loc - The place where this type was defined. |
1165 | SourceLocation Loc; |
1166 | /// EndLoc - If valid, the place where this chunck ends. |
1167 | SourceLocation EndLoc; |
1168 | |
1169 | SourceRange getSourceRange() const { |
1170 | if (EndLoc.isInvalid()) |
1171 | return SourceRange(Loc, Loc); |
1172 | return SourceRange(Loc, EndLoc); |
1173 | } |
1174 | |
1175 | ParsedAttributesView AttrList; |
1176 | |
1177 | struct PointerTypeInfo { |
1178 | /// The type qualifiers: const/volatile/restrict/unaligned/atomic. |
1179 | unsigned TypeQuals : 5; |
1180 | |
1181 | /// The location of the const-qualifier, if any. |
1182 | unsigned ConstQualLoc; |
1183 | |
1184 | /// The location of the volatile-qualifier, if any. |
1185 | unsigned VolatileQualLoc; |
1186 | |
1187 | /// The location of the restrict-qualifier, if any. |
1188 | unsigned RestrictQualLoc; |
1189 | |
1190 | /// The location of the _Atomic-qualifier, if any. |
1191 | unsigned AtomicQualLoc; |
1192 | |
1193 | /// The location of the __unaligned-qualifier, if any. |
1194 | unsigned UnalignedQualLoc; |
1195 | |
1196 | void destroy() { |
1197 | } |
1198 | }; |
1199 | |
1200 | struct ReferenceTypeInfo { |
1201 | /// The type qualifier: restrict. [GNU] C++ extension |
1202 | bool HasRestrict : 1; |
1203 | /// True if this is an lvalue reference, false if it's an rvalue reference. |
1204 | bool LValueRef : 1; |
1205 | void destroy() { |
1206 | } |
1207 | }; |
1208 | |
1209 | struct ArrayTypeInfo { |
1210 | /// The type qualifiers for the array: |
1211 | /// const/volatile/restrict/__unaligned/_Atomic. |
1212 | unsigned TypeQuals : 5; |
1213 | |
1214 | /// True if this dimension included the 'static' keyword. |
1215 | unsigned hasStatic : 1; |
1216 | |
1217 | /// True if this dimension was [*]. In this case, NumElts is null. |
1218 | unsigned isStar : 1; |
1219 | |
1220 | /// This is the size of the array, or null if [] or [*] was specified. |
1221 | /// Since the parser is multi-purpose, and we don't want to impose a root |
1222 | /// expression class on all clients, NumElts is untyped. |
1223 | Expr *NumElts; |
1224 | |
1225 | void destroy() {} |
1226 | }; |
1227 | |
1228 | /// ParamInfo - An array of paraminfo objects is allocated whenever a function |
1229 | /// declarator is parsed. There are two interesting styles of parameters |
1230 | /// here: |
1231 | /// K&R-style identifier lists and parameter type lists. K&R-style identifier |
1232 | /// lists will have information about the identifier, but no type information. |
1233 | /// Parameter type lists will have type info (if the actions module provides |
1234 | /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'. |
1235 | struct ParamInfo { |
1236 | IdentifierInfo *Ident; |
1237 | SourceLocation IdentLoc; |
1238 | Decl *Param; |
1239 | |
1240 | /// DefaultArgTokens - When the parameter's default argument |
1241 | /// cannot be parsed immediately (because it occurs within the |
1242 | /// declaration of a member function), it will be stored here as a |
1243 | /// sequence of tokens to be parsed once the class definition is |
1244 | /// complete. Non-NULL indicates that there is a default argument. |
1245 | std::unique_ptr<CachedTokens> DefaultArgTokens; |
1246 | |
1247 | ParamInfo() = default; |
1248 | ParamInfo(IdentifierInfo *ident, SourceLocation iloc, |
1249 | Decl *param, |
1250 | std::unique_ptr<CachedTokens> DefArgTokens = nullptr) |
1251 | : Ident(ident), IdentLoc(iloc), Param(param), |
1252 | DefaultArgTokens(std::move(DefArgTokens)) {} |
1253 | }; |
1254 | |
1255 | struct TypeAndRange { |
1256 | ParsedType Ty; |
1257 | SourceRange Range; |
1258 | }; |
1259 | |
1260 | struct FunctionTypeInfo { |
1261 | /// hasPrototype - This is true if the function had at least one typed |
1262 | /// parameter. If the function is () or (a,b,c), then it has no prototype, |
1263 | /// and is treated as a K&R-style function. |
1264 | unsigned hasPrototype : 1; |
1265 | |
1266 | /// isVariadic - If this function has a prototype, and if that |
1267 | /// proto ends with ',...)', this is true. When true, EllipsisLoc |
1268 | /// contains the location of the ellipsis. |
1269 | unsigned isVariadic : 1; |
1270 | |
1271 | /// Can this declaration be a constructor-style initializer? |
1272 | unsigned isAmbiguous : 1; |
1273 | |
1274 | /// Whether the ref-qualifier (if any) is an lvalue reference. |
1275 | /// Otherwise, it's an rvalue reference. |
1276 | unsigned RefQualifierIsLValueRef : 1; |
1277 | |
1278 | /// ExceptionSpecType - An ExceptionSpecificationType value. |
1279 | unsigned ExceptionSpecType : 4; |
1280 | |
1281 | /// DeleteParams - If this is true, we need to delete[] Params. |
1282 | unsigned DeleteParams : 1; |
1283 | |
1284 | /// HasTrailingReturnType - If this is true, a trailing return type was |
1285 | /// specified. |
1286 | unsigned HasTrailingReturnType : 1; |
1287 | |
1288 | /// The location of the left parenthesis in the source. |
1289 | unsigned LParenLoc; |
1290 | |
1291 | /// When isVariadic is true, the location of the ellipsis in the source. |
1292 | unsigned EllipsisLoc; |
1293 | |
1294 | /// The location of the right parenthesis in the source. |
1295 | unsigned RParenLoc; |
1296 | |
1297 | /// NumParams - This is the number of formal parameters specified by the |
1298 | /// declarator. |
1299 | unsigned NumParams; |
1300 | |
1301 | /// NumExceptionsOrDecls - This is the number of types in the |
1302 | /// dynamic-exception-decl, if the function has one. In C, this is the |
1303 | /// number of declarations in the function prototype. |
1304 | unsigned NumExceptionsOrDecls; |
1305 | |
1306 | /// The location of the ref-qualifier, if any. |
1307 | /// |
1308 | /// If this is an invalid location, there is no ref-qualifier. |
1309 | unsigned RefQualifierLoc; |
1310 | |
1311 | /// The location of the 'mutable' qualifer in a lambda-declarator, if |
1312 | /// any. |
1313 | unsigned MutableLoc; |
1314 | |
1315 | /// The beginning location of the exception specification, if any. |
1316 | unsigned ExceptionSpecLocBeg; |
1317 | |
1318 | /// The end location of the exception specification, if any. |
1319 | unsigned ExceptionSpecLocEnd; |
1320 | |
1321 | /// Params - This is a pointer to a new[]'d array of ParamInfo objects that |
1322 | /// describe the parameters specified by this function declarator. null if |
1323 | /// there are no parameters specified. |
1324 | ParamInfo *Params; |
1325 | |
1326 | /// DeclSpec for the function with the qualifier related info. |
1327 | DeclSpec *MethodQualifiers; |
1328 | |
1329 | /// AtttibuteFactory for the MethodQualifiers. |
1330 | AttributeFactory *QualAttrFactory; |
1331 | |
1332 | union { |
1333 | /// Pointer to a new[]'d array of TypeAndRange objects that |
1334 | /// contain the types in the function's dynamic exception specification |
1335 | /// and their locations, if there is one. |
1336 | TypeAndRange *Exceptions; |
1337 | |
1338 | /// Pointer to the expression in the noexcept-specifier of this |
1339 | /// function, if it has one. |
1340 | Expr *NoexceptExpr; |
1341 | |
1342 | /// Pointer to the cached tokens for an exception-specification |
1343 | /// that has not yet been parsed. |
1344 | CachedTokens *ExceptionSpecTokens; |
1345 | |
1346 | /// Pointer to a new[]'d array of declarations that need to be available |
1347 | /// for lookup inside the function body, if one exists. Does not exist in |
1348 | /// C++. |
1349 | NamedDecl **DeclsInPrototype; |
1350 | }; |
1351 | |
1352 | /// If HasTrailingReturnType is true, this is the trailing return |
1353 | /// type specified. |
1354 | UnionParsedType TrailingReturnType; |
1355 | |
1356 | /// Reset the parameter list to having zero parameters. |
1357 | /// |
1358 | /// This is used in various places for error recovery. |
1359 | void freeParams() { |
1360 | for (unsigned I = 0; I < NumParams; ++I) |
1361 | Params[I].DefaultArgTokens.reset(); |
1362 | if (DeleteParams) { |
1363 | delete[] Params; |
1364 | DeleteParams = false; |
1365 | } |
1366 | NumParams = 0; |
1367 | } |
1368 | |
1369 | void destroy() { |
1370 | freeParams(); |
1371 | delete QualAttrFactory; |
1372 | delete MethodQualifiers; |
1373 | switch (getExceptionSpecType()) { |
1374 | default: |
1375 | break; |
1376 | case EST_Dynamic: |
1377 | delete[] Exceptions; |
1378 | break; |
1379 | case EST_Unparsed: |
1380 | delete ExceptionSpecTokens; |
1381 | break; |
1382 | case EST_None: |
1383 | if (NumExceptionsOrDecls != 0) |
1384 | delete[] DeclsInPrototype; |
1385 | break; |
1386 | } |
1387 | } |
1388 | |
1389 | DeclSpec &getOrCreateMethodQualifiers() { |
1390 | if (!MethodQualifiers) { |
1391 | QualAttrFactory = new AttributeFactory(); |
1392 | MethodQualifiers = new DeclSpec(*QualAttrFactory); |
1393 | } |
1394 | return *MethodQualifiers; |
1395 | } |
1396 | |
1397 | /// isKNRPrototype - Return true if this is a K&R style identifier list, |
1398 | /// like "void foo(a,b,c)". In a function definition, this will be followed |
1399 | /// by the parameter type definitions. |
1400 | bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; } |
1401 | |
1402 | SourceLocation getLParenLoc() const { |
1403 | return SourceLocation::getFromRawEncoding(LParenLoc); |
1404 | } |
1405 | |
1406 | SourceLocation getEllipsisLoc() const { |
1407 | return SourceLocation::getFromRawEncoding(EllipsisLoc); |
1408 | } |
1409 | |
1410 | SourceLocation getRParenLoc() const { |
1411 | return SourceLocation::getFromRawEncoding(RParenLoc); |
1412 | } |
1413 | |
1414 | SourceLocation getExceptionSpecLocBeg() const { |
1415 | return SourceLocation::getFromRawEncoding(ExceptionSpecLocBeg); |
1416 | } |
1417 | |
1418 | SourceLocation getExceptionSpecLocEnd() const { |
1419 | return SourceLocation::getFromRawEncoding(ExceptionSpecLocEnd); |
1420 | } |
1421 | |
1422 | SourceRange getExceptionSpecRange() const { |
1423 | return SourceRange(getExceptionSpecLocBeg(), getExceptionSpecLocEnd()); |
1424 | } |
1425 | |
1426 | /// Retrieve the location of the ref-qualifier, if any. |
1427 | SourceLocation getRefQualifierLoc() const { |
1428 | return SourceLocation::getFromRawEncoding(RefQualifierLoc); |
1429 | } |
1430 | |
1431 | /// Retrieve the location of the 'const' qualifier. |
1432 | SourceLocation getConstQualifierLoc() const { |
1433 | assert(MethodQualifiers)((MethodQualifiers) ? static_cast<void> (0) : __assert_fail ("MethodQualifiers", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 1433, __PRETTY_FUNCTION__)); |
1434 | return MethodQualifiers->getConstSpecLoc(); |
1435 | } |
1436 | |
1437 | /// Retrieve the location of the 'volatile' qualifier. |
1438 | SourceLocation getVolatileQualifierLoc() const { |
1439 | assert(MethodQualifiers)((MethodQualifiers) ? static_cast<void> (0) : __assert_fail ("MethodQualifiers", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 1439, __PRETTY_FUNCTION__)); |
1440 | return MethodQualifiers->getVolatileSpecLoc(); |
1441 | } |
1442 | |
1443 | /// Retrieve the location of the 'restrict' qualifier. |
1444 | SourceLocation getRestrictQualifierLoc() const { |
1445 | assert(MethodQualifiers)((MethodQualifiers) ? static_cast<void> (0) : __assert_fail ("MethodQualifiers", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 1445, __PRETTY_FUNCTION__)); |
1446 | return MethodQualifiers->getRestrictSpecLoc(); |
1447 | } |
1448 | |
1449 | /// Retrieve the location of the 'mutable' qualifier, if any. |
1450 | SourceLocation getMutableLoc() const { |
1451 | return SourceLocation::getFromRawEncoding(MutableLoc); |
1452 | } |
1453 | |
1454 | /// Determine whether this function declaration contains a |
1455 | /// ref-qualifier. |
1456 | bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); } |
1457 | |
1458 | /// Determine whether this lambda-declarator contains a 'mutable' |
1459 | /// qualifier. |
1460 | bool hasMutableQualifier() const { return getMutableLoc().isValid(); } |
1461 | |
1462 | /// Determine whether this method has qualifiers. |
1463 | bool hasMethodTypeQualifiers() const { |
1464 | return MethodQualifiers && (MethodQualifiers->getTypeQualifiers() || |
1465 | MethodQualifiers->getAttributes().size()); |
1466 | } |
1467 | |
1468 | /// Get the type of exception specification this function has. |
1469 | ExceptionSpecificationType getExceptionSpecType() const { |
1470 | return static_cast<ExceptionSpecificationType>(ExceptionSpecType); |
1471 | } |
1472 | |
1473 | /// Get the number of dynamic exception specifications. |
1474 | unsigned getNumExceptions() const { |
1475 | assert(ExceptionSpecType != EST_None)((ExceptionSpecType != EST_None) ? static_cast<void> (0 ) : __assert_fail ("ExceptionSpecType != EST_None", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 1475, __PRETTY_FUNCTION__)); |
1476 | return NumExceptionsOrDecls; |
1477 | } |
1478 | |
1479 | /// Get the non-parameter decls defined within this function |
1480 | /// prototype. Typically these are tag declarations. |
1481 | ArrayRef<NamedDecl *> getDeclsInPrototype() const { |
1482 | assert(ExceptionSpecType == EST_None)((ExceptionSpecType == EST_None) ? static_cast<void> (0 ) : __assert_fail ("ExceptionSpecType == EST_None", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 1482, __PRETTY_FUNCTION__)); |
1483 | return llvm::makeArrayRef(DeclsInPrototype, NumExceptionsOrDecls); |
1484 | } |
1485 | |
1486 | /// Determine whether this function declarator had a |
1487 | /// trailing-return-type. |
1488 | bool hasTrailingReturnType() const { return HasTrailingReturnType; } |
1489 | |
1490 | /// Get the trailing-return-type for this function declarator. |
1491 | ParsedType getTrailingReturnType() const { return TrailingReturnType; } |
1492 | }; |
1493 | |
1494 | struct BlockPointerTypeInfo { |
1495 | /// For now, sema will catch these as invalid. |
1496 | /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic. |
1497 | unsigned TypeQuals : 5; |
1498 | |
1499 | void destroy() { |
1500 | } |
1501 | }; |
1502 | |
1503 | struct MemberPointerTypeInfo { |
1504 | /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic. |
1505 | unsigned TypeQuals : 5; |
1506 | // CXXScopeSpec has a constructor, so it can't be a direct member. |
1507 | // So we need some pointer-aligned storage and a bit of trickery. |
1508 | alignas(CXXScopeSpec) char ScopeMem[sizeof(CXXScopeSpec)]; |
1509 | CXXScopeSpec &Scope() { |
1510 | return *reinterpret_cast<CXXScopeSpec *>(ScopeMem); |
1511 | } |
1512 | const CXXScopeSpec &Scope() const { |
1513 | return *reinterpret_cast<const CXXScopeSpec *>(ScopeMem); |
1514 | } |
1515 | void destroy() { |
1516 | Scope().~CXXScopeSpec(); |
1517 | } |
1518 | }; |
1519 | |
1520 | struct PipeTypeInfo { |
1521 | /// The access writes. |
1522 | unsigned AccessWrites : 3; |
1523 | |
1524 | void destroy() {} |
1525 | }; |
1526 | |
1527 | union { |
1528 | PointerTypeInfo Ptr; |
1529 | ReferenceTypeInfo Ref; |
1530 | ArrayTypeInfo Arr; |
1531 | FunctionTypeInfo Fun; |
1532 | BlockPointerTypeInfo Cls; |
1533 | MemberPointerTypeInfo Mem; |
1534 | PipeTypeInfo PipeInfo; |
1535 | }; |
1536 | |
1537 | void destroy() { |
1538 | switch (Kind) { |
1539 | case DeclaratorChunk::Function: return Fun.destroy(); |
1540 | case DeclaratorChunk::Pointer: return Ptr.destroy(); |
1541 | case DeclaratorChunk::BlockPointer: return Cls.destroy(); |
1542 | case DeclaratorChunk::Reference: return Ref.destroy(); |
1543 | case DeclaratorChunk::Array: return Arr.destroy(); |
1544 | case DeclaratorChunk::MemberPointer: return Mem.destroy(); |
1545 | case DeclaratorChunk::Paren: return; |
1546 | case DeclaratorChunk::Pipe: return PipeInfo.destroy(); |
1547 | } |
1548 | } |
1549 | |
1550 | /// If there are attributes applied to this declaratorchunk, return |
1551 | /// them. |
1552 | const ParsedAttributesView &getAttrs() const { return AttrList; } |
1553 | ParsedAttributesView &getAttrs() { return AttrList; } |
1554 | |
1555 | /// Return a DeclaratorChunk for a pointer. |
1556 | static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc, |
1557 | SourceLocation ConstQualLoc, |
1558 | SourceLocation VolatileQualLoc, |
1559 | SourceLocation RestrictQualLoc, |
1560 | SourceLocation AtomicQualLoc, |
1561 | SourceLocation UnalignedQualLoc) { |
1562 | DeclaratorChunk I; |
1563 | I.Kind = Pointer; |
1564 | I.Loc = Loc; |
1565 | I.Ptr.TypeQuals = TypeQuals; |
1566 | I.Ptr.ConstQualLoc = ConstQualLoc.getRawEncoding(); |
1567 | I.Ptr.VolatileQualLoc = VolatileQualLoc.getRawEncoding(); |
1568 | I.Ptr.RestrictQualLoc = RestrictQualLoc.getRawEncoding(); |
1569 | I.Ptr.AtomicQualLoc = AtomicQualLoc.getRawEncoding(); |
1570 | I.Ptr.UnalignedQualLoc = UnalignedQualLoc.getRawEncoding(); |
1571 | return I; |
1572 | } |
1573 | |
1574 | /// Return a DeclaratorChunk for a reference. |
1575 | static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, |
1576 | bool lvalue) { |
1577 | DeclaratorChunk I; |
1578 | I.Kind = Reference; |
1579 | I.Loc = Loc; |
1580 | I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0; |
1581 | I.Ref.LValueRef = lvalue; |
1582 | return I; |
1583 | } |
1584 | |
1585 | /// Return a DeclaratorChunk for an array. |
1586 | static DeclaratorChunk getArray(unsigned TypeQuals, |
1587 | bool isStatic, bool isStar, Expr *NumElts, |
1588 | SourceLocation LBLoc, SourceLocation RBLoc) { |
1589 | DeclaratorChunk I; |
1590 | I.Kind = Array; |
1591 | I.Loc = LBLoc; |
1592 | I.EndLoc = RBLoc; |
1593 | I.Arr.TypeQuals = TypeQuals; |
1594 | I.Arr.hasStatic = isStatic; |
1595 | I.Arr.isStar = isStar; |
1596 | I.Arr.NumElts = NumElts; |
1597 | return I; |
1598 | } |
1599 | |
1600 | /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function. |
1601 | /// "TheDeclarator" is the declarator that this will be added to. |
1602 | static DeclaratorChunk getFunction(bool HasProto, |
1603 | bool IsAmbiguous, |
1604 | SourceLocation LParenLoc, |
1605 | ParamInfo *Params, unsigned NumParams, |
1606 | SourceLocation EllipsisLoc, |
1607 | SourceLocation RParenLoc, |
1608 | bool RefQualifierIsLvalueRef, |
1609 | SourceLocation RefQualifierLoc, |
1610 | SourceLocation MutableLoc, |
1611 | ExceptionSpecificationType ESpecType, |
1612 | SourceRange ESpecRange, |
1613 | ParsedType *Exceptions, |
1614 | SourceRange *ExceptionRanges, |
1615 | unsigned NumExceptions, |
1616 | Expr *NoexceptExpr, |
1617 | CachedTokens *ExceptionSpecTokens, |
1618 | ArrayRef<NamedDecl *> DeclsInPrototype, |
1619 | SourceLocation LocalRangeBegin, |
1620 | SourceLocation LocalRangeEnd, |
1621 | Declarator &TheDeclarator, |
1622 | TypeResult TrailingReturnType = |
1623 | TypeResult(), |
1624 | DeclSpec *MethodQualifiers = nullptr); |
1625 | |
1626 | /// Return a DeclaratorChunk for a block. |
1627 | static DeclaratorChunk getBlockPointer(unsigned TypeQuals, |
1628 | SourceLocation Loc) { |
1629 | DeclaratorChunk I; |
1630 | I.Kind = BlockPointer; |
1631 | I.Loc = Loc; |
1632 | I.Cls.TypeQuals = TypeQuals; |
1633 | return I; |
1634 | } |
1635 | |
1636 | /// Return a DeclaratorChunk for a block. |
1637 | static DeclaratorChunk getPipe(unsigned TypeQuals, |
1638 | SourceLocation Loc) { |
1639 | DeclaratorChunk I; |
1640 | I.Kind = Pipe; |
1641 | I.Loc = Loc; |
1642 | I.Cls.TypeQuals = TypeQuals; |
1643 | return I; |
1644 | } |
1645 | |
1646 | static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS, |
1647 | unsigned TypeQuals, |
1648 | SourceLocation Loc) { |
1649 | DeclaratorChunk I; |
1650 | I.Kind = MemberPointer; |
1651 | I.Loc = SS.getBeginLoc(); |
1652 | I.EndLoc = Loc; |
1653 | I.Mem.TypeQuals = TypeQuals; |
1654 | new (I.Mem.ScopeMem) CXXScopeSpec(SS); |
1655 | return I; |
1656 | } |
1657 | |
1658 | /// Return a DeclaratorChunk for a paren. |
1659 | static DeclaratorChunk getParen(SourceLocation LParenLoc, |
1660 | SourceLocation RParenLoc) { |
1661 | DeclaratorChunk I; |
1662 | I.Kind = Paren; |
1663 | I.Loc = LParenLoc; |
1664 | I.EndLoc = RParenLoc; |
1665 | return I; |
1666 | } |
1667 | |
1668 | bool isParen() const { |
1669 | return Kind == Paren; |
1670 | } |
1671 | }; |
1672 | |
1673 | /// A parsed C++17 decomposition declarator of the form |
1674 | /// '[' identifier-list ']' |
1675 | class DecompositionDeclarator { |
1676 | public: |
1677 | struct Binding { |
1678 | IdentifierInfo *Name; |
1679 | SourceLocation NameLoc; |
1680 | }; |
1681 | |
1682 | private: |
1683 | /// The locations of the '[' and ']' tokens. |
1684 | SourceLocation LSquareLoc, RSquareLoc; |
1685 | |
1686 | /// The bindings. |
1687 | Binding *Bindings; |
1688 | unsigned NumBindings : 31; |
1689 | unsigned DeleteBindings : 1; |
1690 | |
1691 | friend class Declarator; |
1692 | |
1693 | public: |
1694 | DecompositionDeclarator() |
1695 | : Bindings(nullptr), NumBindings(0), DeleteBindings(false) {} |
1696 | DecompositionDeclarator(const DecompositionDeclarator &G) = delete; |
1697 | DecompositionDeclarator &operator=(const DecompositionDeclarator &G) = delete; |
1698 | ~DecompositionDeclarator() { |
1699 | if (DeleteBindings) |
1700 | delete[] Bindings; |
1701 | } |
1702 | |
1703 | void clear() { |
1704 | LSquareLoc = RSquareLoc = SourceLocation(); |
1705 | if (DeleteBindings) |
1706 | delete[] Bindings; |
1707 | Bindings = nullptr; |
1708 | NumBindings = 0; |
1709 | DeleteBindings = false; |
1710 | } |
1711 | |
1712 | ArrayRef<Binding> bindings() const { |
1713 | return llvm::makeArrayRef(Bindings, NumBindings); |
1714 | } |
1715 | |
1716 | bool isSet() const { return LSquareLoc.isValid(); } |
1717 | |
1718 | SourceLocation getLSquareLoc() const { return LSquareLoc; } |
1719 | SourceLocation getRSquareLoc() const { return RSquareLoc; } |
1720 | SourceRange getSourceRange() const { |
1721 | return SourceRange(LSquareLoc, RSquareLoc); |
1722 | } |
1723 | }; |
1724 | |
1725 | /// Described the kind of function definition (if any) provided for |
1726 | /// a function. |
1727 | enum FunctionDefinitionKind { |
1728 | FDK_Declaration, |
1729 | FDK_Definition, |
1730 | FDK_Defaulted, |
1731 | FDK_Deleted |
1732 | }; |
1733 | |
1734 | enum class DeclaratorContext { |
1735 | FileContext, // File scope declaration. |
1736 | PrototypeContext, // Within a function prototype. |
1737 | ObjCResultContext, // An ObjC method result type. |
1738 | ObjCParameterContext,// An ObjC method parameter type. |
1739 | KNRTypeListContext, // K&R type definition list for formals. |
1740 | TypeNameContext, // Abstract declarator for types. |
1741 | FunctionalCastContext, // Type in a C++ functional cast expression. |
1742 | MemberContext, // Struct/Union field. |
1743 | BlockContext, // Declaration within a block in a function. |
1744 | ForContext, // Declaration within first part of a for loop. |
1745 | InitStmtContext, // Declaration within optional init stmt of if/switch. |
1746 | ConditionContext, // Condition declaration in a C++ if/switch/while/for. |
1747 | TemplateParamContext,// Within a template parameter list. |
1748 | CXXNewContext, // C++ new-expression. |
1749 | CXXCatchContext, // C++ catch exception-declaration |
1750 | ObjCCatchContext, // Objective-C catch exception-declaration |
1751 | BlockLiteralContext, // Block literal declarator. |
1752 | LambdaExprContext, // Lambda-expression declarator. |
1753 | LambdaExprParameterContext, // Lambda-expression parameter declarator. |
1754 | ConversionIdContext, // C++ conversion-type-id. |
1755 | TrailingReturnContext, // C++11 trailing-type-specifier. |
1756 | TrailingReturnVarContext, // C++11 trailing-type-specifier for variable. |
1757 | TemplateArgContext, // Any template argument (in template argument list). |
1758 | TemplateTypeArgContext, // Template type argument (in default argument). |
1759 | AliasDeclContext, // C++11 alias-declaration. |
1760 | AliasTemplateContext // C++11 alias-declaration template. |
1761 | }; |
1762 | |
1763 | |
1764 | /// Information about one declarator, including the parsed type |
1765 | /// information and the identifier. |
1766 | /// |
1767 | /// When the declarator is fully formed, this is turned into the appropriate |
1768 | /// Decl object. |
1769 | /// |
1770 | /// Declarators come in two types: normal declarators and abstract declarators. |
1771 | /// Abstract declarators are used when parsing types, and don't have an |
1772 | /// identifier. Normal declarators do have ID's. |
1773 | /// |
1774 | /// Instances of this class should be a transient object that lives on the |
1775 | /// stack, not objects that are allocated in large quantities on the heap. |
1776 | class Declarator { |
1777 | |
1778 | private: |
1779 | const DeclSpec &DS; |
1780 | CXXScopeSpec SS; |
1781 | UnqualifiedId Name; |
1782 | SourceRange Range; |
1783 | |
1784 | /// Where we are parsing this declarator. |
1785 | DeclaratorContext Context; |
1786 | |
1787 | /// The C++17 structured binding, if any. This is an alternative to a Name. |
1788 | DecompositionDeclarator BindingGroup; |
1789 | |
1790 | /// DeclTypeInfo - This holds each type that the declarator includes as it is |
1791 | /// parsed. This is pushed from the identifier out, which means that element |
1792 | /// #0 will be the most closely bound to the identifier, and |
1793 | /// DeclTypeInfo.back() will be the least closely bound. |
1794 | SmallVector<DeclaratorChunk, 8> DeclTypeInfo; |
1795 | |
1796 | /// InvalidType - Set by Sema::GetTypeForDeclarator(). |
1797 | unsigned InvalidType : 1; |
1798 | |
1799 | /// GroupingParens - Set by Parser::ParseParenDeclarator(). |
1800 | unsigned GroupingParens : 1; |
1801 | |
1802 | /// FunctionDefinition - Is this Declarator for a function or member |
1803 | /// definition and, if so, what kind? |
1804 | /// |
1805 | /// Actually a FunctionDefinitionKind. |
1806 | unsigned FunctionDefinition : 2; |
1807 | |
1808 | /// Is this Declarator a redeclaration? |
1809 | unsigned Redeclaration : 1; |
1810 | |
1811 | /// true if the declaration is preceded by \c __extension__. |
1812 | unsigned Extension : 1; |
1813 | |
1814 | /// Indicates whether this is an Objective-C instance variable. |
1815 | unsigned ObjCIvar : 1; |
1816 | |
1817 | /// Indicates whether this is an Objective-C 'weak' property. |
1818 | unsigned ObjCWeakProperty : 1; |
1819 | |
1820 | /// Indicates whether the InlineParams / InlineBindings storage has been used. |
1821 | unsigned InlineStorageUsed : 1; |
1822 | |
1823 | /// Attrs - Attributes. |
1824 | ParsedAttributes Attrs; |
1825 | |
1826 | /// The asm label, if specified. |
1827 | Expr *AsmLabel; |
1828 | |
1829 | /// \brief The constraint-expression specified by the trailing |
1830 | /// requires-clause, or null if no such clause was specified. |
1831 | Expr *TrailingRequiresClause; |
1832 | |
1833 | #ifndef _MSC_VER |
1834 | union { |
1835 | #endif |
1836 | /// InlineParams - This is a local array used for the first function decl |
1837 | /// chunk to avoid going to the heap for the common case when we have one |
1838 | /// function chunk in the declarator. |
1839 | DeclaratorChunk::ParamInfo InlineParams[16]; |
1840 | DecompositionDeclarator::Binding InlineBindings[16]; |
1841 | #ifndef _MSC_VER |
1842 | }; |
1843 | #endif |
1844 | |
1845 | /// If this is the second or subsequent declarator in this declaration, |
1846 | /// the location of the comma before this declarator. |
1847 | SourceLocation CommaLoc; |
1848 | |
1849 | /// If provided, the source location of the ellipsis used to describe |
1850 | /// this declarator as a parameter pack. |
1851 | SourceLocation EllipsisLoc; |
1852 | |
1853 | friend struct DeclaratorChunk; |
1854 | |
1855 | public: |
1856 | Declarator(const DeclSpec &ds, DeclaratorContext C) |
1857 | : DS(ds), Range(ds.getSourceRange()), Context(C), |
1858 | InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error), |
1859 | GroupingParens(false), FunctionDefinition(FDK_Declaration), |
1860 | Redeclaration(false), Extension(false), ObjCIvar(false), |
1861 | ObjCWeakProperty(false), InlineStorageUsed(false), |
1862 | Attrs(ds.getAttributePool().getFactory()), AsmLabel(nullptr), |
1863 | TrailingRequiresClause(nullptr) {} |
1864 | |
1865 | ~Declarator() { |
1866 | clear(); |
1867 | } |
1868 | /// getDeclSpec - Return the declaration-specifier that this declarator was |
1869 | /// declared with. |
1870 | const DeclSpec &getDeclSpec() const { return DS; } |
1871 | |
1872 | /// getMutableDeclSpec - Return a non-const version of the DeclSpec. This |
1873 | /// should be used with extreme care: declspecs can often be shared between |
1874 | /// multiple declarators, so mutating the DeclSpec affects all of the |
1875 | /// Declarators. This should only be done when the declspec is known to not |
1876 | /// be shared or when in error recovery etc. |
1877 | DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); } |
1878 | |
1879 | AttributePool &getAttributePool() const { |
1880 | return Attrs.getPool(); |
1881 | } |
1882 | |
1883 | /// getCXXScopeSpec - Return the C++ scope specifier (global scope or |
1884 | /// nested-name-specifier) that is part of the declarator-id. |
1885 | const CXXScopeSpec &getCXXScopeSpec() const { return SS; } |
1886 | CXXScopeSpec &getCXXScopeSpec() { return SS; } |
1887 | |
1888 | /// Retrieve the name specified by this declarator. |
1889 | UnqualifiedId &getName() { return Name; } |
1890 | |
1891 | const DecompositionDeclarator &getDecompositionDeclarator() const { |
1892 | return BindingGroup; |
1893 | } |
1894 | |
1895 | DeclaratorContext getContext() const { return Context; } |
1896 | |
1897 | bool isPrototypeContext() const { |
1898 | return (Context == DeclaratorContext::PrototypeContext || |
1899 | Context == DeclaratorContext::ObjCParameterContext || |
1900 | Context == DeclaratorContext::ObjCResultContext || |
1901 | Context == DeclaratorContext::LambdaExprParameterContext); |
1902 | } |
1903 | |
1904 | /// Get the source range that spans this declarator. |
1905 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; } |
1906 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); } |
1907 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); } |
1908 | |
1909 | void SetSourceRange(SourceRange R) { Range = R; } |
1910 | /// SetRangeBegin - Set the start of the source range to Loc, unless it's |
1911 | /// invalid. |
1912 | void SetRangeBegin(SourceLocation Loc) { |
1913 | if (!Loc.isInvalid()) |
1914 | Range.setBegin(Loc); |
1915 | } |
1916 | /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid. |
1917 | void SetRangeEnd(SourceLocation Loc) { |
1918 | if (!Loc.isInvalid()) |
1919 | Range.setEnd(Loc); |
1920 | } |
1921 | /// ExtendWithDeclSpec - Extend the declarator source range to include the |
1922 | /// given declspec, unless its location is invalid. Adopts the range start if |
1923 | /// the current range start is invalid. |
1924 | void ExtendWithDeclSpec(const DeclSpec &DS) { |
1925 | SourceRange SR = DS.getSourceRange(); |
1926 | if (Range.getBegin().isInvalid()) |
1927 | Range.setBegin(SR.getBegin()); |
1928 | if (!SR.getEnd().isInvalid()) |
1929 | Range.setEnd(SR.getEnd()); |
1930 | } |
1931 | |
1932 | /// Reset the contents of this Declarator. |
1933 | void clear() { |
1934 | SS.clear(); |
1935 | Name.clear(); |
1936 | Range = DS.getSourceRange(); |
1937 | BindingGroup.clear(); |
1938 | |
1939 | for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i) |
1940 | DeclTypeInfo[i].destroy(); |
1941 | DeclTypeInfo.clear(); |
1942 | Attrs.clear(); |
1943 | AsmLabel = nullptr; |
1944 | InlineStorageUsed = false; |
1945 | ObjCIvar = false; |
1946 | ObjCWeakProperty = false; |
1947 | CommaLoc = SourceLocation(); |
1948 | EllipsisLoc = SourceLocation(); |
1949 | } |
1950 | |
1951 | /// mayOmitIdentifier - Return true if the identifier is either optional or |
1952 | /// not allowed. This is true for typenames, prototypes, and template |
1953 | /// parameter lists. |
1954 | bool mayOmitIdentifier() const { |
1955 | switch (Context) { |
1956 | case DeclaratorContext::FileContext: |
1957 | case DeclaratorContext::KNRTypeListContext: |
1958 | case DeclaratorContext::MemberContext: |
1959 | case DeclaratorContext::BlockContext: |
1960 | case DeclaratorContext::ForContext: |
1961 | case DeclaratorContext::InitStmtContext: |
1962 | case DeclaratorContext::ConditionContext: |
1963 | return false; |
1964 | |
1965 | case DeclaratorContext::TypeNameContext: |
1966 | case DeclaratorContext::FunctionalCastContext: |
1967 | case DeclaratorContext::AliasDeclContext: |
1968 | case DeclaratorContext::AliasTemplateContext: |
1969 | case DeclaratorContext::PrototypeContext: |
1970 | case DeclaratorContext::LambdaExprParameterContext: |
1971 | case DeclaratorContext::ObjCParameterContext: |
1972 | case DeclaratorContext::ObjCResultContext: |
1973 | case DeclaratorContext::TemplateParamContext: |
1974 | case DeclaratorContext::CXXNewContext: |
1975 | case DeclaratorContext::CXXCatchContext: |
1976 | case DeclaratorContext::ObjCCatchContext: |
1977 | case DeclaratorContext::BlockLiteralContext: |
1978 | case DeclaratorContext::LambdaExprContext: |
1979 | case DeclaratorContext::ConversionIdContext: |
1980 | case DeclaratorContext::TemplateArgContext: |
1981 | case DeclaratorContext::TemplateTypeArgContext: |
1982 | case DeclaratorContext::TrailingReturnContext: |
1983 | case DeclaratorContext::TrailingReturnVarContext: |
1984 | return true; |
1985 | } |
1986 | llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 1986); |
1987 | } |
1988 | |
1989 | /// mayHaveIdentifier - Return true if the identifier is either optional or |
1990 | /// required. This is true for normal declarators and prototypes, but not |
1991 | /// typenames. |
1992 | bool mayHaveIdentifier() const { |
1993 | switch (Context) { |
1994 | case DeclaratorContext::FileContext: |
1995 | case DeclaratorContext::KNRTypeListContext: |
1996 | case DeclaratorContext::MemberContext: |
1997 | case DeclaratorContext::BlockContext: |
1998 | case DeclaratorContext::ForContext: |
1999 | case DeclaratorContext::InitStmtContext: |
2000 | case DeclaratorContext::ConditionContext: |
2001 | case DeclaratorContext::PrototypeContext: |
2002 | case DeclaratorContext::LambdaExprParameterContext: |
2003 | case DeclaratorContext::TemplateParamContext: |
2004 | case DeclaratorContext::CXXCatchContext: |
2005 | case DeclaratorContext::ObjCCatchContext: |
2006 | return true; |
2007 | |
2008 | case DeclaratorContext::TypeNameContext: |
2009 | case DeclaratorContext::FunctionalCastContext: |
2010 | case DeclaratorContext::CXXNewContext: |
2011 | case DeclaratorContext::AliasDeclContext: |
2012 | case DeclaratorContext::AliasTemplateContext: |
2013 | case DeclaratorContext::ObjCParameterContext: |
2014 | case DeclaratorContext::ObjCResultContext: |
2015 | case DeclaratorContext::BlockLiteralContext: |
2016 | case DeclaratorContext::LambdaExprContext: |
2017 | case DeclaratorContext::ConversionIdContext: |
2018 | case DeclaratorContext::TemplateArgContext: |
2019 | case DeclaratorContext::TemplateTypeArgContext: |
2020 | case DeclaratorContext::TrailingReturnContext: |
2021 | case DeclaratorContext::TrailingReturnVarContext: |
2022 | return false; |
2023 | } |
2024 | llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 2024); |
2025 | } |
2026 | |
2027 | /// Return true if the context permits a C++17 decomposition declarator. |
2028 | bool mayHaveDecompositionDeclarator() const { |
2029 | switch (Context) { |
2030 | case DeclaratorContext::FileContext: |
2031 | // FIXME: It's not clear that the proposal meant to allow file-scope |
2032 | // structured bindings, but it does. |
2033 | case DeclaratorContext::BlockContext: |
2034 | case DeclaratorContext::ForContext: |
2035 | case DeclaratorContext::InitStmtContext: |
2036 | case DeclaratorContext::ConditionContext: |
2037 | return true; |
2038 | |
2039 | case DeclaratorContext::MemberContext: |
2040 | case DeclaratorContext::PrototypeContext: |
2041 | case DeclaratorContext::TemplateParamContext: |
2042 | // Maybe one day... |
2043 | return false; |
2044 | |
2045 | // These contexts don't allow any kind of non-abstract declarator. |
2046 | case DeclaratorContext::KNRTypeListContext: |
2047 | case DeclaratorContext::TypeNameContext: |
2048 | case DeclaratorContext::FunctionalCastContext: |
2049 | case DeclaratorContext::AliasDeclContext: |
2050 | case DeclaratorContext::AliasTemplateContext: |
2051 | case DeclaratorContext::LambdaExprParameterContext: |
2052 | case DeclaratorContext::ObjCParameterContext: |
2053 | case DeclaratorContext::ObjCResultContext: |
2054 | case DeclaratorContext::CXXNewContext: |
2055 | case DeclaratorContext::CXXCatchContext: |
2056 | case DeclaratorContext::ObjCCatchContext: |
2057 | case DeclaratorContext::BlockLiteralContext: |
2058 | case DeclaratorContext::LambdaExprContext: |
2059 | case DeclaratorContext::ConversionIdContext: |
2060 | case DeclaratorContext::TemplateArgContext: |
2061 | case DeclaratorContext::TemplateTypeArgContext: |
2062 | case DeclaratorContext::TrailingReturnContext: |
2063 | case DeclaratorContext::TrailingReturnVarContext: |
2064 | return false; |
2065 | } |
2066 | llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 2066); |
2067 | } |
2068 | |
2069 | /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be |
2070 | /// followed by a C++ direct initializer, e.g. "int x(1);". |
2071 | bool mayBeFollowedByCXXDirectInit() const { |
2072 | if (hasGroupingParens()) return false; |
2073 | |
2074 | if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) |
2075 | return false; |
2076 | |
2077 | if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern && |
2078 | Context != DeclaratorContext::FileContext) |
2079 | return false; |
2080 | |
2081 | // Special names can't have direct initializers. |
2082 | if (Name.getKind() != UnqualifiedIdKind::IK_Identifier) |
2083 | return false; |
2084 | |
2085 | switch (Context) { |
2086 | case DeclaratorContext::FileContext: |
2087 | case DeclaratorContext::BlockContext: |
2088 | case DeclaratorContext::ForContext: |
2089 | case DeclaratorContext::InitStmtContext: |
2090 | case DeclaratorContext::TrailingReturnVarContext: |
2091 | return true; |
2092 | |
2093 | case DeclaratorContext::ConditionContext: |
2094 | // This may not be followed by a direct initializer, but it can't be a |
2095 | // function declaration either, and we'd prefer to perform a tentative |
2096 | // parse in order to produce the right diagnostic. |
2097 | return true; |
2098 | |
2099 | case DeclaratorContext::KNRTypeListContext: |
2100 | case DeclaratorContext::MemberContext: |
2101 | case DeclaratorContext::PrototypeContext: |
2102 | case DeclaratorContext::LambdaExprParameterContext: |
2103 | case DeclaratorContext::ObjCParameterContext: |
2104 | case DeclaratorContext::ObjCResultContext: |
2105 | case DeclaratorContext::TemplateParamContext: |
2106 | case DeclaratorContext::CXXCatchContext: |
2107 | case DeclaratorContext::ObjCCatchContext: |
2108 | case DeclaratorContext::TypeNameContext: |
2109 | case DeclaratorContext::FunctionalCastContext: // FIXME |
2110 | case DeclaratorContext::CXXNewContext: |
2111 | case DeclaratorContext::AliasDeclContext: |
2112 | case DeclaratorContext::AliasTemplateContext: |
2113 | case DeclaratorContext::BlockLiteralContext: |
2114 | case DeclaratorContext::LambdaExprContext: |
2115 | case DeclaratorContext::ConversionIdContext: |
2116 | case DeclaratorContext::TemplateArgContext: |
2117 | case DeclaratorContext::TemplateTypeArgContext: |
2118 | case DeclaratorContext::TrailingReturnContext: |
2119 | return false; |
2120 | } |
2121 | llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 2121); |
2122 | } |
2123 | |
2124 | /// isPastIdentifier - Return true if we have parsed beyond the point where |
2125 | /// the name would appear. (This may happen even if we haven't actually parsed |
2126 | /// a name, perhaps because this context doesn't require one.) |
2127 | bool isPastIdentifier() const { return Name.isValid(); } |
2128 | |
2129 | /// hasName - Whether this declarator has a name, which might be an |
2130 | /// identifier (accessible via getIdentifier()) or some kind of |
2131 | /// special C++ name (constructor, destructor, etc.), or a structured |
2132 | /// binding (which is not exactly a name, but occupies the same position). |
2133 | bool hasName() const { |
2134 | return Name.getKind() != UnqualifiedIdKind::IK_Identifier || |
2135 | Name.Identifier || isDecompositionDeclarator(); |
2136 | } |
2137 | |
2138 | /// Return whether this declarator is a decomposition declarator. |
2139 | bool isDecompositionDeclarator() const { |
2140 | return BindingGroup.isSet(); |
2141 | } |
2142 | |
2143 | IdentifierInfo *getIdentifier() const { |
2144 | if (Name.getKind() == UnqualifiedIdKind::IK_Identifier) |
2145 | return Name.Identifier; |
2146 | |
2147 | return nullptr; |
2148 | } |
2149 | SourceLocation getIdentifierLoc() const { return Name.StartLocation; } |
2150 | |
2151 | /// Set the name of this declarator to be the given identifier. |
2152 | void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) { |
2153 | Name.setIdentifier(Id, IdLoc); |
2154 | } |
2155 | |
2156 | /// Set the decomposition bindings for this declarator. |
2157 | void |
2158 | setDecompositionBindings(SourceLocation LSquareLoc, |
2159 | ArrayRef<DecompositionDeclarator::Binding> Bindings, |
2160 | SourceLocation RSquareLoc); |
2161 | |
2162 | /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to |
2163 | /// EndLoc, which should be the last token of the chunk. |
2164 | /// This function takes attrs by R-Value reference because it takes ownership |
2165 | /// of those attributes from the parameter. |
2166 | void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, |
2167 | SourceLocation EndLoc) { |
2168 | DeclTypeInfo.push_back(TI); |
2169 | DeclTypeInfo.back().getAttrs().addAll(attrs.begin(), attrs.end()); |
2170 | getAttributePool().takeAllFrom(attrs.getPool()); |
2171 | |
2172 | if (!EndLoc.isInvalid()) |
2173 | SetRangeEnd(EndLoc); |
2174 | } |
2175 | |
2176 | /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to |
2177 | /// EndLoc, which should be the last token of the chunk. |
2178 | void AddTypeInfo(const DeclaratorChunk &TI, SourceLocation EndLoc) { |
2179 | DeclTypeInfo.push_back(TI); |
2180 | |
2181 | if (!EndLoc.isInvalid()) |
2182 | SetRangeEnd(EndLoc); |
2183 | } |
2184 | |
2185 | /// Add a new innermost chunk to this declarator. |
2186 | void AddInnermostTypeInfo(const DeclaratorChunk &TI) { |
2187 | DeclTypeInfo.insert(DeclTypeInfo.begin(), TI); |
2188 | } |
2189 | |
2190 | /// Return the number of types applied to this declarator. |
2191 | unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); } |
2192 | |
2193 | /// Return the specified TypeInfo from this declarator. TypeInfo #0 is |
2194 | /// closest to the identifier. |
2195 | const DeclaratorChunk &getTypeObject(unsigned i) const { |
2196 | assert(i < DeclTypeInfo.size() && "Invalid type chunk")((i < DeclTypeInfo.size() && "Invalid type chunk") ? static_cast<void> (0) : __assert_fail ("i < DeclTypeInfo.size() && \"Invalid type chunk\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 2196, __PRETTY_FUNCTION__)); |
2197 | return DeclTypeInfo[i]; |
2198 | } |
2199 | DeclaratorChunk &getTypeObject(unsigned i) { |
2200 | assert(i < DeclTypeInfo.size() && "Invalid type chunk")((i < DeclTypeInfo.size() && "Invalid type chunk") ? static_cast<void> (0) : __assert_fail ("i < DeclTypeInfo.size() && \"Invalid type chunk\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 2200, __PRETTY_FUNCTION__)); |
2201 | return DeclTypeInfo[i]; |
2202 | } |
2203 | |
2204 | typedef SmallVectorImpl<DeclaratorChunk>::const_iterator type_object_iterator; |
2205 | typedef llvm::iterator_range<type_object_iterator> type_object_range; |
2206 | |
2207 | /// Returns the range of type objects, from the identifier outwards. |
2208 | type_object_range type_objects() const { |
2209 | return type_object_range(DeclTypeInfo.begin(), DeclTypeInfo.end()); |
2210 | } |
2211 | |
2212 | void DropFirstTypeObject() { |
2213 | assert(!DeclTypeInfo.empty() && "No type chunks to drop.")((!DeclTypeInfo.empty() && "No type chunks to drop.") ? static_cast<void> (0) : __assert_fail ("!DeclTypeInfo.empty() && \"No type chunks to drop.\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 2213, __PRETTY_FUNCTION__)); |
2214 | DeclTypeInfo.front().destroy(); |
2215 | DeclTypeInfo.erase(DeclTypeInfo.begin()); |
2216 | } |
2217 | |
2218 | /// Return the innermost (closest to the declarator) chunk of this |
2219 | /// declarator that is not a parens chunk, or null if there are no |
2220 | /// non-parens chunks. |
2221 | const DeclaratorChunk *getInnermostNonParenChunk() const { |
2222 | for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) { |
2223 | if (!DeclTypeInfo[i].isParen()) |
2224 | return &DeclTypeInfo[i]; |
2225 | } |
2226 | return nullptr; |
2227 | } |
2228 | |
2229 | /// Return the outermost (furthest from the declarator) chunk of |
2230 | /// this declarator that is not a parens chunk, or null if there are |
2231 | /// no non-parens chunks. |
2232 | const DeclaratorChunk *getOutermostNonParenChunk() const { |
2233 | for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) { |
2234 | if (!DeclTypeInfo[i-1].isParen()) |
2235 | return &DeclTypeInfo[i-1]; |
2236 | } |
2237 | return nullptr; |
2238 | } |
2239 | |
2240 | /// isArrayOfUnknownBound - This method returns true if the declarator |
2241 | /// is a declarator for an array of unknown bound (looking through |
2242 | /// parentheses). |
2243 | bool isArrayOfUnknownBound() const { |
2244 | const DeclaratorChunk *chunk = getInnermostNonParenChunk(); |
2245 | return (chunk && chunk->Kind == DeclaratorChunk::Array && |
2246 | !chunk->Arr.NumElts); |
2247 | } |
2248 | |
2249 | /// isFunctionDeclarator - This method returns true if the declarator |
2250 | /// is a function declarator (looking through parentheses). |
2251 | /// If true is returned, then the reference type parameter idx is |
2252 | /// assigned with the index of the declaration chunk. |
2253 | bool isFunctionDeclarator(unsigned& idx) const { |
2254 | for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) { |
2255 | switch (DeclTypeInfo[i].Kind) { |
2256 | case DeclaratorChunk::Function: |
2257 | idx = i; |
2258 | return true; |
2259 | case DeclaratorChunk::Paren: |
2260 | continue; |
2261 | case DeclaratorChunk::Pointer: |
2262 | case DeclaratorChunk::Reference: |
2263 | case DeclaratorChunk::Array: |
2264 | case DeclaratorChunk::BlockPointer: |
2265 | case DeclaratorChunk::MemberPointer: |
2266 | case DeclaratorChunk::Pipe: |
2267 | return false; |
2268 | } |
2269 | llvm_unreachable("Invalid type chunk")::llvm::llvm_unreachable_internal("Invalid type chunk", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 2269); |
2270 | } |
2271 | return false; |
2272 | } |
2273 | |
2274 | /// isFunctionDeclarator - Once this declarator is fully parsed and formed, |
2275 | /// this method returns true if the identifier is a function declarator |
2276 | /// (looking through parentheses). |
2277 | bool isFunctionDeclarator() const { |
2278 | unsigned index; |
2279 | return isFunctionDeclarator(index); |
2280 | } |
2281 | |
2282 | /// getFunctionTypeInfo - Retrieves the function type info object |
2283 | /// (looking through parentheses). |
2284 | DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() { |
2285 | assert(isFunctionDeclarator() && "Not a function declarator!")((isFunctionDeclarator() && "Not a function declarator!" ) ? static_cast<void> (0) : __assert_fail ("isFunctionDeclarator() && \"Not a function declarator!\"" , "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 2285, __PRETTY_FUNCTION__)); |
2286 | unsigned index = 0; |
2287 | isFunctionDeclarator(index); |
2288 | return DeclTypeInfo[index].Fun; |
2289 | } |
2290 | |
2291 | /// getFunctionTypeInfo - Retrieves the function type info object |
2292 | /// (looking through parentheses). |
2293 | const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const { |
2294 | return const_cast<Declarator*>(this)->getFunctionTypeInfo(); |
2295 | } |
2296 | |
2297 | /// Determine whether the declaration that will be produced from |
2298 | /// this declaration will be a function. |
2299 | /// |
2300 | /// A declaration can declare a function even if the declarator itself |
2301 | /// isn't a function declarator, if the type specifier refers to a function |
2302 | /// type. This routine checks for both cases. |
2303 | bool isDeclarationOfFunction() const; |
2304 | |
2305 | /// Return true if this declaration appears in a context where a |
2306 | /// function declarator would be a function declaration. |
2307 | bool isFunctionDeclarationContext() const { |
2308 | if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) |
2309 | return false; |
2310 | |
2311 | switch (Context) { |
2312 | case DeclaratorContext::FileContext: |
2313 | case DeclaratorContext::MemberContext: |
2314 | case DeclaratorContext::BlockContext: |
2315 | case DeclaratorContext::ForContext: |
2316 | case DeclaratorContext::InitStmtContext: |
2317 | return true; |
2318 | |
2319 | case DeclaratorContext::ConditionContext: |
2320 | case DeclaratorContext::KNRTypeListContext: |
2321 | case DeclaratorContext::TypeNameContext: |
2322 | case DeclaratorContext::FunctionalCastContext: |
2323 | case DeclaratorContext::AliasDeclContext: |
2324 | case DeclaratorContext::AliasTemplateContext: |
2325 | case DeclaratorContext::PrototypeContext: |
2326 | case DeclaratorContext::LambdaExprParameterContext: |
2327 | case DeclaratorContext::ObjCParameterContext: |
2328 | case DeclaratorContext::ObjCResultContext: |
2329 | case DeclaratorContext::TemplateParamContext: |
2330 | case DeclaratorContext::CXXNewContext: |
2331 | case DeclaratorContext::CXXCatchContext: |
2332 | case DeclaratorContext::ObjCCatchContext: |
2333 | case DeclaratorContext::BlockLiteralContext: |
2334 | case DeclaratorContext::LambdaExprContext: |
2335 | case DeclaratorContext::ConversionIdContext: |
2336 | case DeclaratorContext::TemplateArgContext: |
2337 | case DeclaratorContext::TemplateTypeArgContext: |
2338 | case DeclaratorContext::TrailingReturnContext: |
2339 | case DeclaratorContext::TrailingReturnVarContext: |
2340 | return false; |
2341 | } |
2342 | llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 2342); |
2343 | } |
2344 | |
2345 | /// Determine whether this declaration appears in a context where an |
2346 | /// expression could appear. |
2347 | bool isExpressionContext() const { |
2348 | switch (Context) { |
2349 | case DeclaratorContext::FileContext: |
2350 | case DeclaratorContext::KNRTypeListContext: |
2351 | case DeclaratorContext::MemberContext: |
2352 | |
2353 | // FIXME: sizeof(...) permits an expression. |
2354 | case DeclaratorContext::TypeNameContext: |
2355 | |
2356 | case DeclaratorContext::FunctionalCastContext: |
2357 | case DeclaratorContext::AliasDeclContext: |
2358 | case DeclaratorContext::AliasTemplateContext: |
2359 | case DeclaratorContext::PrototypeContext: |
2360 | case DeclaratorContext::LambdaExprParameterContext: |
2361 | case DeclaratorContext::ObjCParameterContext: |
2362 | case DeclaratorContext::ObjCResultContext: |
2363 | case DeclaratorContext::TemplateParamContext: |
2364 | case DeclaratorContext::CXXNewContext: |
2365 | case DeclaratorContext::CXXCatchContext: |
2366 | case DeclaratorContext::ObjCCatchContext: |
2367 | case DeclaratorContext::BlockLiteralContext: |
2368 | case DeclaratorContext::LambdaExprContext: |
2369 | case DeclaratorContext::ConversionIdContext: |
2370 | case DeclaratorContext::TrailingReturnContext: |
2371 | case DeclaratorContext::TrailingReturnVarContext: |
2372 | case DeclaratorContext::TemplateTypeArgContext: |
2373 | return false; |
2374 | |
2375 | case DeclaratorContext::BlockContext: |
2376 | case DeclaratorContext::ForContext: |
2377 | case DeclaratorContext::InitStmtContext: |
2378 | case DeclaratorContext::ConditionContext: |
2379 | case DeclaratorContext::TemplateArgContext: |
2380 | return true; |
2381 | } |
2382 | |
2383 | llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include/clang/Sema/DeclSpec.h" , 2383); |
2384 | } |
2385 | |
2386 | /// Return true if a function declarator at this position would be a |
2387 | /// function declaration. |
2388 | bool isFunctionDeclaratorAFunctionDeclaration() const { |
2389 | if (!isFunctionDeclarationContext()) |
2390 | return false; |
2391 | |
2392 | for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I) |
2393 | if (getTypeObject(I).Kind != DeclaratorChunk::Paren) |
2394 | return false; |
2395 | |
2396 | return true; |
2397 | } |
2398 | |
2399 | /// Determine whether a trailing return type was written (at any |
2400 | /// level) within this declarator. |
2401 | bool hasTrailingReturnType() const { |
2402 | for (const auto &Chunk : type_objects()) |
2403 | if (Chunk.Kind == DeclaratorChunk::Function && |
2404 | Chunk.Fun.hasTrailingReturnType()) |
2405 | return true; |
2406 | return false; |
2407 | } |
2408 | |
2409 | /// \brief Sets a trailing requires clause for this declarator. |
2410 | void setTrailingRequiresClause(Expr *TRC) { |
2411 | TrailingRequiresClause = TRC; |
2412 | } |
2413 | |
2414 | /// \brief Sets a trailing requires clause for this declarator. |
2415 | Expr *getTrailingRequiresClause() { |
2416 | return TrailingRequiresClause; |
2417 | } |
2418 | |
2419 | /// \brief Determine whether a trailing requires clause was written in this |
2420 | /// declarator. |
2421 | bool hasTrailingRequiresClause() const { |
2422 | return TrailingRequiresClause != nullptr; |
2423 | } |
2424 | |
2425 | /// takeAttributes - Takes attributes from the given parsed-attributes |
2426 | /// set and add them to this declarator. |
2427 | /// |
2428 | /// These examples both add 3 attributes to "var": |
2429 | /// short int var __attribute__((aligned(16),common,deprecated)); |
2430 | /// short int x, __attribute__((aligned(16)) var |
2431 | /// __attribute__((common,deprecated)); |
2432 | /// |
2433 | /// Also extends the range of the declarator. |
2434 | void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc) { |
2435 | Attrs.takeAllFrom(attrs); |
2436 | |
2437 | if (!lastLoc.isInvalid()) |
2438 | SetRangeEnd(lastLoc); |
2439 | } |
2440 | |
2441 | const ParsedAttributes &getAttributes() const { return Attrs; } |
2442 | ParsedAttributes &getAttributes() { return Attrs; } |
2443 | |
2444 | /// hasAttributes - do we contain any attributes? |
2445 | bool hasAttributes() const { |
2446 | if (!getAttributes().empty() || getDeclSpec().hasAttributes()) |
2447 | return true; |
2448 | for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i) |
2449 | if (!getTypeObject(i).getAttrs().empty()) |
2450 | return true; |
2451 | return false; |
2452 | } |
2453 | |
2454 | /// Return a source range list of C++11 attributes associated |
2455 | /// with the declarator. |
2456 | void getCXX11AttributeRanges(SmallVectorImpl<SourceRange> &Ranges) { |
2457 | for (const ParsedAttr &AL : Attrs) |
2458 | if (AL.isCXX11Attribute()) |
2459 | Ranges.push_back(AL.getRange()); |
2460 | } |
2461 | |
2462 | void setAsmLabel(Expr *E) { AsmLabel = E; } |
2463 | Expr *getAsmLabel() const { return AsmLabel; } |
2464 | |
2465 | void setExtension(bool Val = true) { Extension = Val; } |
2466 | bool getExtension() const { return Extension; } |
2467 | |
2468 | void setObjCIvar(bool Val = true) { ObjCIvar = Val; } |
2469 | bool isObjCIvar() const { return ObjCIvar; } |
2470 | |
2471 | void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; } |
2472 | bool isObjCWeakProperty() const { return ObjCWeakProperty; } |
2473 | |
2474 | void setInvalidType(bool Val = true) { InvalidType = Val; } |
2475 | bool isInvalidType() const { |
2476 | return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error; |
2477 | } |
2478 | |
2479 | void setGroupingParens(bool flag) { GroupingParens = flag; } |
2480 | bool hasGroupingParens() const { return GroupingParens; } |
2481 | |
2482 | bool isFirstDeclarator() const { return !CommaLoc.isValid(); } |
2483 | SourceLocation getCommaLoc() const { return CommaLoc; } |
2484 | void setCommaLoc(SourceLocation CL) { CommaLoc = CL; } |
2485 | |
2486 | bool hasEllipsis() const { return EllipsisLoc.isValid(); } |
2487 | SourceLocation getEllipsisLoc() const { return EllipsisLoc; } |
2488 | void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; } |
2489 | |
2490 | void setFunctionDefinitionKind(FunctionDefinitionKind Val) { |
2491 | FunctionDefinition = Val; |
2492 | } |
2493 | |
2494 | bool isFunctionDefinition() const { |
2495 | return getFunctionDefinitionKind() != FDK_Declaration; |
2496 | } |
2497 | |
2498 | FunctionDefinitionKind getFunctionDefinitionKind() const { |
2499 | return (FunctionDefinitionKind)FunctionDefinition; |
2500 | } |
2501 | |
2502 | /// Returns true if this declares a real member and not a friend. |
2503 | bool isFirstDeclarationOfMember() { |
2504 | return getContext() == DeclaratorContext::MemberContext && |
2505 | !getDeclSpec().isFriendSpecified(); |
2506 | } |
2507 | |
2508 | /// Returns true if this declares a static member. This cannot be called on a |
2509 | /// declarator outside of a MemberContext because we won't know until |
2510 | /// redeclaration time if the decl is static. |
2511 | bool isStaticMember(); |
2512 | |
2513 | /// Returns true if this declares a constructor or a destructor. |
2514 | bool isCtorOrDtor(); |
2515 | |
2516 | void setRedeclaration(bool Val) { Redeclaration = Val; } |
2517 | bool isRedeclaration() const { return Redeclaration; } |
2518 | }; |
2519 | |
2520 | /// This little struct is used to capture information about |
2521 | /// structure field declarators, which is basically just a bitfield size. |
2522 | struct FieldDeclarator { |
2523 | Declarator D; |
2524 | Expr *BitfieldSize; |
2525 | explicit FieldDeclarator(const DeclSpec &DS) |
2526 | : D(DS, DeclaratorContext::MemberContext), |
2527 | BitfieldSize(nullptr) {} |
2528 | }; |
2529 | |
2530 | /// Represents a C++11 virt-specifier-seq. |
2531 | class VirtSpecifiers { |
2532 | public: |
2533 | enum Specifier { |
2534 | VS_None = 0, |
2535 | VS_Override = 1, |
2536 | VS_Final = 2, |
2537 | VS_Sealed = 4, |
2538 | // Represents the __final keyword, which is legal for gcc in pre-C++11 mode. |
2539 | VS_GNU_Final = 8 |
2540 | }; |
2541 | |
2542 | VirtSpecifiers() : Specifiers(0), LastSpecifier(VS_None) { } |
2543 | |
2544 | bool SetSpecifier(Specifier VS, SourceLocation Loc, |
2545 | const char *&PrevSpec); |
2546 | |
2547 | bool isUnset() const { return Specifiers == 0; } |
2548 | |
2549 | bool isOverrideSpecified() const { return Specifiers & VS_Override; } |
2550 | SourceLocation getOverrideLoc() const { return VS_overrideLoc; } |
2551 | |
2552 | bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed | VS_GNU_Final); } |
2553 | bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; } |
2554 | SourceLocation getFinalLoc() const { return VS_finalLoc; } |
2555 | |
2556 | void clear() { Specifiers = 0; } |
2557 | |
2558 | static const char *getSpecifierName(Specifier VS); |
2559 | |
2560 | SourceLocation getFirstLocation() const { return FirstLocation; } |
2561 | SourceLocation getLastLocation() const { return LastLocation; } |
2562 | Specifier getLastSpecifier() const { return LastSpecifier; } |
2563 | |
2564 | private: |
2565 | unsigned Specifiers; |
2566 | Specifier LastSpecifier; |
2567 | |
2568 | SourceLocation VS_overrideLoc, VS_finalLoc; |
2569 | SourceLocation FirstLocation; |
2570 | SourceLocation LastLocation; |
2571 | }; |
2572 | |
2573 | enum class LambdaCaptureInitKind { |
2574 | NoInit, //!< [a] |
2575 | CopyInit, //!< [a = b], [a = {b}] |
2576 | DirectInit, //!< [a(b)] |
2577 | ListInit //!< [a{b}] |
2578 | }; |
2579 | |
2580 | /// Represents a complete lambda introducer. |
2581 | struct LambdaIntroducer { |
2582 | /// An individual capture in a lambda introducer. |
2583 | struct LambdaCapture { |
2584 | LambdaCaptureKind Kind; |
2585 | SourceLocation Loc; |
2586 | IdentifierInfo *Id; |
2587 | SourceLocation EllipsisLoc; |
2588 | LambdaCaptureInitKind InitKind; |
2589 | ExprResult Init; |
2590 | ParsedType InitCaptureType; |
2591 | SourceRange ExplicitRange; |
2592 | |
2593 | LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc, |
2594 | IdentifierInfo *Id, SourceLocation EllipsisLoc, |
2595 | LambdaCaptureInitKind InitKind, ExprResult Init, |
2596 | ParsedType InitCaptureType, |
2597 | SourceRange ExplicitRange) |
2598 | : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc), |
2599 | InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType), |
2600 | ExplicitRange(ExplicitRange) {} |
2601 | }; |
2602 | |
2603 | SourceRange Range; |
2604 | SourceLocation DefaultLoc; |
2605 | LambdaCaptureDefault Default; |
2606 | SmallVector<LambdaCapture, 4> Captures; |
2607 | |
2608 | LambdaIntroducer() |
2609 | : Default(LCD_None) {} |
2610 | |
2611 | /// Append a capture in a lambda introducer. |
2612 | void addCapture(LambdaCaptureKind Kind, |
2613 | SourceLocation Loc, |
2614 | IdentifierInfo* Id, |
2615 | SourceLocation EllipsisLoc, |
2616 | LambdaCaptureInitKind InitKind, |
2617 | ExprResult Init, |
2618 | ParsedType InitCaptureType, |
2619 | SourceRange ExplicitRange) { |
2620 | Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init, |
2621 | InitCaptureType, ExplicitRange)); |
2622 | } |
2623 | }; |
2624 | |
2625 | } // end namespace clang |
2626 | |
2627 | #endif // LLVM_CLANG_SEMA_DECLSPEC_H |